diff --git a/README.md b/README.md index f3f4df6..28a5517 100644 --- a/README.md +++ b/README.md @@ -29,8 +29,10 @@ current working directory. - [Operations guide](docs/operations.md) - [Troubleshooting guide](docs/troubleshooting.md) - [Example configs](examples/) +- [Go consumer guide](docs/consumers/api.md) - [Event wire contract](docs/integrations/events.md) - [Postgres table contract](docs/integrations/postgres.md) +- [Feedkit integration notes](docs/integrations/feedkit.md) - [NWS integration notes](docs/integrations/nws.md) - [SPC integration notes](docs/integrations/spc.md) - [Open-Meteo integration notes](docs/integrations/openmeteo.md) diff --git a/docs/consumers/api.md b/docs/consumers/api.md new file mode 100644 index 0000000..3813a5e --- /dev/null +++ b/docs/consumers/api.md @@ -0,0 +1,92 @@ +# Consumer API Guide + +## Purpose + +This guide is for developers and LLM coding agents integrating `weatherfeeder` +from another Go codebase. + +`weatherfeeder` is primarily a daemon, not an SDK. Its public integration +surface is intentionally narrow: + +- `model`: canonical weather payload structs. +- `standards`: schema strings, event kind strings, and shared WMO constants. +- JSON event output from stdout and NATS sinks. +- Postgres tables written by the optional Postgres sink. + +Packages under `internal/` are implementation details and are not public +integration surfaces. + +## Recommended Workflow + +Consumers should switch on the event `schema` value and decode `payload` into +the matching `model` type. + +Minimal example: + +```go +package consumer + +import ( + "encoding/json" + "fmt" + + "gitea.maximumdirect.net/ejr/weatherfeeder/model" + "gitea.maximumdirect.net/ejr/weatherfeeder/standards" +) + +type Event struct { + ID string `json:"id"` + Kind string `json:"kind"` + Schema string `json:"schema"` + Payload json.RawMessage `json:"payload"` +} + +func Decode(payload []byte) (any, error) { + var evt Event + if err := json.Unmarshal(payload, &evt); err != nil { + return nil, err + } + + switch evt.Schema { + case standards.SchemaWeatherObservationV1: + var out model.WeatherObservation + return &out, json.Unmarshal(evt.Payload, &out) + case standards.SchemaWeatherForecastV1: + var out model.WeatherForecastRun + return &out, json.Unmarshal(evt.Payload, &out) + case standards.SchemaWeatherForecastDiscussionV1: + var out model.WeatherForecastDiscussion + return &out, json.Unmarshal(evt.Payload, &out) + case standards.SchemaWeatherStoryV1: + var out model.WeatherStoryRun + return &out, json.Unmarshal(evt.Payload, &out) + case standards.SchemaWeatherAlertV1: + var out model.WeatherAlertRun + return &out, json.Unmarshal(evt.Payload, &out) + case standards.SchemaWeatherOutlookV1: + var out model.WeatherOutlookRun + return &out, json.Unmarshal(evt.Payload, &out) + default: + return nil, fmt.Errorf("unsupported weatherfeeder schema %q", evt.Schema) + } +} +``` + +## Consumer Responsibilities + +- Treat event IDs as opaque. +- Treat absent `omitempty` fields as unknown, not zero. +- Prefer schema constants from `standards` over string literals in Go code. +- Expect canonical numeric measurements to use metric units. +- Expect canonical timestamps from normalizers to be UTC unless a field-specific + contract says otherwise. +- Handle additive fields within the same schema version. +- Do not import `internal/...` packages. + +## Canonical References + +- Public payload package: [`pkg-model.md`](pkg-model.md). +- Public constants package: [`pkg-standards.md`](pkg-standards.md). +- JSON event wire contract: [`../integrations/events.md`](../integrations/events.md). +- Postgres table contract: [`../integrations/postgres.md`](../integrations/postgres.md). +- Runtime and adapter architecture: [`../policy/architecture.md`](../policy/architecture.md). diff --git a/docs/consumers/pkg-model.md b/docs/consumers/pkg-model.md new file mode 100644 index 0000000..6d3ccc7 --- /dev/null +++ b/docs/consumers/pkg-model.md @@ -0,0 +1,63 @@ +# Package `model` + +## Import Path + +```go +import "gitea.maximumdirect.net/ejr/weatherfeeder/model" +``` + +## Purpose + +Package `model` defines `weatherfeeder`'s canonical weather payload structs. +These structs are emitted as the `payload` of canonical `weather.*.v1` events +and are also the domain types consumed by downstream applications such as +`weatherapi`. + +The JSON field tags on these structs are part of the wire contract. For the full +field-by-field JSON contract, use the [event wire contract](../integrations/events.md). + +## Payload Types + +Current canonical schema families map to these public types: + +| Schema | Primary type | +|---|---| +| `weather.observation.v1` | `WeatherObservation` | +| `weather.forecast.v1` | `WeatherForecastRun` | +| `weather.forecast_discussion.v1` | `WeatherForecastDiscussion` | +| `weather.weather_story.v1` | `WeatherStoryRun` | +| `weather.alert.v1` | `WeatherAlertRun` | +| `weather.outlook.v1` | `WeatherOutlookRun` | + +Related child types include: + +- `WeatherObservationPresentWeather` +- `WeatherForecastPeriod` +- `WeatherForecastDiscussionSection` +- `WeatherStory` +- `WeatherAlert` +- `WeatherAlertReference` +- `WeatherOutlook` +- `WMOCode` + +## Wire And Compatibility Rules + +- JSON tags define canonical payload field names. +- Pointer fields and fields tagged `omitempty` are optional on the wire. +- Missing optional fields mean unknown or not applicable. +- Canonical measurements use metric units. +- Canonical timestamps are `time.Time` values encoded by Go's JSON encoder. +- Normalized canonical timestamps are UTC unless a field-specific contract says + otherwise. +- Additive fields are compatible within a schema version. +- Removing, renaming, or changing the meaning of a field requires a new schema + identifier. + +## Boundaries + +`model` should not depend on source adapters, sinks, SQL column names, provider +HTTP shapes, or runtime configuration. + +Consumers should not rely on packages under `internal/...`. Use `model` with +schema constants from [`standards`](pkg-standards.md) and the JSON contract in +[`docs/integrations/events.md`](../integrations/events.md). diff --git a/docs/consumers/pkg-standards.md b/docs/consumers/pkg-standards.md new file mode 100644 index 0000000..1143fa5 --- /dev/null +++ b/docs/consumers/pkg-standards.md @@ -0,0 +1,90 @@ +# Package `standards` + +## Import Path + +```go +import "gitea.maximumdirect.net/ejr/weatherfeeder/standards" +``` + +## Purpose + +Package `standards` defines stable identifiers and shared weather constants used +by `weatherfeeder` producers and Go consumers. + +Use this package when switching on event schemas, comparing event kinds, or +working with canonical WMO condition codes. + +## Event Kind Constants + +Current event kind constants are: + +| Constant | Value | +|---|---| +| `KindObservation` | `observation` | +| `KindForecast` | `forecast` | +| `KindForecastDiscussion` | `forecast_discussion` | +| `KindWeatherStory` | `weather_story` | +| `KindAlert` | `alert` | +| `KindOutlook` | `outlook` | + +These are plain string constants. Convert them at adapter boundaries when using +feedkit's `event.Kind` type. + +## Canonical Schema Constants + +Canonical schemas emitted after normalization: + +| Constant | Value | +|---|---| +| `SchemaWeatherObservationV1` | `weather.observation.v1` | +| `SchemaWeatherForecastV1` | `weather.forecast.v1` | +| `SchemaWeatherForecastDiscussionV1` | `weather.forecast_discussion.v1` | +| `SchemaWeatherStoryV1` | `weather.weather_story.v1` | +| `SchemaWeatherAlertV1` | `weather.alert.v1` | +| `SchemaWeatherOutlookV1` | `weather.outlook.v1` | + +## Raw Schema Constants + +Raw source schemas emitted by current registered sources: + +| Constant | Value | +|---|---| +| `SchemaRawNWSObservationV1` | `raw.nws.observation.v1` | +| `SchemaRawOpenMeteoCurrentV1` | `raw.openmeteo.current.v1` | +| `SchemaRawOpenWeatherCurrentV1` | `raw.openweather.current.v1` | +| `SchemaRawNWSHourlyForecastV1` | `raw.nws.hourly.forecast.v1` | +| `SchemaRawNWSNarrativeForecastV1` | `raw.nws.narrative.forecast.v1` | +| `SchemaRawNWSForecastDiscussionV1` | `raw.nws.forecast_discussion.v1` | +| `SchemaRawNWSWeatherStoriesV1` | `raw.nws.weatherstories.v1` | +| `SchemaRawOpenMeteoHourlyForecastV1` | `raw.openmeteo.hourly.forecast.v1` | +| `SchemaRawNWSAlertsV1` | `raw.nws.alerts.v1` | +| `SchemaRawSPCConvectiveOutlookV1` | `raw.spc.convective_outlook.v1` | + +Additional raw schema constant: + +| Constant | Value | +|---|---| +| `SchemaRawOpenWeatherHourlyForecastV1` | `raw.openweather.hourly.forecast.v1` | + +`SchemaRawOpenWeatherHourlyForecastV1` exists in code, but no current registered +source emits it. Consumers should not expect that raw schema unless a later +registered source documents it as part of the current event contract. + +## WMO Constants And Text + +`standards` also defines the canonical `WMOCode` vocabulary and text helpers +used by normalized observations and forecasts. + +Consumer guidance: + +- Treat `WMOUnknown` as unknown condition data. +- Observation `conditionCode` is required in the current event contract. +- Forecast period `conditionCode` is optional because some forecast products do + not provide a meaningful WMO condition. +- Prefer WMO constants and helper functions from this package instead of + duplicating code tables in consumers. + +## Boundaries + +`standards` is provider-agnostic. Provider-specific parsing belongs in +`weatherfeeder` internals, not in this package and not in consumers. diff --git a/docs/integrations/feedkit.md b/docs/integrations/feedkit.md new file mode 100644 index 0000000..159eee2 --- /dev/null +++ b/docs/integrations/feedkit.md @@ -0,0 +1,106 @@ +# Feedkit Integration + +## Purpose + +This document describes the feedkit runtime behavior that `weatherfeeder` +currently depends on. It is for maintainers and LLM coding agents changing +runtime wiring, config behavior, source construction, processing, routing, or +sink behavior. + +Weather-domain behavior belongs in `weatherfeeder`. Generic daemon mechanics +belong to feedkit. + +## Current Dependency + +`weatherfeeder` imports feedkit as its daemon framework dependency. The exact +module version is declared in `go.mod`. + +Feedkit provides: + +- YAML config loading and validation. +- Source, processor, and sink registries. +- HTTP source helper behavior. +- Scheduler polling. +- Normalize and dedupe processors. +- Route compilation and sink dispatch. +- Built-in stdout, NATS, and Postgres sink mechanics. + +## Config Contract + +`cmd/weatherfeeder` calls feedkit config loading for `config.yml` in the current +working directory. + +Implemented behavior relied on by weatherfeeder docs and tests: + +- Top-level config contains `sources`, `sinks`, and optional `routes`. +- Config struct fields are decoded strictly, so misspelled struct fields fail + startup. +- Driver-specific `params` maps are decoded generically and validated by the + source or sink constructor that consumes them. +- Source `kinds` can be validated against a source's advertised `Kinds()`. + +## Source And HTTP Contract + +Most weatherfeeder sources use feedkit's single-document HTTP source helper for: + +- request construction; +- `User-Agent` and `Accept` headers; +- optional conditional GET validators; +- response body size limits; +- context-aware HTTP work; +- unchanged `304 Not Modified` responses that emit no events. + +The SPC convective outlook source fetches multiple documents itself, but it uses +feedkit transport helpers for HTTP clients and response body limits. + +## Scheduler And Processing Contract + +Weatherfeeder builds feedkit scheduler jobs from source configs. Current source +drivers are polling drivers and use the configured `every` interval. + +Events flow through a feedkit pipeline in this order: + +1. normalize processor; +2. dedupe processor. + +The normalize processor is configured with `RequireMatch=false`, so unmatched +schemas pass through unchanged. Weatherfeeder registers its built-in normalizers +and owns the provider-to-canonical mapping. + +The dedupe processor stores a bounded in-memory set of recent event IDs. The +bound is configured in `cmd/weatherfeeder`. + +## Dispatch And Sink Contract + +Feedkit compiles routes from config and dispatches processed events to matching +sinks. If `routes` is omitted, every configured sink receives every event kind. + +Feedkit owns sink fanout mechanics, per-sink workers, queueing, context-aware +shutdown, and sink error logging. Weatherfeeder owns the event kinds and schemas +that make routes meaningful. + +Built-in feedkit sinks used by weatherfeeder: + +- `stdout`: validates and writes JSON events to stdout. +- `nats`: publishes JSON events to a configured subject. +- generic `postgres` sink factory: opens the database, ensures tables/indexes, + runs transactions, inserts mapped rows, and prunes when configured. + +Weatherfeeder supplies its Postgres table schema and event mapper to feedkit's +Postgres sink factory. The table contract is documented in +[`postgres.md`](postgres.md). + +## Boundaries + +Do not move weather-domain policy into feedkit. Weatherfeeder owns: + +- provider source drivers; +- raw and canonical schema constants; +- event kind meaning; +- canonical payload structs; +- normalizers; +- Postgres table shape and row mapping. + +Do not duplicate generic feedkit mechanics in weatherfeeder unless there is a +narrow weather-specific reason. Runtime composition details are documented in +[`../internal/runtime.md`](../internal/runtime.md). diff --git a/docs/policy/development.md b/docs/policy/development.md index bfddd84..c617278 100644 --- a/docs/policy/development.md +++ b/docs/policy/development.md @@ -24,7 +24,8 @@ docs, not here. normalizers. - `internal/sinks/postgres/`: weatherfeeder-owned Postgres schema and canonical event mapper. -- `docs/`: current behavior, policies, integration contracts, and roadmap files. +- `docs/`: current behavior, consumer guides, integration contracts, policies, + and roadmap files. - `examples/`: maintained, copyable configuration examples. ## Build And Test @@ -209,6 +210,7 @@ When behavior changes, update the canonical docs in the same change: - CLI behavior: `docs/cli.md`; - operations and recovery: `docs/operations.md`; - troubleshooting: `docs/troubleshooting.md`; +- public Go package consumption: `docs/consumers/`; - external contracts: `docs/integrations/`; - internal component behavior: `docs/internal/`; - copyable configs: `examples/`. diff --git a/docs/policy/documentation.md b/docs/policy/documentation.md index d9ed7fa..9ace9dc 100644 --- a/docs/policy/documentation.md +++ b/docs/policy/documentation.md @@ -2,12 +2,13 @@ ## Purpose -Project documentation must help four audiences: +Project documentation must help five audiences: 1. users who need to run the application; 2. administrators/operators who need to configure and operate it; 3. developers who need to understand and change it safely; -4. LLM coding agents that need clear scope, boundaries, and invariants. +4. LLM coding agents that need clear scope, boundaries, and invariants; +5. developers and LLM coding agents integrating this project from another codebase. Docs should be accurate, concise, task-oriented, and organized by audience. Prefer links to canonical docs over repetition. @@ -42,11 +43,14 @@ Canonical homes: - project purpose and quickstart: `README.md` - development principles: `docs/policy/architecture.md` +- public HTTP API reference: `docs/api.md` - configuration reference: `docs/config.md` - CLI reference: `docs/cli.md` - operations and recovery: `docs/operations.md` - troubleshooting: `docs/troubleshooting.md` +- public API/package consumer guidance: `docs/consumers/` - implemented internals: `docs/internal/` +- external protocol, service, and file-format contracts: `docs/integrations/` - future work: `docs/roadmap/` - contributor workflow: `docs/policy/development.md` - copyable examples: `examples/` @@ -106,7 +110,7 @@ Recommended: - `examples/` - `docs/policy/development.md` -### Modular, staged, service-oriented, or orchestration application +### Modular, service-oriented, or orchestration application Required: - `docs/cli.md`, if CLI-based @@ -119,6 +123,31 @@ Recommended: - `docs/troubleshooting.md` - validated examples under `examples/` +### Public HTTP API service + +Required: +- `docs/api.md` +- `docs/cli.md`, if CLI-based +- `docs/config.md`, if config-driven +- `docs/operations.md` +- `docs/internal/` +- `docs/policy/development.md` + +Recommended: +- `docs/troubleshooting.md` +- `docs/consumers/`, for task-oriented client integration guides +- `docs/integrations/`, for upstream/downstream service contracts +- validated examples under `examples/` + +### Project with public packages or consumer APIs + +Required: +- `docs/consumers/api.md` +- one `docs/consumers/pkg-.md` file per public package, if public packages exist + +Recommended: +- copyable consumer examples under `examples/`, if practical + ## Required Documents ### README.md @@ -161,6 +190,32 @@ It should include: For small projects, this file may be brief. It may simply state that the project is intentionally narrow, monolithic, and dependency-light. +### docs/api.md + +**Audience:** external HTTP API consumers, developers, LLM coding agents integrating by HTTP + +Required for projects whose primary public interface is HTTP. + +`docs/api.md` is the canonical public HTTP API contract. It should be normative for external consumers and should not be duplicated by README, operations docs, consumer guides, or integration docs. + +It should include: + +1. base URL conventions; +2. authentication and authorization behavior, if implemented; +3. response envelope; +4. supported media types and content negotiation behavior; +5. shared query parameters; +6. endpoint reference grouped by route family; +7. request parameters and validation rules; +8. response fields, units, nullability, and optionality; +9. error response shape and status codes; +10. pagination, caching, rate-limit, idempotency, and retry behavior, if implemented; +11. compact request and response examples. + +It must document only implemented endpoints and behavior. Planned endpoints, proposed fields, future filters, and experimental response shapes belong only under `docs/roadmap/`. + +For HTTP API projects, `docs/consumers/` may provide task-oriented client integration guides, but those guides should link to `docs/api.md` for the authoritative endpoint contract. + ### docs/policy/development.md **Audience:** developers, LLM coding agents @@ -175,7 +230,7 @@ It should include: - dependency policy; - how to add config fields; - how to add CLI flags; -- how to add stages/modules/adapters, if applicable; +- how to add modules or adapters, if applicable; - how to update examples; - documentation update expectations. @@ -216,7 +271,7 @@ Explain when commands are useful, not just their syntax. **Audience:** administrators, operators -Required for applications that maintain state, support resume behavior, run multiple stages, write durable artifacts, use remote storage, or require recovery procedures. +Required for applications that maintain state, support resume behavior, run multi-step workflows, write durable artifacts, use remote storage, or require recovery procedures. It should cover: @@ -244,11 +299,40 @@ Each entry should include: - safe fix; - relevant links. +### docs/consumers/ + +**Audience:** developers and LLM coding agents integrating this project from another codebase + +Required for projects with public packages, SDKs, client APIs, plugin APIs, or other application-facing integration surfaces. + +This directory describes how an external codebase should consume the project's public API. It should be task-oriented and copyable where useful. It is not the place for internal implementation details or operator procedures. + +For projects whose public API is HTTP, `docs/consumers/` is not required, and it should not duplicate the endpoint reference in `docs/api.md`. If present, it may provide practical integration workflows, client-specific examples, or migration notes that link back to `docs/api.md`. + +`docs/consumers/api.md` should provide the consumer-facing overview and primary implementation workflow. It should include: + +1. intended consumer audience and use cases; +2. required inputs supplied by operators or deployment configuration; +3. recommended public package or API workflow; +4. minimal copyable example; +5. consumer responsibilities and boundaries; +6. retry, idempotency, or status behavior, if applicable; +7. links to package-specific docs and canonical integration contracts. + +Package-specific docs should be named `pkg-.md` and should include: + +1. import path; +2. intended use cases; +3. primary types and functions needed by consumers; +4. minimal examples; +5. validation, error, retry, and boundary behavior; +6. links to canonical file-format or wire-protocol contracts. + ### docs/internal/ **Audience:** developers, LLM coding agents -Required for modular, staged, service-oriented, or orchestration projects. +Required for modular, service-oriented, or orchestration projects. This directory describes implemented internal components. It is not the roadmap. @@ -289,7 +373,9 @@ Roadmap docs should not be confused with current behavior. Required for projects that depend on external CLIs, APIs, services, protocols, or file formats where the integration contract is important to maintain. -This directory contains concise, versioned reference notes for external integration contracts. It should document only the parts of the external system that this project actually uses. +This directory contains concise, versioned reference notes for external integration contracts. It should document only the parts of the external system that this project actually uses or exposes. + +For public HTTP API services, `docs/integrations/` should document upstream, downstream, storage, protocol, or runtime contracts that the service depends on or bridges. It should not become a second copy of the public HTTP endpoint reference; that belongs in `docs/api.md`. Use one file per integration where useful. @@ -346,8 +432,10 @@ Before merging documentation changes, verify: - README is concise and orientation-focused. - `docs/policy/architecture.md` describes development principles. +- `docs/api.md` is the canonical HTTP contract for HTTP API services. - Future work appears only under `docs/roadmap/`. - User-facing docs avoid unnecessary internals. +- Consumer-facing docs explain public APIs without duplicating HTTP endpoint or integration contracts. - Developer-facing docs preserve boundaries and invariants. - Config examples match the schema. - CLI examples match real commands and flags. diff --git a/docs/roadmap/audit.md b/docs/roadmap/audit.md index a63e122..963125e 100644 --- a/docs/roadmap/audit.md +++ b/docs/roadmap/audit.md @@ -1,558 +1,82 @@ -# Code Quality And Deduplication Audit +# Code Quality Audit Snapshot -## Executive Summary +## Purpose -`weatherfeeder` is in good shape for a limited cleanup pass before the next major release. The current architecture is coherent: runtime composition is thin, provider fetching lives in source adapters, provider-specific parsing lives under `internal/providers`, canonical mapping lives in normalizers, and Postgres persistence is isolated under `internal/sinks/postgres`. +This roadmap file records the current cleanup audit status for `weatherfeeder`. +It is not current-behavior documentation and should not be used as the source of +truth for implemented features. Current behavior belongs in README, config, +operations, internal, consumer, and integration docs. -The codebase does not show a major architectural risk that would require broad redesign. Most duplication is the predictable result of recent feature growth across sources, canonical payloads, and persistence tables. The highest-value cleanup should be narrow and behavior-preserving. +## Current Assessment -Top refactoring targets: +`weatherfeeder` remains architecturally coherent: -1. Source adapter HTTP/config scaffolding: single-document sources and the SPC multi-document source share config, request, effective-time, and event-envelope policy in similar but not identical forms. -2. Postgres mapper boilerplate: parent envelope columns, UTC/null conversion, required-field checks, and child-row construction are repeated across every canonical product mapper. -3. Event kind and driver-name strings: event kinds and source driver names are repeated across registries, source implementations, tests, examples, and docs without code constants comparable to the centralized schema constants. +- `cmd/weatherfeeder` is runtime composition. +- Source adapters fetch upstream provider payloads. +- Provider helpers isolate provider-specific parsing. +- Normalizers map raw schemas into canonical `model` payloads. +- `standards` owns schema, kind, and WMO constants. +- Postgres sink mapping is isolated under `internal/sinks/postgres`. +- Feedkit owns generic config, scheduling, processing, dispatch, and sink + mechanics. -Recommended posture: perform a limited cleanup pass in small commits. Avoid broad framework changes, generic workflow engines, plugin systems, or ORM-like abstractions. +The highest-value completed cleanup work since the original audit includes: -## Repository Map Reviewed +- event kind constants in `standards`; +- source driver constants in provider source packages; +- source registry tests derived from registered drivers; +- shared HTTP config parsing for multi-document sources; +- config/example load coverage; +- shallow documentation consistency tests for current schemas and source + drivers; +- consumer documentation for public Go packages. -Inspected directories and packages: +## Remaining Cleanup Opportunities -- `cmd/weatherfeeder`: runtime composition, sample config, config-load and pipeline tests. -- `internal/sources`: source registry and provider source adapters for NWS, Open-Meteo, OpenWeather, and SPC. -- `internal/providers`: provider-specific parsing helpers for NWS, Open-Meteo, OpenWeather, and SPC. -- `internal/normalizers`: built-in normalizer registration, common helpers, and provider normalizers. -- `internal/sinks/postgres`: weatherfeeder-owned table schema and canonical-event mapper. -- `internal/geo`: point-in-geometry helper used by SPC outlook normalization. -- `model`: canonical payload structs. -- `standards`: schema and WMO constants. -- `examples`: maintained config examples. -- `docs`: policy, config, CLI, operations, troubleshooting, internal docs, integration docs, and `docs/roadmap/future.md`. +### Postgres Mapper Boilerplate -Major execution paths reviewed: +The Postgres mapper still repeats event envelope values and parent-row map +patterns across canonical product families. -- daemon startup from `cmd/weatherfeeder/main.go`; -- source driver registration and source construction; -- source polling for single-document HTTP products and SPC multi-document bundles; -- normalizer registration and raw-schema dispatch; -- raw-to-canonical mapping for observations, forecasts, discussions, weather stories, alerts, and outlooks; -- Postgres schema and write mapping; -- maintained config loading tests. +Recommended next action: implement the Postgres mapper envelope cleanup in +[`cleanup.md`](cleanup.md) without changing table contracts or mapper behavior. -Important areas not deeply inspected: +### Package-Local Fixture Helpers -- Feedkit internals were not audited because they are a dependency and outside this repository's ownership boundary. -- Live upstream service behavior was not tested; this audit used local source inspection, fixtures, and existing docs. -- Full test execution was not run because this is a report-only task and no code behavior changed. +Some tests still use package-local fixture-loading helpers that may be +consolidated where multiple files in the same package duplicate the same logic. -## High-Confidence Deduplication Opportunities +Recommended next action: consolidate only obvious same-package duplication. Do +not add cross-package test helper packages. -### 1. Centralize Repeated Source HTTP And Config Scaffolding +### Literal Sweep -Affected files/packages: +Some string literals remain intentional in docs, YAML examples, and negative +tests. Internal code and tests can still be reviewed for opportunities to use +existing constants where that reduces drift risk. -- `internal/sources/nws/observation.go` -- `internal/sources/nws/alerts.go` -- `internal/sources/nws/forecast_common.go` -- `internal/sources/nws/forecast_discussion.go` -- `internal/sources/nws/weatherstories.go` -- `internal/sources/openmeteo/observation.go` -- `internal/sources/openmeteo/forecast.go` -- `internal/sources/openweather/observation.go` -- `internal/sources/spc/convective_outlook.go` -- `docs/internal/sources.md` -- `docs/config.md` +Recommended next action: perform a final literal sweep only after higher-value +cleanup stages are complete. -Duplicated or near-duplicated behavior: +## Non-Issues -- Most sources wrap `fksources.NewHTTPSource`, implement `Name`, advertise one `Kinds` value, fetch raw content if changed, compute `effectiveAt`, call `DefaultEventID`, and emit a single event. -- The SPC source cannot use `HTTPSource` directly because it fetches an atomic multi-document bundle, but it repeats the same user-agent, HTTP timeout, body limit, request accept header, and unchanged-content policy at a lower level through `transport.FetchBodyWithLimit`. -- HTTP config params are documented as shared, but source construction has no weatherfeeder-owned helper for the common param names and error shape when a source cannot use `HTTPSource`. +These areas were reviewed and should not be refactored without a new roadmap: -Why it matters: +- Normalizer `Match` methods are intentionally explicit schema checks. +- Provider-specific time parsers should remain provider-specific. +- SPC multi-document polling should remain source-local and atomic. +- The current runtime does not need a generic workflow engine. +- The Postgres sink should not become an ORM or reflection mapper. +- Documentation should remain audience-specific rather than generated from code. -- Adding future providers or multi-document products increases the chance of drift in `user_agent`, `http_timeout`, `http_response_body_limit_bytes`, body-limit, and error-message behavior. -- The single-document and SPC paths both implement operator-facing HTTP policy, but the shared policy is visible only in docs and feedkit conventions. -- Bug fixes to source envelope construction or shared HTTP params would likely need multiple package edits. +## Validation Baseline -Recommended refactor: +The current test suite covers source construction, normalizer registration and +mapping, Postgres schema/mapping, maintained config loading, source-driver docs, +and event-schema docs. -- Add a small source-internal helper package or file, for example `internal/sources/sourceconfig` or `internal/sources/internal/httpconfig`, that owns weatherfeeder-specific HTTP param extraction for sources that cannot directly use `fksources.NewHTTPSource`. -- Keep `fksources.NewHTTPSource` as the implementation for simple sources. Do not replace it with a custom framework. -- Add a helper for common single-event envelope construction only if it remains explicit about `kind`, `source`, `schema`, `eventID`, `emittedAt`, `effectiveAt`, and payload. Avoid hiding provider-specific effective-time selection. -- For SPC, replace local parsing of `user_agent`, `http_timeout`, and `http_response_body_limit_bytes` with the shared helper while preserving its atomic multi-fetch and hash semantics. - -Suggested tests: - -- Add helper-level tests for param aliases, positive timeout/body-limit validation, missing `user_agent`, and error messages. -- Keep existing source tests for emitted kind/schema/effective time unchanged. -- Add one SPC constructor test that proves shared timeout/body-limit validation still applies. - -Risk level: Low to Medium. The behavior is straightforward, but source constructor errors are user-facing and should be protected by tests. - -### 2. Reduce Postgres Mapper Boilerplate Without Creating An ORM - -Affected files/packages: - -- `internal/sinks/postgres/map.go` -- `internal/sinks/postgres/schema.go` -- `internal/sinks/postgres/map_test.go` -- `internal/sinks/postgres/schema_test.go` -- `docs/internal/postgres-sink.md` -- `docs/integrations/postgres.md` - -Duplicated or near-duplicated behavior: - -- Every parent table mapper repeats the same event envelope columns: `event_id`, `event_kind`, `event_source`, `event_schema`, `event_emitted_at`, and `event_effective_at`. -- Every run mapper follows the same pattern: decode payload, validate required run time/product fields, normalize to UTC, write one parent row, then write child rows with positional indexes. -- Nullable conversion helpers already exist, but each mapper repeats the same map literal shape and required-field error phrasing. -- Schema definitions repeat the same envelope column declarations across parent tables. - -Why it matters: - -- The mapper is now the largest concentration of cross-product persistence policy. As more canonical products are added, missing an envelope column, count field, UTC conversion, or required-field check becomes easier. -- Recent SPC work showed that canonical fields can be accidentally omitted from persistence even when the model and docs are correct. -- Refactoring this area would reduce maintenance risk and make mapper tests easier to read. - -Recommended refactor: - -- Add a small `eventEnvelopeValues(e)` helper returning the parent envelope value map, then merge product-specific columns into it. -- Add a small `eventEnvelopeColumns()` helper for schema definitions if feedkit schema construction remains readable. -- Add required-field helper functions for common checks such as `requireTime`, `requireString`, and `requireJSON`, but keep product-specific validation functions where policy differs. -- Keep explicit per-product mapper functions. Do not introduce reflection-based table mapping, struct tags, or a generic ORM layer. - -Suggested tests: - -- Add focused helper tests for envelope value UTC/null behavior. -- Keep product mapper tests asserting important columns per product. -- Add a regression test that each parent table with event envelope columns receives all envelope values from mapper output. -- Keep schema tests for nullable/required columns, especially recent outlook and forecast condition semantics. - -Risk level: Medium. The target is low-level persistence code; refactor only with existing mapper tests passing and add tests before moving column/value construction. - -### 3. Centralize Event Kind And Driver Name Constants - -Affected files/packages: - -- `internal/sources/builtins.go` -- `internal/sources/builtins_test.go` -- `internal/sources/*/*.go` -- `internal/normalizers/*/*_test.go` -- `cmd/weatherfeeder/main_test.go` -- `cmd/weatherfeeder/config.yml` -- `examples/*.yml` -- `docs/config.md` -- `docs/internal/sources.md` -- `docs/integrations/events.md` -- `standards/schema.go` - -Duplicated or near-duplicated behavior: - -- Schemas are centralized in `standards/schema.go`, but event kinds are repeatedly typed as string literals such as `event.Kind("forecast")`, `event.Kind("weather_story")`, and `event.Kind("outlook")`. -- Driver names are repeated in source constructors, registry entries, tests, config examples, docs, and troubleshooting text. -- The all-current-drivers test duplicates the registry table manually. - -Why it matters: - -- Kinds and driver names are public operator-facing strings. A typo or stale test value can produce startup failures or documentation drift. -- The mismatch between centralized schemas and non-centralized kinds/drivers makes future feature additions more error-prone. -- The source registry already has a structured `pollDriverRegistrations` slice that can become the canonical source for driver tests. - -Recommended refactor: - -- Add event kind constants in `standards`, for example `KindObservation`, `KindForecast`, `KindForecastDiscussion`, `KindWeatherStory`, `KindAlert`, and `KindOutlook`, typed as `event.Kind` if dependency direction is acceptable. If `standards` should not import feedkit, use string constants and convert at adapter boundaries. -- Add source driver constants near source registration, for example in `internal/sources/drivers.go`, and have constructors/tests use those constants. -- Update source registry tests to derive the all-current-drivers list from `pollDriverRegistrations`, while keeping explicit negative tests for removed legacy names. -- Keep docs and YAML examples literal; they are user-facing examples and should not be generated for this cleanup pass. - -Suggested tests: - -- Update source registry tests to assert every registered driver builds as a `PollSource` using the registry slice. -- Add a small test that configured source `Kinds()` match the central kind constants. -- Keep example config load tests as the docs/example guardrail. - -Risk level: Low. This is mostly mechanical, but care is needed to avoid import cycles if kind constants are typed with feedkit's `event.Kind`. - -### 4. Centralize Config Example Coverage Around All Maintained YAML Files - -Affected files/packages: - -- `cmd/weatherfeeder/main_test.go` -- `cmd/weatherfeeder/config.yml` -- `examples/config.minimal.yml` -- `examples/config.nats.yml` -- `examples/config.postgres.yml` -- `docs/config.md` - -Duplicated or near-duplicated behavior: - -- The sample and copyable configs repeat driver names, event kinds, route kind lists, NWS user-agent conventions, source cadences, and sink shapes. -- `main_test.go` already verifies that `cmd/weatherfeeder/config.yml` and `examples/*.yml` load and that sources build scheduler jobs. -- There is no single test that compares example route kind lists against current source-advertised kinds or documented current kinds. - -Why it matters: - -- Config examples are part of the operator contract. They tend to drift when a new canonical kind is added or renamed. -- Routes are easy to leave stale because a config can load successfully while omitting newly supported kinds from a production-oriented route example. - -Recommended refactor: - -- Keep examples explicit and copyable. -- Add tests that collect advertised source kinds from configured examples and verify route examples either intentionally match all kinds or document why they are selective. -- Add a small helper in tests for building the weatherfeeder source registry and validating all maintained configs, so config coverage stays obvious. - -Suggested tests: - -- Extend `TestMaintainedConfigExamplesLoad` to assert source expected kinds and scheduler jobs, which it already does, and add route-kind sanity checks if feedkit exposes compiled routes clearly enough. -- Add a docs/config example guard only if it can be kept simple; avoid parsing Markdown tables unless this repo already uses doc extraction tests. - -Risk level: Low. This is test-only cleanup unless route semantics in examples are intentionally selective. - -## Medium-Confidence Opportunities - -### 1. Normalize Required-Time Helper Patterns Where Semantics Match - -Affected files/packages: - -- `internal/providers/nws/time.go` -- `internal/providers/openmeteo/time.go` -- `internal/providers/spc/time.go` -- `internal/normalizers/nws/forecast.go` -- `internal/normalizers/nws/weatherstories.go` -- `internal/normalizers/spc/convective_outlook.go` -- `internal/sources/nws/*` -- `internal/sources/spc/convective_outlook.go` - -Duplicated or near-duplicated behavior: - -- Multiple normalizers implement required timestamp parsing with field-specific error messages. -- Multiple sources parse provider timestamps best-effort for effective-time selection. -- Providers correctly differ in timestamp formats, but callers often repeat trim/empty/UTC/error-context patterns. - -Why it matters: - -- Time parsing is a domain policy hotspot. Small drift in required vs optional parsing, UTC normalization, or error wording can create subtle behavior differences. -- Required field names in errors are useful and should be preserved. - -Recommended refactor: - -- Do not force all providers through one cross-provider parser; NWS, Open-Meteo, and SPC formats differ for good reasons. -- Consider small provider-local helpers such as `ParseRequiredTime(value, field)` and `ParseOptionalTime(value)` where a provider already has a canonical parser. -- Use common helper signatures only when the failure behavior is truly identical. - -Suggested tests: - -- Provider helper tests for empty, malformed, and UTC-normalized timestamps. -- Normalizer tests that assert required timestamp errors include the field path. - -Risk level: Medium. The duplication is real, but over-centralization could obscure provider-specific formats. - -### 2. Table-Drive Source Registry Tests More Aggressively - -Affected files/packages: - -- `internal/sources/builtins_test.go` - -Duplicated or near-duplicated behavior: - -- Several tests independently instantiate a registry and build one named driver. -- `TestRegisterBuiltinsRegistersAllCurrentDrivers` duplicates the same driver list that exists in `pollDriverRegistrations`. - -Why it matters: - -- Adding new drivers currently requires touching both the registration table and a manually duplicated test list. -- The test suite already has the structure needed to derive cases from the registration table. - -Recommended refactor: - -- Replace individual positive registration tests with a table derived from `pollDriverRegistrations`. -- Keep one or two named tests only when they assert special policy, such as legacy driver removal. -- Keep `sourceConfigForDriver` but make it keyed off driver constants. - -Suggested tests: - -- One table-driven positive registration test for every driver. -- One explicit negative test for `nws_forecast` legacy driver. - -Risk level: Low. This is test cleanup with minimal behavior risk. - -### 3. Package-Local Fixture Helpers Are Duplicated - -Affected files/packages: - -- `internal/providers/nws/forecast_discussion_test.go` -- `internal/providers/spc/geojson_test.go` -- `internal/sources/nws/forecast_discussion_test.go` -- `internal/sources/spc/convective_outlook_test.go` -- `internal/normalizers/nws/forecast_discussion_test.go` -- `internal/normalizers/spc/convective_outlook_test.go` - -Duplicated or near-duplicated behavior: - -- Several tests define local helpers that read from `testdata` using `os.ReadFile` and `filepath.Join`. -- Helper names differ by package, but behavior is mostly identical. - -Why it matters: - -- This is low-risk duplication, but fixture read failures and paths could be made more consistent. -- Cleaner fixture helpers would reduce noise in parser/source/normalizer tests. - -Recommended refactor: - -- Prefer package-local test helpers, not a cross-package test utility. Go package tests are easier to understand when fixtures remain near the package under test. -- Within each package with multiple test files, consolidate repeated `readTestFile` helpers into one `_test.go` helper file. - -Suggested tests: - -- No new behavior tests required; this cleanup is test-only. -- Run affected package tests. - -Risk level: Low. - -### 4. Schema, Model, And Postgres Documentation Lists Require Manual Synchronization - -Affected files/packages: - -- `standards/schema.go` -- `model/*.go` -- `docs/integrations/events.md` -- `docs/integrations/postgres.md` -- `docs/internal/normalizers.md` -- `docs/internal/sources.md` -- `docs/config.md` - -Duplicated or near-duplicated behavior: - -- Current schemas, raw mappings, canonical mappings, event kinds, and Postgres table contracts are documented in multiple current-behavior docs. -- This is partly intentional because docs serve different audiences, but all lists must be manually updated when a feature is added. - -Why it matters: - -- Recent feature additions touched many docs. Manual sync is workable now but will remain a recurring release risk. -- Documentation policy requires current-behavior docs to avoid speculative or stale content. - -Recommended refactor: - -- Do not generate docs wholesale. -- Add targeted doc consistency tests only for compact, machine-checkable facts, such as ensuring every schema constant appears in `docs/integrations/events.md` and every source driver appears in `docs/config.md`. -- Keep prose manual. - -Suggested tests: - -- A small standards/docs test that reads selected docs and checks for schema constants and driver constants. -- Keep examples load-tested. - -Risk level: Medium. Doc tests can become brittle if they parse prose too deeply; keep them shallow. - -## Boundary And Responsibility Concerns - -### Source Adapter HTTP Policy Is Split Between Feedkit And Weatherfeeder - -Most single-document sources rely on feedkit `HTTPSource`, while SPC implements a custom multi-document fetch loop. This boundary is acceptable because SPC's atomic bundle semantics differ from single-document polling. The concern is not the custom source itself; the concern is that shared weatherfeeder HTTP config policy is partly reimplemented in the SPC adapter. - -Recommended home: keep generic HTTP mechanics in feedkit, but add a small weatherfeeder source helper for weatherfeeder-owned parameter names and validation when a source cannot use `HTTPSource` directly. - -### Postgres Mapping Is Correctly Isolated But Becoming Too Dense - -The Postgres mapper is in the right package and does not leak into domain or normalizer code. The package responsibility is clear. The concern is density and repeated policy, not boundary drift. - -Recommended home: keep mapper helpers under `internal/sinks/postgres`. Do not move persistence concerns into `model` or normalizers. - -### Event Kind Strings Lack A Canonical Home - -Schemas have a clear home in `standards`; event kinds do not. Because kinds are part of routing and operator config, they deserve a comparable canonical code location. - -Recommended home: `standards` is the best conceptual location if dependency direction remains clean. If importing feedkit's `event` package into `standards` is undesirable, use string constants in `standards` and convert in source adapters. - -### Runtime Composition Is Appropriately Thin - -`cmd/weatherfeeder/main.go` is mostly process wiring. It does not contain provider parsing or sink mapping. No refactor is recommended here beyond possibly extracting tiny helper functions if future CLI flags make startup more complex. - -## Path, Key, And Naming Construction Review - -Centralized enough: - -- Schema strings are centralized in `standards/schema.go`. -- SPC product keys, day numbers, outlook types, and default URLs are centralized in `internal/providers/spc/product.go`. -- Postgres table names are centralized as constants in `internal/sinks/postgres/schema.go`. -- Test fixture paths are local and simple. - -Needs cleanup: - -- Event kind strings are repeated across source adapters, tests, YAML examples, and docs. -- Source driver names are repeated across constructors, registration, tests, docs, and examples. -- Postgres envelope column names are repeated in schema and mapper literals. -- Config route kind lists in examples are manually synchronized with supported canonical kinds. - -Recommended approach: - -- Add code constants for kinds and drivers first. -- Add narrow Postgres helpers for envelope column/value names second. -- Leave user-facing YAML and Markdown examples explicit, but test them against the code constants where practical. - -## Resolution And Catalog Review - -Current resolution model: - -- Source drivers resolve through `internal/sources.RegisterBuiltins` and feedkit's source registry. -- Normalizers resolve by schema matching through `internal/normalizers.RegisterBuiltins` and feedkit's normalize processor. -- Sinks resolve through feedkit's sink registry, with weatherfeeder registering a Postgres schema mapper. -- Schemas resolve through `standards` constants. -- SPC product catalogs resolve through `internal/providers/spc` product metadata helpers. - -Consistency assessment: - -- Normalizer resolution is strong: schema equality is explicit and follows policy. -- Source driver resolution is explicit and readable, but test coverage duplicates driver lists rather than deriving from the registry table. -- SPC product resolution is strong and should remain provider-local. -- There is no artifact, prompt, module, profile, manifest, or object-key catalog in this repository. - -Recommended centralization: - -- Treat source driver constants and event kind constants as small catalogs. -- Avoid building a generic catalog framework; explicit registry tables are appropriate for this codebase. - -## Config And Command-Loading Review - -Current behavior: - -- The executable reads exactly `config.yml` from the current working directory. -- There are no CLI flags, subcommands, profiles, environment-variable config overlays, or config path precedence rules. -- Feedkit owns top-level config loading and validation. -- Weatherfeeder source/sink constructors own driver-specific param validation. -- Maintained examples are load-tested and source-build-tested. - -Consistency assessment: - -- There is no duplicated command-loading behavior because there is only one command path. -- Driver-specific config validation is mostly consistent, but SPC has to duplicate some HTTP param parsing because it cannot use feedkit's single-document `HTTPSource`. -- OpenWeather's `units=metric` invariant is correctly located in `internal/providers/openweather` and enforced by the source constructor. - -Intentional differences: - -- SPC does not require `params.url` because it owns a fixed product catalog plus optional override maps. -- OpenWeather has stricter URL validation because unit semantics affect canonical mapping correctness. -- Single-document sources use conditional HTTP validators; SPC uses a bundle hash because it fetches multiple documents atomically. - -Likely accidental drift risk: - -- HTTP timeout and body-limit validation wording can differ between feedkit-backed HTTP sources and SPC. -- Future multi-document sources may copy SPC's config parsing rather than sharing a narrow helper. - -## State, Manifest, Or Progress Handling Review - -Current state handling: - -- The daemon has no durable internal run state, manifest, checkpoint, or resume marker. -- Feedkit scheduler, dispatcher, sink fanout queues, and dedupe operate in memory. -- Single-document HTTP conditional validators are source-instance memory only. -- SPC unchanged-response behavior uses a source-local hash of the last complete bundle. -- Postgres persistence is external sink state. - -Consistency assessment: - -- The state model is documented and consistent with the architecture policy. -- There is no hidden filesystem state substituting for declared state. -- There is no resume/force/dry-run behavior to drift across commands. - -Cleanup recommendation: - -- No state/manifest refactor is needed now. -- If future durable checkpoints are added, design them explicitly rather than expanding the current in-memory dedupe or source-local hash semantics. - -## Refactors To Avoid - -Avoid these refactors in the next cleanup pass: - -- A generic workflow engine or stage abstraction. The current runtime has source polling, normalization, dedupe, and dispatch; adding a stage framework would be speculative. -- A plugin runtime. The policy explicitly favors built-in registries over a general plugin system. -- Replacing feedkit HTTP, scheduler, dispatch, or sink infrastructure with weatherfeeder-owned equivalents. -- A generic Postgres ORM or reflection-driven mapper. The table contract is explicit and should remain readable. -- Cross-provider timestamp parsing that ignores provider-specific timestamp formats. -- Consolidating WMO mapping too aggressively. Provider-specific condition signals differ; only shared text fallback belongs in common helpers. -- Generating all docs from code. Shallow consistency tests are useful; generated manuals would fight the documentation policy's audience-specific structure. -- Collapsing all source adapters into one generic source type. The effective-time and payload policies are similar but still product-specific. -- Moving persistence tags or database column names into `model`. Canonical payloads should not depend on the Postgres sink. - -## Recommended Implementation Sequence - -1. Add event kind and source driver constants. - - Scope: constants plus mechanical usage in source adapters, registry tests, and normalizer tests where appropriate. Keep docs/YAML literal. Run `go test ./internal/sources ./internal/normalizers/... ./cmd/weatherfeeder`. - -2. Table-drive source registry tests. - - Scope: derive positive source driver cases from `pollDriverRegistrations`; keep legacy-driver negative tests. Run `go test ./internal/sources ./cmd/weatherfeeder`. - -3. Add source HTTP config helper for non-`HTTPSource` adapters. - - Scope: centralize `user_agent`, `http_timeout`, and `http_response_body_limit_bytes` parsing for SPC and future multi-document sources. Do not alter simple `HTTPSource` adapters. Run `go test ./internal/sources/spc ./internal/sources ./cmd/weatherfeeder`. - -4. Add Postgres envelope helper tests, then helper functions. - - Scope: add `eventEnvelopeValues`, optionally envelope column helpers, and product-specific required-field helpers. Keep explicit mapper functions. Run `go test ./internal/sinks/postgres`. - -5. Consolidate package-local fixture helpers. - - Scope: per package only; no cross-package testing utility. Run affected provider/source/normalizer package tests. - -6. Add shallow docs consistency tests. - - Scope: verify schema constants and source driver constants appear in canonical docs. Avoid parsing Markdown tables deeply. Run `go test ./standards ./cmd/weatherfeeder` or place tests in a suitable package that can read repo docs. - -7. Dead-code and legacy sweep. - - Scope: after constants/tests are in place, search for obsolete schema/driver/kind literals such as removed legacy driver names. Keep explicit negative tests where they document supported removals. - -## Test Strategy - -Tests to add before refactoring: - -- Source HTTP config helper tests for aliases, missing params, positive duration/body-limit validation, and error context. -- Postgres mapper tests that assert parent envelope columns are consistently present for every mapped canonical parent row. -- Source driver/kind constant tests if constants are introduced. - -Tests to update during refactoring: - -- `internal/sources/builtins_test.go` for table-driven registry coverage. -- `internal/sources/spc/convective_outlook_test.go` for shared HTTP config validation. -- `internal/sinks/postgres/map_test.go` and `schema_test.go` for envelope helper preservation. -- Existing provider/source/normalizer fixture tests if fixture helpers move. - -Focused verification commands: - -```sh -go test ./cmd/weatherfeeder ./internal/sources ./internal/sources/... ./internal/providers/... ./internal/normalizers/... ./internal/sinks/postgres ./model ./standards -``` - -Full verification command before merging cleanup: +Recommended baseline after any cleanup: ```sh go test ./... ``` - -## Appendix: Findings Not Worth Acting On - -### Provider-Specific Source Files Share A Similar Shape - -NWS, Open-Meteo, and OpenWeather source files all implement `Name`, `Kinds`, `Poll`, metadata decode, and event emission. This is acceptable because each product has distinct effective-time and metadata policy. Extract only the clearly shared HTTP/config pieces. - -### Normalizer Match Methods Are Repetitive By Design - -Most normalizers implement a one-line `Match` against a schema constant. This repetition is good: it keeps routing explicit and cheap. A generic schema-to-builder registry would add indirection without meaningful risk reduction. - -### Provider Time Parsers Should Remain Provider-Specific - -NWS, Open-Meteo, and SPC timestamp formats differ. The current provider-local parsers are easier to reason about than a broad cross-provider parser. Only required/optional wrapper patterns should be considered for cleanup. - -### Documentation Repeats Some Lists Intentionally - -`README.md`, `docs/config.md`, `docs/internal/sources.md`, and `docs/integrations/events.md` repeat selected feature lists for different audiences. Do not eliminate that repetition wholesale. Prefer shallow consistency tests for high-risk identifiers. - -### SPC Bundle Hash State Should Stay Local - -The SPC source's last-bundle hash is source-local unchanged-content state, not a general manifest/checkpoint system. Generalizing it now would be premature. - -### Runtime Wiring Could Be Split Into Helpers, But Need Not Be - -`cmd/weatherfeeder/main.go` is readable and policy-aligned. Extracting helper functions now would mostly move code around. Revisit only if CLI flags, config path options, metrics, or health checks are added. diff --git a/docs/roadmap/cleanup.md b/docs/roadmap/cleanup.md index 15fd13a..2c6ad08 100644 --- a/docs/roadmap/cleanup.md +++ b/docs/roadmap/cleanup.md @@ -2,158 +2,52 @@ ## Summary -This roadmap turns the findings in `docs/roadmap/audit.md` into staged, behavior-preserving cleanup work for `weatherfeeder`. +This roadmap tracks remaining behavior-preserving cleanup opportunities for +`weatherfeeder`. Earlier cleanup stages for event kind constants, source driver +constants, registry-derived source tests, shared multi-document HTTP config, and +shallow docs consistency tests have been completed and are no longer listed as +future work. -The goal is to reduce duplication and drift risk before the next major release without changing public contracts. Implement these stages in order. Each stage should be small enough for one focused implementation prompt or commit unless the implementing agent discovers unexpected coupling. +The remaining work should be implemented only in small, focused changes that do +not alter public event schemas, event kinds, source driver names, config keys, +Postgres table contracts, or canonical JSON field names. -Preserve the current architecture: +## Guardrails -- `feedkit` remains generic daemon infrastructure. -- `weatherfeeder` keeps weather-domain policy in sources, providers, normalizers, `model`, `standards`, and Postgres mapping. -- Current-behavior docs should change only when implementation changes require them. -- Roadmap-only cleanup instructions belong here until implemented. - -## Global Guardrails - -- Do not change public schema strings, event kind strings, source driver names, config keys, table names, column names, column nullability, or canonical model JSON field names. -- Do not include database migrations; this is cleanup-only work. -- Do not change `feedkit` in this cleanup pass. -- Do not introduce broad framework abstractions, plugin systems, workflow engines, generic source frameworks, ORM-style mapping, reflection mapping, or persistence annotations in `model`. -- Keep `cmd/weatherfeeder` focused on runtime composition. -- Keep source fetching separate from normalizer mapping. -- Keep provider-specific timestamp parsing and WMO mapping provider-specific unless an existing common helper already has exactly matching semantics. -- Keep user-facing YAML examples and Markdown examples literal; do not generate docs. +- Keep `feedkit` as the generic daemon infrastructure boundary. +- Keep weather-domain behavior in sources, provider helpers, normalizers, + `model`, `standards`, and Postgres mapping. +- Keep current-behavior docs accurate and roadmap-only plans under + `docs/roadmap/`. +- Do not introduce plugin systems, workflow engines, generic source frameworks, + ORM-style mapping, reflection mapping, generated docs, or persistence tags on + canonical model structs. - Run focused tests after each stage and `go test ./...` after all stages. -## Stage 1: Centralize Event Kind And Driver Constants +## Stage 1: Reduce Postgres Mapper Envelope Duplication -Add code constants for repeated weatherfeeder identifiers while preserving the literal string values. +Centralize repeated parent event envelope mapping without changing the table +contract. Implementation requirements: -- Add event kind string constants in `standards`, for example: - - `KindObservation = "observation"` - - `KindForecast = "forecast"` - - `KindForecastDiscussion = "forecast_discussion"` - - `KindWeatherStory = "weather_story"` - - `KindAlert = "alert"` - - `KindOutlook = "outlook"` -- Keep kind constants typed as plain strings, not `event.Kind`, so `standards` does not import `feedkit`. -- Add source driver string constants in the provider source packages to avoid import cycles: - - NWS driver constants under `internal/sources/nws`. - - Open-Meteo driver constants under `internal/sources/openmeteo`. - - OpenWeather driver constants under `internal/sources/openweather`. - - SPC driver constant under `internal/sources/spc`. -- Update source constructors to use driver constants instead of local string literals. -- Update `Kinds()` methods and `SingleEvent` calls to use `event.Kind(standards.Kind...)`. -- Update source registration to use provider driver constants. -- Update internal tests to use constants where doing so reduces drift. -- Keep docs and YAML examples literal because they are user-facing examples. -- Do not add weather-specific kind constants to `feedkit`. +- Add small helpers inside `internal/sinks/postgres` for parent envelope values: + `event_id`, `event_kind`, `event_source`, `event_schema`, + `event_emitted_at`, and `event_effective_at`. +- Use the helper in every parent table mapper that stores event envelope + columns. +- Keep explicit per-product mapper functions and product-specific validation. +- Optionally centralize envelope column declarations only if `schema.go` remains + easy to scan. +- Preserve every table, column, nullability rule, required-field check, compact + JSON behavior, UTC normalization, child positional index, and write count. Acceptance criteria: -- All driver and event kind string values remain unchanged. -- No import cycle is introduced. -- `standards` does not import `feedkit`. -- Source constructors, emitted events, and advertised kinds behave identically. - -Focused tests: - -```sh -go test ./internal/sources ./cmd/weatherfeeder -go test ./internal/normalizers/... -``` - -## Stage 2: Table-Drive Source Registry Tests - -Reduce source registry test duplication while preserving registry coverage. - -Implementation requirements: - -- Replace repeated positive tests in `internal/sources/builtins_test.go` with one table-driven test derived from `pollDriverRegistrations`. -- Keep the explicit negative test proving legacy `nws_forecast` is not registered. -- Keep `sourceConfigForDriver`, but update it to use driver constants or registry-derived driver names. -- Preserve coverage that every current registered driver builds as a `PollSource`. -- Do not weaken `ValidateExpectedKinds` or scheduler job build coverage in `cmd/weatherfeeder` tests. - -Acceptance criteria: - -- Adding a new driver to `pollDriverRegistrations` automatically includes it in the positive registry test. -- Legacy-driver rejection remains explicitly tested. -- Test behavior remains deterministic and independent of live upstream services. - -Focused tests: - -```sh -go test ./internal/sources ./cmd/weatherfeeder -``` - -## Stage 3: Add Shared HTTP Config Helper For Multi-Document Sources - -Centralize common HTTP config parsing for sources that cannot use feedkit's single-document `HTTPSource`. - -Implementation requirements: - -- Add a narrow helper under `internal/sources/internal/httpconfig`. -- The helper should parse only the common source HTTP client params needed by non-`HTTPSource` sources: - - trimmed source name; - - required `params.user_agent` / `params.userAgent`; - - optional `params.http_timeout` using feedkit config duration semantics; - - optional `params.http_response_body_limit_bytes` as a positive integer. -- The helper should return values sufficient for callers to build a `transport.NewHTTPClient(timeout)` and pass a body limit to `transport.FetchBodyWithLimit`. -- Refactor only the SPC source to use this helper. -- Preserve SPC-specific config parsing in the SPC source: - - `latitude`; - - `longitude`; - - `location_id` / `locationID`; - - `location_name` / `locationName`; - - `geojson_urls`; - - `discussion_urls`; - - `rss_url` / `rssURL`. -- Do not replace `fksources.NewHTTPSource` for normal single-URL sources. -- Preserve SPC atomic bundle fetch behavior, bundle hash behavior, effective-time policy, raw payload shape, and error context. - -Acceptance criteria: - -- SPC constructor accepts and rejects the same configs as before. -- SPC still fetches required documents atomically and emits no partial bundle. -- Existing SPC source tests pass unchanged except for expected helper-related error wording if the wording becomes more consistent. -- No single-document source is refactored away from `fksources.NewHTTPSource`. - -Focused tests: - -```sh -go test ./internal/sources/spc ./internal/sources -``` - -## Stage 4: Reduce Postgres Mapper Envelope Duplication - -Centralize repeated Postgres parent envelope mapping without changing the table contract. - -Implementation requirements: - -- Add small helper functions inside `internal/sinks/postgres`. -- Centralize parent event envelope values: - - `event_id`; - - `event_kind`; - - `event_source`; - - `event_schema`; - - `event_emitted_at`; - - `event_effective_at`. -- Use the helper in every parent table mapper that stores event envelope columns. -- Optionally centralize event envelope column declarations if it keeps `schema.go` readable. If it makes the schema definition harder to scan, leave column declarations explicit. -- Keep explicit per-product mapper functions. -- Keep product-specific validation in product-specific functions where policy differs. -- Do not introduce reflection mapping, struct tags, ORM-style abstractions, generated table mapping, or persistence annotations in `model`. -- Preserve every existing table, column, nullability rule, required-field check, compact JSON behavior, UTC normalization, child positional index, and write count. - -Acceptance criteria: - -- Mapper output for existing valid payloads is equivalent before and after the refactor. +- Mapper output for existing valid payloads is equivalent before and after the + refactor. - Unsupported schemas still map to zero writes and no error. - Required-field failures still include useful product/path context. -- Feedkit Postgres schema validation still receives complete rows for every declared column. Focused tests: @@ -161,50 +55,23 @@ Focused tests: go test ./internal/sinks/postgres ``` -## Stage 5: Tighten Config Example And Documentation Consistency Tests +## Stage 2: Consolidate Package-Local Fixture Helpers -Add shallow tests that detect identifier drift without generating or over-parsing documentation. - -Implementation requirements: - -- Extend maintained config tests so `cmd/weatherfeeder/config.yml` and every `examples/*.yml` remain loadable and source-buildable. -- Add shallow docs consistency tests for stable identifiers only: - - every schema constant in `standards` appears in `docs/integrations/events.md` when it is part of the current event contract; - - every registered source driver name appears in `docs/config.md`; - - every registered source driver name appears in `docs/internal/sources.md`. -- Avoid parsing Markdown tables deeply; simple file-content checks are sufficient. -- Do not generate docs. -- Do not modify current-behavior docs unless the implementation uncovers an actual stale documented identifier. -- Keep documentation policy intact: implemented behavior outside `docs/roadmap/`, future plans under `docs/roadmap/`. - -Acceptance criteria: - -- Identifier consistency tests fail when a new source driver or current schema is added without updating canonical docs. -- Tests are shallow and low maintenance. -- Tests do not assert prose formatting or table layout. - -Focused tests: - -```sh -go test ./cmd/weatherfeeder ./standards ./internal/sources -``` - -## Stage 6: Consolidate Package-Local Test Fixture Helpers - -Remove low-value duplicated fixture-reading code only where it is local and obvious. +Reduce low-value duplicated fixture-reading code only where it is local and +obvious. Implementation requirements: - Consolidate duplicated fixture readers only within the same Go package. -- Do not create a cross-package test utility package. - Keep fixtures under each package's `testdata` directory. -- If a package has only one fixture helper, leave it alone. -- Do not change fixture contents unless a test already requires it. -- Do not mix this stage with parser behavior changes. +- Do not create a cross-package test utility package. +- Do not change fixture contents unless an existing test already requires it. +- Do not mix this cleanup with parser behavior changes. Acceptance criteria: -- Test helper duplication is reduced where multiple files in one package share the same fixture-reading behavior. +- Local test helper duplication is reduced where multiple files in one package + already share the same fixture-reading behavior. - Tests remain easy to read locally. - No package imports a helper solely for tests from another package. @@ -216,17 +83,18 @@ go test ./internal/sources/nws ./internal/sources/spc go test ./internal/normalizers/nws ./internal/normalizers/spc ``` -## Stage 7: Dead-Code And Literal Sweep +## Stage 3: Dead-Code And Literal Sweep -Perform a final cleanup sweep after constants and helper stages are complete. +Perform a final cleanup sweep after mapper and fixture cleanup. Implementation requirements: -- Search for stale driver, kind, and schema literals after earlier stages. -- Replace internal code/test literals with constants where it reduces typo or drift risk. +- Search for stale internal driver, kind, and schema literals. +- Replace internal code/test literals with constants where it reduces typo or + drift risk. - Keep user-facing docs and YAML examples literal. - Keep intentional legacy-driver negative tests. -- Do not remove compatibility tests unless they are clearly obsolete and no longer document supported behavior. +- Do not remove compatibility tests unless they are clearly obsolete. - Do not broaden the cleanup into unrelated refactors. Suggested searches: @@ -238,8 +106,9 @@ rg 'TODO|legacy|deprecated|unknown source driver' internal cmd docs examples Acceptance criteria: -- Internal literals are reduced where constants now exist. -- Intentional literals in docs, YAML examples, raw schema docs, and negative tests remain readable. +- Internal literals are reduced where constants already exist. +- Intentional literals in docs, YAML examples, raw schema docs, and negative + tests remain readable. - No behavior changes are introduced. Focused tests: @@ -257,12 +126,8 @@ go test ./... git status --short ``` -Before committing the implemented cleanup, verify: - -- No public contracts changed unintentionally. -- Current-behavior docs still describe implemented behavior only. -- `docs/roadmap/cleanup.md` is either updated to remove completed work or moved to future/remediation tracking according to the repository's roadmap practice. -- No unrelated changes are included. +Verify current-behavior docs still describe implemented behavior only and no +public contracts changed unintentionally. ## Refactors To Avoid diff --git a/model/docs_test.go b/model/docs_test.go new file mode 100644 index 0000000..7fade0c --- /dev/null +++ b/model/docs_test.go @@ -0,0 +1,37 @@ +package model + +import ( + "os" + "strings" + "testing" +) + +func TestDocumentedConsumerModelTypes(t *testing.T) { + raw, err := os.ReadFile("../docs/consumers/pkg-model.md") + if err != nil { + t.Fatalf("ReadFile(pkg-model.md) error = %v", err) + } + doc := string(raw) + + required := []string{ + "gitea.maximumdirect.net/ejr/weatherfeeder/model", + "WeatherObservation", + "WeatherForecastRun", + "WeatherForecastPeriod", + "WeatherForecastDiscussion", + "WeatherForecastDiscussionSection", + "WeatherStoryRun", + "WeatherStory", + "WeatherAlertRun", + "WeatherAlert", + "WeatherAlertReference", + "WeatherOutlookRun", + "WeatherOutlook", + "WMOCode", + } + for _, want := range required { + if !strings.Contains(doc, want) { + t.Fatalf("docs/consumers/pkg-model.md missing %q", want) + } + } +} diff --git a/standards/docs_test.go b/standards/docs_test.go index 88ddf06..e44e7b9 100644 --- a/standards/docs_test.go +++ b/standards/docs_test.go @@ -17,20 +17,52 @@ func TestDocumentedEventSchemas(t *testing.T) { } doc := string(raw) - schemas := schemaConstants(t) - for _, schema := range schemas { + for _, schema := range schemaConstants(t, false) { if !strings.Contains(doc, schema) { t.Fatalf("docs/integrations/events.md missing schema %q", schema) } } } -func schemaConstants(t *testing.T) []string { +func TestDocumentedConsumerStandardsConstants(t *testing.T) { + raw, err := os.ReadFile("../docs/consumers/pkg-standards.md") + if err != nil { + t.Fatalf("ReadFile(pkg-standards.md) error = %v", err) + } + doc := string(raw) + + for _, schema := range schemaConstants(t, true) { + if !strings.Contains(doc, schema) { + t.Fatalf("docs/consumers/pkg-standards.md missing schema %q", schema) + } + } + for _, kind := range kindConstants(t) { + if !strings.Contains(doc, kind) { + t.Fatalf("docs/consumers/pkg-standards.md missing kind %q", kind) + } + } +} + +func schemaConstants(t *testing.T, includeNonCurrent bool) []string { t.Helper() - file, err := parser.ParseFile(token.NewFileSet(), "schema.go", nil, 0) + return stringConstantsFromFile(t, "schema.go", "Schema", func(name string) bool { + return !includeNonCurrent && schemaConstantNotInCurrentContract(name) + }) +} + +func kindConstants(t *testing.T) []string { + t.Helper() + + return stringConstantsFromFile(t, "kind.go", "Kind", nil) +} + +func stringConstantsFromFile(t *testing.T, path string, prefix string, skip func(string) bool) []string { + t.Helper() + + file, err := parser.ParseFile(token.NewFileSet(), path, nil, 0) if err != nil { - t.Fatalf("ParseFile(schema.go) error = %v", err) + t.Fatalf("ParseFile(%s) error = %v", path, err) } var out []string @@ -40,26 +72,26 @@ func schemaConstants(t *testing.T) []string { return true } for i, name := range valueSpec.Names { - if !strings.HasPrefix(name.Name, "Schema") || schemaConstantNotInCurrentContract(name.Name) { + if !strings.HasPrefix(name.Name, prefix) || (skip != nil && skip(name.Name)) { continue } if i >= len(valueSpec.Values) { - t.Fatalf("schema constant %s has no explicit value", name.Name) + t.Fatalf("constant %s has no explicit value", name.Name) } lit, ok := valueSpec.Values[i].(*ast.BasicLit) if !ok || lit.Kind != token.STRING { - t.Fatalf("schema constant %s is not a string literal", name.Name) + t.Fatalf("constant %s is not a string literal", name.Name) } - schema, err := strconv.Unquote(lit.Value) + value, err := strconv.Unquote(lit.Value) if err != nil { - t.Fatalf("schema constant %s value is not a quoted string: %v", name.Name, err) + t.Fatalf("constant %s value is not a quoted string: %v", name.Name, err) } - out = append(out, schema) + out = append(out, value) } return true }) if len(out) == 0 { - t.Fatalf("no schema constants found") + t.Fatalf("no %s constants found in %s", prefix, path) } return out }