Add a /conditions/current endpoint
All checks were successful
ci/woodpecker/push/build-image Pipeline was successful

This commit is contained in:
2026-03-19 23:16:26 -05:00
parent 26a52f8c44
commit 8deb4fd12e
10 changed files with 576 additions and 3 deletions

View File

@@ -18,6 +18,7 @@ type Service interface {
LatestObservation(ctx context.Context) (*model.WeatherObservation, error)
LatestHourlyForecast(ctx context.Context) (*model.WeatherForecastRun, error)
LatestActiveAlerts(ctx context.Context) (*model.WeatherAlertRun, error)
CurrentConditions(ctx context.Context) (*core.CurrentConditions, error)
}
type queryRequest struct {
@@ -65,6 +66,19 @@ func Definitions(svc Service) []endpoint.Definition {
endpoint.WithProduces(render.FormatJSON, render.FormatXML, render.FormatText),
endpoint.WithTemplate("alerts_active.txt.tmpl"),
),
endpoint.GET(
"/conditions/current",
bindQuery,
func(ctx context.Context, req queryRequest) (any, error) {
conditions, err := svc.CurrentConditions(ctx)
if err != nil {
return nil, err
}
return response.Envelope{Data: core.CurrentConditionsPayload(conditions, req.Units)}, nil
},
endpoint.WithProduces(render.FormatJSON, render.FormatXML, render.FormatText),
endpoint.WithTemplate("conditions_current.txt.tmpl"),
),
}
}

View File

@@ -16,6 +16,7 @@ import (
"gitea.maximumdirect.net/ejr/feedapi/render"
"gitea.maximumdirect.net/ejr/feedapi/templates"
"gitea.maximumdirect.net/ejr/feedapi/transport/httpx"
"gitea.maximumdirect.net/ejr/weatherapi/internal/core"
"gitea.maximumdirect.net/ejr/weatherfeeder/model"
)
@@ -23,6 +24,7 @@ type fakeService struct {
observation *model.WeatherObservation
forecast *model.WeatherForecastRun
alerts *model.WeatherAlertRun
conditions *core.CurrentConditions
err error
}
@@ -38,6 +40,10 @@ func (s *fakeService) LatestActiveAlerts(context.Context) (*model.WeatherAlertRu
return s.alerts, s.err
}
func (s *fakeService) CurrentConditions(context.Context) (*core.CurrentConditions, error) {
return s.conditions, s.err
}
func TestObservationsRejectUnknownQueryParameter(t *testing.T) {
h := newHandler(t, &fakeService{}, "/observations")
@@ -216,6 +222,218 @@ func TestAlertsUSUnitsKeepSchema(t *testing.T) {
}
}
func TestObservationUSUnitsWithXMLFormat(t *testing.T) {
h := newHandler(t, &fakeService{
observation: &model.WeatherObservation{
StationID: "KSTL",
Timestamp: time.Now().UTC(),
ConditionCode: 1,
TemperatureC: float64Ptr(20),
},
}, "/observations")
w := httptest.NewRecorder()
req := httptest.NewRequest(http.MethodGet, "/observations?format=xml&units=us", nil)
h.ServeHTTP(w, req)
if w.Code != http.StatusOK {
t.Fatalf("expected 200, got %d", w.Code)
}
if !strings.Contains(w.Header().Get("Content-Type"), "application/xml") {
t.Fatalf("expected xml content type, got %q", w.Header().Get("Content-Type"))
}
if strings.Contains(w.Body.String(), "temperatureC") {
t.Fatalf("expected metric field temperatureC to be omitted in XML payload: %s", w.Body.String())
}
if !strings.Contains(w.Body.String(), "temperatureF") {
t.Fatalf("expected US field temperatureF in XML payload: %s", w.Body.String())
}
}
func TestForecastUSUnitsWithXMLFormatUppercaseQuery(t *testing.T) {
h := newHandler(t, &fakeService{
forecast: &model.WeatherForecastRun{
Product: model.ForecastProductHourly,
IssuedAt: time.Now().UTC(),
Periods: []model.WeatherForecastPeriod{{
StartTime: time.Now().UTC(),
EndTime: time.Now().UTC().Add(time.Hour),
ConditionCode: 1,
TemperatureC: float64Ptr(10),
}},
},
}, "/forecast/hourly")
w := httptest.NewRecorder()
req := httptest.NewRequest(http.MethodGet, "/forecast/hourly?format=XML&units=US", nil)
h.ServeHTTP(w, req)
if w.Code != http.StatusOK {
t.Fatalf("expected 200, got %d", w.Code)
}
if !strings.Contains(w.Header().Get("Content-Type"), "application/xml") {
t.Fatalf("expected xml content type, got %q", w.Header().Get("Content-Type"))
}
body := w.Body.String()
if strings.Contains(body, "temperatureC") {
t.Fatalf("expected metric field temperatureC to be omitted in XML payload: %s", body)
}
if !strings.Contains(body, "temperatureF") {
t.Fatalf("expected US field temperatureF in XML payload: %s", body)
}
}
func TestCurrentConditionsNoDataReturnsNullEnvelopeData(t *testing.T) {
h := newHandler(t, &fakeService{}, "/conditions/current")
w := httptest.NewRecorder()
req := httptest.NewRequest(http.MethodGet, "/conditions/current", nil)
h.ServeHTTP(w, req)
if w.Code != http.StatusOK {
t.Fatalf("expected 200, got %d", w.Code)
}
var payload struct {
Data *json.RawMessage `json:"data"`
}
if err := json.Unmarshal(w.Body.Bytes(), &payload); err != nil {
t.Fatalf("decode envelope: %v", err)
}
if payload.Data != nil {
t.Fatalf("expected data null, got %s", string(*payload.Data))
}
}
func TestCurrentConditionsMetricDefaultJSON(t *testing.T) {
h := newHandler(t, &fakeService{
conditions: &core.CurrentConditions{
TemperatureC: float64Ptr(10),
ApparentTemperatureC: float64Ptr(9),
DewpointC: float64Ptr(5),
RelativeHumidityPercent: float64Ptr(75),
WindSpeedKmh: float64Ptr(18),
WindDirectionDegrees: float64Ptr(135),
ConditionCode: 63,
},
}, "/conditions/current")
w := httptest.NewRecorder()
req := httptest.NewRequest(http.MethodGet, "/conditions/current", nil)
h.ServeHTTP(w, req)
if w.Code != http.StatusOK {
t.Fatalf("expected 200, got %d", w.Code)
}
var payload struct {
Data map[string]any `json:"data"`
}
if err := json.Unmarshal(w.Body.Bytes(), &payload); err != nil {
t.Fatalf("decode envelope: %v", err)
}
if _, ok := payload.Data["temperatureC"]; !ok {
t.Fatalf("expected temperatureC in metric payload")
}
if _, ok := payload.Data["temperatureF"]; ok {
t.Fatalf("expected temperatureF omitted in metric payload")
}
if payload.Data["conditionText"] != "Rain" {
t.Fatalf("expected conditionText Rain, got %#v", payload.Data["conditionText"])
}
}
func TestCurrentConditionsUSJSON(t *testing.T) {
h := newHandler(t, &fakeService{
conditions: &core.CurrentConditions{
TemperatureC: float64Ptr(10),
ApparentTemperatureC: float64Ptr(9),
DewpointC: float64Ptr(5),
RelativeHumidityPercent: float64Ptr(75),
WindSpeedKmh: float64Ptr(18),
WindDirectionDegrees: float64Ptr(135),
ConditionCode: 63,
},
}, "/conditions/current")
w := httptest.NewRecorder()
req := httptest.NewRequest(http.MethodGet, "/conditions/current?units=us", nil)
h.ServeHTTP(w, req)
if w.Code != http.StatusOK {
t.Fatalf("expected 200, got %d", w.Code)
}
var payload struct {
Data map[string]any `json:"data"`
}
if err := json.Unmarshal(w.Body.Bytes(), &payload); err != nil {
t.Fatalf("decode envelope: %v", err)
}
if _, ok := payload.Data["temperatureF"]; !ok {
t.Fatalf("expected temperatureF in us payload")
}
if _, ok := payload.Data["temperatureC"]; ok {
t.Fatalf("expected temperatureC omitted in us payload")
}
if _, ok := payload.Data["windSpeedMph"]; !ok {
t.Fatalf("expected windSpeedMph in us payload")
}
if _, ok := payload.Data["windSpeedKmh"]; ok {
t.Fatalf("expected windSpeedKmh omitted in us payload")
}
}
func TestCurrentConditionsXMLAndTextFormats(t *testing.T) {
h := newHandler(t, &fakeService{
conditions: &core.CurrentConditions{
TemperatureC: float64Ptr(10),
WindSpeedKmh: float64Ptr(18),
ConditionCode: 2,
},
}, "/conditions/current")
w := httptest.NewRecorder()
req := httptest.NewRequest(http.MethodGet, "/conditions/current?format=xml&units=us", nil)
h.ServeHTTP(w, req)
if w.Code != http.StatusOK {
t.Fatalf("expected 200, got %d", w.Code)
}
if !strings.Contains(w.Header().Get("Content-Type"), "application/xml") {
t.Fatalf("expected xml content type, got %q", w.Header().Get("Content-Type"))
}
if !strings.Contains(w.Body.String(), "temperatureF") {
t.Fatalf("expected US field temperatureF in XML payload: %s", w.Body.String())
}
w = httptest.NewRecorder()
req = httptest.NewRequest(http.MethodGet, "/conditions/current?format=TEXT", nil)
h.ServeHTTP(w, req)
if w.Code != http.StatusOK {
t.Fatalf("expected 200 for text request, got %d", w.Code)
}
if !strings.Contains(w.Header().Get("Content-Type"), "text/plain") {
t.Fatalf("expected text/plain content type, got %q", w.Header().Get("Content-Type"))
}
if !strings.Contains(w.Body.String(), "Conditions text") {
t.Fatalf("expected rendered text template body, got %q", w.Body.String())
}
}
func TestCurrentConditionsRejectUnknownQueryParameter(t *testing.T) {
h := newHandler(t, &fakeService{}, "/conditions/current")
w := httptest.NewRecorder()
req := httptest.NewRequest(http.MethodGet, "/conditions/current?bogus=1", nil)
h.ServeHTTP(w, req)
if w.Code != http.StatusBadRequest {
t.Fatalf("expected 400, got %d", w.Code)
}
}
func newHandler(t *testing.T, svc Service, path string) http.Handler {
t.Helper()
@@ -250,9 +468,10 @@ func testRenderers(t *testing.T) *render.Registry {
tmplReg := templates.NewRegistry()
for name, body := range map[string]string{
"observations.txt.tmpl": "Observation text",
"forecast_hourly.txt.tmpl": "Forecast text",
"alerts_active.txt.tmpl": "Alerts text",
"observations.txt.tmpl": "Observation text",
"forecast_hourly.txt.tmpl": "Forecast text",
"alerts_active.txt.tmpl": "Alerts text",
"conditions_current.txt.tmpl": "Conditions text",
} {
tmpl, err := template.New(name).Parse(body)
if err != nil {

View File

@@ -36,6 +36,51 @@ FROM observations
ORDER BY observed_at DESC, event_emitted_at DESC
LIMIT 1`
queryCurrentConditions = `
WITH windowed AS (
SELECT
temperature_c,
apparent_temperature_c,
dewpoint_c,
relative_humidity_percent,
wind_speed_kmh,
wind_direction_degrees,
condition_code,
is_day,
observed_at
FROM observations
WHERE observed_at > CURRENT_TIMESTAMP - make_interval(mins => $1)
)
SELECT
COUNT(*) AS sample_count,
AVG(temperature_c) AS temperature_c,
AVG(apparent_temperature_c) AS apparent_temperature_c,
AVG(dewpoint_c) AS dewpoint_c,
AVG(relative_humidity_percent) AS relative_humidity_percent,
AVG(wind_speed_kmh) AS wind_speed_kmh,
CASE
WHEN atan2d(
AVG(sind(wind_direction_degrees)),
AVG(cosd(wind_direction_degrees))
) < 0
THEN atan2d(
AVG(sind(wind_direction_degrees)),
AVG(cosd(wind_direction_degrees))
) + 360.0
ELSE atan2d(
AVG(sind(wind_direction_degrees)),
AVG(cosd(wind_direction_degrees))
)
END AS wind_direction_degrees,
MAX(condition_code) AS condition_code,
(
SELECT is_day
FROM windowed
ORDER BY observed_at DESC
LIMIT 1
) AS is_day
FROM windowed`
queryObservationPresentWeather = `
SELECT weather_index, raw_text
FROM observation_present_weather
@@ -193,6 +238,33 @@ func (r *Repository) LatestObservation(ctx context.Context) (*model.WeatherObser
return &obs, nil
}
func (r *Repository) CurrentConditions(ctx context.Context, observationWindowMinutes int) (*core.CurrentConditions, error) {
if r == nil || r.db == nil {
return nil, fmt.Errorf("postgres repository is not configured")
}
var row currentConditionsRow
err := r.db.QueryRowContext(ctx, queryCurrentConditions, observationWindowMinutes).Scan(
&row.SampleCount,
&row.TemperatureC,
&row.ApparentTemperatureC,
&row.DewpointC,
&row.RelativeHumidityPercent,
&row.WindSpeedKmh,
&row.WindDirectionDegrees,
&row.ConditionCode,
&row.IsDay,
)
if errors.Is(err, sql.ErrNoRows) {
return nil, nil
}
if err != nil {
return nil, fmt.Errorf("query current conditions: %w", err)
}
return mapCurrentConditionsRow(row), nil
}
func (r *Repository) LatestHourlyForecast(ctx context.Context) (*model.WeatherForecastRun, error) {
if r == nil || r.db == nil {
return nil, fmt.Errorf("postgres repository is not configured")
@@ -419,6 +491,40 @@ type observationParentRow struct {
ApparentTemperatureC sql.NullFloat64
}
type currentConditionsRow struct {
SampleCount int64
TemperatureC sql.NullFloat64
ApparentTemperatureC sql.NullFloat64
DewpointC sql.NullFloat64
RelativeHumidityPercent sql.NullFloat64
WindSpeedKmh sql.NullFloat64
WindDirectionDegrees sql.NullFloat64
ConditionCode sql.NullInt64
IsDay sql.NullBool
}
func mapCurrentConditionsRow(row currentConditionsRow) *core.CurrentConditions {
if row.SampleCount == 0 {
return nil
}
conditionCode := model.WMOUnknown
if row.ConditionCode.Valid {
conditionCode = model.WMOCode(row.ConditionCode.Int64)
}
return &core.CurrentConditions{
TemperatureC: float64Ptr(row.TemperatureC),
ApparentTemperatureC: float64Ptr(row.ApparentTemperatureC),
DewpointC: float64Ptr(row.DewpointC),
RelativeHumidityPercent: float64Ptr(row.RelativeHumidityPercent),
WindSpeedKmh: float64Ptr(row.WindSpeedKmh),
WindDirectionDegrees: float64Ptr(row.WindDirectionDegrees),
ConditionCode: conditionCode,
IsDay: boolPtr(row.IsDay),
}
}
func mapObservationParentRow(row observationParentRow) model.WeatherObservation {
return model.WeatherObservation{
StationID: stringValue(row.StationID),

View File

@@ -110,3 +110,54 @@ func TestAttachAlertReferencesPreservesOrder(t *testing.T) {
t.Fatalf("unexpected second alert references: %+v", out[1].References)
}
}
func TestMapCurrentConditionsRowNoSamplesReturnsNil(t *testing.T) {
got := mapCurrentConditionsRow(currentConditionsRow{
SampleCount: 0,
})
if got != nil {
t.Fatalf("expected nil for empty sample window, got %+v", got)
}
}
func TestMapCurrentConditionsRowMapsFields(t *testing.T) {
isDay := true
got := mapCurrentConditionsRow(currentConditionsRow{
SampleCount: 12,
TemperatureC: sql.NullFloat64{Float64: 15.5, Valid: true},
ApparentTemperatureC: sql.NullFloat64{Float64: 14.2, Valid: true},
DewpointC: sql.NullFloat64{Float64: 10.1, Valid: true},
RelativeHumidityPercent: sql.NullFloat64{Float64: 72, Valid: true},
WindSpeedKmh: sql.NullFloat64{Float64: 24.8, Valid: true},
WindDirectionDegrees: sql.NullFloat64{Float64: 182.5, Valid: true},
ConditionCode: sql.NullInt64{Int64: 65, Valid: true},
IsDay: sql.NullBool{Bool: isDay, Valid: true},
})
if got == nil {
t.Fatalf("expected mapped current conditions")
}
if got.TemperatureC == nil || *got.TemperatureC != 15.5 {
t.Fatalf("expected temperature pointer 15.5, got %v", got.TemperatureC)
}
if got.ApparentTemperatureC == nil || *got.ApparentTemperatureC != 14.2 {
t.Fatalf("expected apparent temp pointer 14.2, got %v", got.ApparentTemperatureC)
}
if got.DewpointC == nil || *got.DewpointC != 10.1 {
t.Fatalf("expected dewpoint pointer 10.1, got %v", got.DewpointC)
}
if got.RelativeHumidityPercent == nil || *got.RelativeHumidityPercent != 72 {
t.Fatalf("expected rh pointer 72, got %v", got.RelativeHumidityPercent)
}
if got.WindSpeedKmh == nil || *got.WindSpeedKmh != 24.8 {
t.Fatalf("expected wind speed pointer 24.8, got %v", got.WindSpeedKmh)
}
if got.WindDirectionDegrees == nil || *got.WindDirectionDegrees != 182.5 {
t.Fatalf("expected wind direction pointer 182.5, got %v", got.WindDirectionDegrees)
}
if got.ConditionCode != 65 {
t.Fatalf("expected condition code 65, got %d", got.ConditionCode)
}
if got.IsDay == nil || !*got.IsDay {
t.Fatalf("expected isDay pointer true, got %v", got.IsDay)
}
}