Files
weatherfeeder/internal/sources/openweather/observation.go
Eric Rakestraw 123e8ff763
All checks were successful
ci/woodpecker/push/build-image Pipeline was successful
Moved the standards package out of internal/ so it can be imported by downstream consumers.
2026-02-08 09:15:07 -06:00

95 lines
2.2 KiB
Go

// FILE: ./internal/sources/openweather/observation.go
package openweather
import (
"context"
"encoding/json"
"fmt"
"time"
"gitea.maximumdirect.net/ejr/feedkit/config"
"gitea.maximumdirect.net/ejr/feedkit/event"
owcommon "gitea.maximumdirect.net/ejr/weatherfeeder/internal/providers/openweather"
"gitea.maximumdirect.net/ejr/weatherfeeder/internal/sources/common"
"gitea.maximumdirect.net/ejr/weatherfeeder/standards"
)
type ObservationSource struct {
http *common.HTTPSource
}
func NewObservationSource(cfg config.SourceConfig) (*ObservationSource, error) {
const driver = "openweather_observation"
hs, err := common.NewHTTPSource(driver, cfg, "application/json")
if err != nil {
return nil, err
}
if err := owcommon.RequireMetricUnits(hs.URL); err != nil {
return nil, fmt.Errorf("%s %q: %w", hs.Driver, hs.Name, err)
}
return &ObservationSource{http: hs}, nil
}
func (s *ObservationSource) Name() string { return s.http.Name }
func (s *ObservationSource) Kind() event.Kind { return event.Kind("observation") }
func (s *ObservationSource) Poll(ctx context.Context) ([]event.Event, error) {
if err := owcommon.RequireMetricUnits(s.http.URL); err != nil {
return nil, fmt.Errorf("%s %q: %w", s.http.Driver, s.http.Name, err)
}
raw, meta, err := s.fetchRaw(ctx)
if err != nil {
return nil, err
}
var effectiveAt *time.Time
if !meta.ParsedTimestamp.IsZero() {
t := meta.ParsedTimestamp.UTC()
effectiveAt = &t
}
emittedAt := time.Now().UTC()
eventID := common.ChooseEventID("", s.http.Name, effectiveAt, emittedAt)
return common.SingleRawEvent(
s.Kind(),
s.http.Name,
standards.SchemaRawOpenWeatherCurrentV1,
eventID,
emittedAt,
effectiveAt,
raw,
)
}
// ---- RAW fetch + minimal metadata decode ----
type openWeatherMeta struct {
Dt int64 `json:"dt"` // unix seconds, UTC
ParsedTimestamp time.Time `json:"-"`
}
func (s *ObservationSource) fetchRaw(ctx context.Context) (json.RawMessage, openWeatherMeta, error) {
raw, err := s.http.FetchJSON(ctx)
if err != nil {
return nil, openWeatherMeta{}, err
}
var meta openWeatherMeta
if err := json.Unmarshal(raw, &meta); err != nil {
return raw, openWeatherMeta{}, nil
}
if meta.Dt > 0 {
meta.ParsedTimestamp = time.Unix(meta.Dt, 0).UTC()
}
return raw, meta, nil
}