Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

feat(data-warehouse): add Open-Meteo source (#77142)

Tom Owersd1dbb08d479a
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
index 092d1a63e54f..30cc3ee5d780 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
@@ -446,6 +446,7 @@ the row lists both.
| onepassword | HTTP (cursor pagination) | requests | ✅ |
| onfleet | HTTP (cursor pagination) | requests | ✅ |
| open_exchange_rates | HTTP | requests | ✅ |
+| open_meteo | HTTP (date windows) | requests | ✅ |
| openai | HTTP | requests | ✅ |
| openai_ads | HTTP | requests + `rest_source.RESTClient` | ✅ |
| opinion_stage | HTTP | requests | ✅ |
@@ -1174,7 +1175,6 @@ doesn't conflict with concurrent PRs.
- onesignal
- open_data_dc
- open_dental
-- open_meteo
- openalex
- opencorporates
- openfec
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/openmeteo.py b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/openmeteo.py
index 6d447f587edc..4af74fdbf1b6 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/openmeteo.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/openmeteo.py
@@ -6,4 +6,6 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common imp
@config.config
class OpenMeteoSourceConfig(config.Config):
- pass
+ locations: str
+ start_date: str | None = None
+ api_key: str | None = None
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/open_meteo/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/open_meteo/canonical_descriptions.py
new file mode 100644
index 000000000000..7a72d22aca2e
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/open_meteo/canonical_descriptions.py
@@ -0,0 +1,133 @@
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (
+ CanonicalDescriptions,
+)
+
+# Stamped onto every row by the connector; not part of the raw Open-Meteo response.
+_INJECTED_COLUMNS = {
+ "location_id": "Configured location as `latitude,longitude`. Part of the primary key.",
+ "latitude": "Requested latitude of the location, exactly as configured.",
+ "longitude": "Requested longitude of the location, exactly as configured.",
+ "location_label": "Optional label supplied for the configured location.",
+ "resolved_latitude": "Latitude of the grid cell Open-Meteo actually served, which can differ from the requested one.",
+ "resolved_longitude": "Longitude of the grid cell Open-Meteo actually served, which can differ from the requested one.",
+ "elevation": "Elevation of the grid cell in metres, from a 90m digital elevation model.",
+ "timezone": "Timezone the timestamps are expressed in. Always GMT, since every request pins it.",
+ "utc_offset_seconds": "Timezone offset applied to the timestamps, in seconds. Always 0.",
+ "time_utc": "Timestamp of the row as a UTC datetime, derived from `time`. Used as the incremental cursor and partition key.",
+ "time": "Timestamp of the row exactly as Open-Meteo returned it (ISO 8601, no offset).",
+}
+
+_HOURLY_WEATHER_COLUMNS = {
+ "temperature_2m": "Air temperature at 2 metres above ground.",
+ "relative_humidity_2m": "Relative humidity at 2 metres above ground, as a percentage.",
+ "dew_point_2m": "Dew point temperature at 2 metres above ground.",
+ "apparent_temperature": "Perceived feels-like temperature, combining wind chill, humidity and solar radiation.",
+ "precipitation": "Total precipitation (rain, showers, snow) for the preceding hour.",
+ "rain": "Rain from large scale weather systems for the preceding hour.",
+ "snowfall": "Snowfall for the preceding hour, in centimetres.",
+ "snow_depth": "Snow depth on the ground, in metres.",
+ "weather_code": "WMO weather interpretation code for the hour.",
+ "pressure_msl": "Atmospheric pressure reduced to mean sea level.",
+ "surface_pressure": "Atmospheric pressure at surface level.",
+ "cloud_cover": "Total cloud cover, as a percentage.",
+ "wind_speed_10m": "Wind speed at 10 metres above ground.",
+ "wind_direction_10m": "Wind direction at 10 metres above ground, in degrees.",
+ "wind_gusts_10m": "Maximum wind gust of the preceding hour at 10 metres above ground.",
+}
+
+_DAILY_WEATHER_COLUMNS = {
+ "weather_code": "Most severe WMO weather interpretation code of the day.",
+ "temperature_2m_max": "Maximum daily air temperature at 2 metres above ground.",
+ "temperature_2m_min": "Minimum daily air temperature at 2 metres above ground.",
+ "apparent_temperature_max": "Maximum daily feels-like temperature.",
+ "apparent_temperature_min": "Minimum daily feels-like temperature.",
+ "sunrise": "Sunrise time for the day.",
+ "sunset": "Sunset time for the day.",
+ "daylight_duration": "Number of seconds of daylight.",
+ "sunshine_duration": "Number of seconds of sunshine, counting only direct normal irradiance above 120 W/m².",
+ "precipitation_sum": "Total precipitation (rain, showers, snow) for the day.",
+ "rain_sum": "Total rain for the day.",
+ "snowfall_sum": "Total snowfall for the day, in centimetres.",
+ "precipitation_hours": "Number of hours in the day with precipitation.",
+ "wind_speed_10m_max": "Maximum wind speed of the day at 10 metres above ground.",
+ "wind_gusts_10m_max": "Maximum wind gust of the day at 10 metres above ground.",
+ "wind_direction_10m_dominant": "Dominant wind direction of the day, in degrees.",
+ "shortwave_radiation_sum": "Sum of daily shortwave solar radiation, in MJ/m².",
+ "et0_fao_evapotranspiration": "Daily reference evapotranspiration for a well watered grass field (FAO-56).",
+}
+
+CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
+ "weather_archive_hourly": {
+ "description": "Hourly historical weather for each configured location, from the Open-Meteo Historical Weather API (ERA5 and ERA5-Land reanalysis, 1940 onwards). One row per location per hour.",
+ "docs_url": "https://open-meteo.com/en/docs/historical-weather-api",
+ "columns": {
+ **_INJECTED_COLUMNS,
+ **_HOURLY_WEATHER_COLUMNS,
+ "shortwave_radiation": "Average shortwave solar radiation of the preceding hour, in W/m².",
+ },
+ },
+ "weather_archive_daily": {
+ "description": "Daily aggregated historical weather for each configured location, from the Open-Meteo Historical Weather API (ERA5 and ERA5-Land reanalysis, 1940 onwards). One row per location per day.",
+ "docs_url": "https://open-meteo.com/en/docs/historical-weather-api",
+ "columns": {
+ **_INJECTED_COLUMNS,
+ **_DAILY_WEATHER_COLUMNS,
+ "temperature_2m_mean": "Mean daily air temperature at 2 metres above ground.",
+ },
+ },
+ "weather_forecast_hourly": {
+ "description": "Hourly weather forecast for each configured location, covering the past 7 days and the next 16 days. Replaced on every sync, because forecast values for a given hour are revised on every model run.",
+ "docs_url": "https://open-meteo.com/en/docs",
+ "columns": {
+ **_INJECTED_COLUMNS,
+ **_HOURLY_WEATHER_COLUMNS,
+ "precipitation_probability": "Probability of precipitation in the hour, as a percentage.",
+ "showers": "Convective shower precipitation for the preceding hour.",
+ "visibility": "Horizontal visibility at ground level, in metres.",
+ "uv_index": "UV index, accounting for cloud cover.",
+ "is_day": "1 while the sun is above the horizon at this location, 0 otherwise.",
+ },
+ },
+ "weather_forecast_daily": {
+ "description": "Daily weather forecast for each configured location, covering the past 7 days and the next 16 days. Replaced on every sync, because forecast values for a given day are revised on every model run.",
+ "docs_url": "https://open-meteo.com/en/docs",
+ "columns": {
+ **_INJECTED_COLUMNS,
+ **_DAILY_WEATHER_COLUMNS,
+ "showers_sum": "Total convective shower precipitation for the day.",
+ "precipitation_probability_max": "Highest hourly probability of precipitation during the day, as a percentage.",
+ "uv_index_max": "Maximum UV index of the day, accounting for cloud cover.",
+ },
+ },
+ "weather_current": {
+ "description": "Current weather conditions for each configured location. One row per location per sync; use the append sync method to build a time series of snapshots.",
+ "docs_url": "https://open-meteo.com/en/docs",
+ "columns": {
+ **_INJECTED_COLUMNS,
+ **_HOURLY_WEATHER_COLUMNS,
+ "interval": "Number of seconds the current conditions are valid for.",
+ "showers": "Convective shower precipitation for the preceding hour.",
+ "is_day": "1 while the sun is above the horizon at this location, 0 otherwise.",
+ },
+ },
+ "air_quality_hourly": {
+ "description": "Hourly air quality for each configured location, from the Open-Meteo Air Quality API (CAMS European and global models), covering the past 7 days and the next 5 days. Replaced on every sync, because the CAMS values are revised on every model run.",
+ "docs_url": "https://open-meteo.com/en/docs/air-quality-api",
+ "columns": {
+ **_INJECTED_COLUMNS,
+ "pm10": "Particulate matter up to 10 micrometres, close to surface (10 metres above ground).",
+ "pm2_5": "Particulate matter up to 2.5 micrometres, close to surface (10 metres above ground).",
+ "carbon_monoxide": "Carbon monoxide concentration close to surface.",
+ "nitrogen_dioxide": "Nitrogen dioxide concentration close to surface.",
+ "sulphur_dioxide": "Sulphur dioxide concentration close to surface.",
+ "ozone": "Ozone concentration close to surface.",
+ "ammonia": "Ammonia concentration close to surface. Europe only.",
+ "dust": "Saharan dust particle concentration close to surface.",
+ "aerosol_optical_depth": "Aerosol optical depth at 550 nm of the entire atmosphere column.",
+ "uv_index": "UV index, accounting for cloud cover.",
+ "uv_index_clear_sky": "UV index assuming clear sky.",
+ "european_aqi": "European Air Quality Index, on a 0 (good) to over 100 (extremely poor) scale.",
+ "us_aqi": "United States Air Quality Index, on a 0 (good) to over 300 (hazardous) scale.",
+ },
+ },
+}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/open_meteo/open_meteo.py b/products/warehouse_sources/backend/temporal/data_imports/sources/open_meteo/open_meteo.py
new file mode 100644
index 000000000000..9ec0448ecdc8
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/open_meteo/open_meteo.py
@@ -0,0 +1,503 @@
+"""Transport for the Open-Meteo weather API.
+
+Hand-rolled rather than built on the shared `rest_source` framework: Open-Meteo has no list
+endpoint and no pagination, responses are column-oriented (parallel arrays under `hourly`/`daily`)
+and need pivoting into rows, and the archive endpoints are walked as date windows per configured
+coordinate. None of that is expressible as a declarative endpoint config. It still rides
+`make_tracked_session()`, so retries, rate-limit handling and egress telemetry are the framework's.
+"""
+
+import re
+import dataclasses
+from collections.abc import Iterator
+from datetime import UTC, date, datetime, timedelta
+from typing import Any
+from urllib.parse import urlencode
+
+import requests
+from structlog.types import FilteringBoundLogger
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.http import make_tracked_session
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceResponse
+from products.warehouse_sources.backend.temporal.data_imports.sources.open_meteo.settings import (
+ HOSTS,
+ OPEN_METEO_ENDPOINTS,
+ OpenMeteoEndpointConfig,
+)
+
+REQUEST_TIMEOUT_SECONDS = 60
+
+# Every location costs one request per date window, so cap the config to bound worker time and
+# outbound fan-out. The cap also bounds the per-window batch held in memory (see ARCHIVE_WINDOW_DAYS).
+MAX_LOCATIONS = 25
+
+# Archive backfills are walked a month at a time. One window holds every location's rows before it is
+# yielded (see `_windowed_rows`), so this times MAX_LOCATIONS times 24 is the worst-case batch size:
+# roughly 18k hourly rows.
+ARCHIVE_WINDOW_DAYS = 31
+
+# Labels are stamped onto every row of every batch, so an oversized one is amplified by the row
+# count (a whole hourly window is ~744 rows per location). Cap it at something comfortably longer
+# than any real place name.
+MAX_LABEL_LENGTH = 256
+
+# Used as the archive backfill start when the user leaves the start date blank. The archive reaches
+# back to 1940, so defaulting to "everything" would be a multi-decade first sync nobody asked for.
+DEFAULT_ARCHIVE_BACKFILL_DAYS = 365
+
+# All timestamps are requested and stored in UTC so the incremental watermark and the partition key
+# are comparable across locations in different zones.
+REQUEST_TIMEZONE = "GMT"
+
+
+class OpenMeteoResumeConfig:
+ """Resume cursor.
+
+ Windowed (archive) endpoints iterate date windows outermost and cover every location within a
+ window before yielding, so `next_start_date` alone describes progress. Rolling endpoints make one
+ request per location and track `location_index`.
+ """
+
+ next_start_date: str | None = None
+ location_index: int = 0
+
+
[email protected](frozen=True)
+class Location:
+ latitude: float
+ longitude: float
+ label: str | None = None
+
+ @property
+ def id(self) -> str:
+ # Stable string key so the primary key doesn't rely on float equality in the Delta merge.
+ return f"{self.latitude},{self.longitude}"
+
+
+def parse_locations(raw: str | None) -> list[Location]:
+ """Parse the user's free-text `locations` field into coordinate pairs.
+
+ Each non-empty line is `latitude,longitude` with an optional trailing `,label`. Raises
+ `ValueError` with an actionable message on malformed input so the user can fix the config rather
+ than getting a silently empty sync.
+ """
+ if not raw:
+ raise ValueError("At least one location (latitude,longitude) is required.")
+
+ locations: list[Location] = []
+ seen: set[str] = set()
+ for line_number, line in enumerate(raw.splitlines(), start=1):
+ stripped = line.strip()
+ if not stripped:
+ continue
+
+ # Split on the first two commas only so a label may itself contain commas (e.g. "New York, NY").
+ parts = stripped.split(",", 2)
+ if len(parts) < 2:
+ raise ValueError(
+ f"Line {line_number} ({stripped!r}) must be in the form 'latitude,longitude' or "
+ "'latitude,longitude,label'."
+ )
+
+ try:
+ latitude = float(parts[0].strip())
+ longitude = float(parts[1].strip())
+ except ValueError:
+ raise ValueError(f"Line {line_number} ({stripped!r}) has a non-numeric latitude or longitude.")
+
+ if not (-90.0 <= latitude <= 90.0) or not (-180.0 <= longitude <= 180.0):
+ raise ValueError(
+ f"Line {line_number} ({stripped!r}) is out of range: latitude must be in [-90, 90] and "
+ "longitude in [-180, 180]."
+ )
+
+ label = parts[2].strip() if len(parts) > 2 else None
+ # The label is copied onto every row, so a huge one is multiplied by the batch's row count.
+ if label is not None and len(label) > MAX_LABEL_LENGTH:
+ raise ValueError(
+ f"Line {line_number} has a label of {len(label)} characters: at most {MAX_LABEL_LENGTH} are allowed."
+ )
+
+ location = Location(latitude=latitude, longitude=longitude, label=label or None)
+
+ # Duplicates would collide on the `location_id` primary key and merge into one row.
+ if location.id in seen:
+ raise ValueError(f"Line {line_number} ({stripped!r}) repeats a location already listed above.")
+ seen.add(location.id)
+
+ locations.append(location)
+ if len(locations) > MAX_LOCATIONS:
+ raise ValueError(f"Too many locations: at most {MAX_LOCATIONS} are allowed per source.")
+
+ if not locations:
+ raise ValueError("At least one location (latitude,longitude) is required.")
+
+ return locations
+
+
+def parse_start_date(raw: str | None) -> date | None:
+ """Parse the optional archive backfill start date (`YYYY-MM-DD`)."""
+ if not raw or not raw.strip():
+ return None
+ try:
+ return date.fromisoformat(raw.strip())
+ except ValueError:
+ raise ValueError(f"Start date {raw.strip()!r} must be in YYYY-MM-DD form, for example 2024-01-01.")
+
+
+def base_url(endpoint: OpenMeteoEndpointConfig, api_key: str | None) -> str:
+ free_host, commercial_host = HOSTS[endpoint.host]
+ return commercial_host if api_key else free_host
+
+
+def build_params(
+ endpoint: OpenMeteoEndpointConfig,
+ location: Location,
+ api_key: str | None,
+ start: date | None = None,
+ end: date | None = None,
+) -> dict[str, Any]:
+ params: dict[str, Any] = {
+ "latitude": location.latitude,
+ "longitude": location.longitude,
+ endpoint.block: ",".join(endpoint.variables),
+ "timezone": REQUEST_TIMEZONE,
+ "timeformat": "iso8601",
+ **endpoint.extra_params,
+ }
+ if start is not None and end is not None:
+ params["start_date"] = start.isoformat()
+ params["end_date"] = end.isoformat()
+ if api_key:
+ params["apikey"] = api_key
+ return params
+
+
+# The commercial API key rides in the `apikey` query param, so it lands in `response.url` and in the
+# message `raise_for_status()` builds. Strip it before any of that reaches stored errors or logs.
+_APIKEY_RE = re.compile(r"(apikey=)[^&\s]+", re.IGNORECASE)
+
+
+def _redact_apikey(text: str) -> str:
+ return _APIKEY_RE.sub(r"\1REDACTED", text)
+
+
+def _get_with_redacted_errors(session: requests.Session, url: str) -> requests.Response:
+ """`session.get` with the API key stripped from any transport-level failure.
+
+ urllib3 builds connection, timeout and retry-exhausted messages out of the full URL, query
+ string included, and those exceptions propagate out of the sync all the way to
+ `ExternalDataJob.latest_error` and the operational logs. `make_tracked_session(redact_values=...)`
+ only masks the session's own log lines, not the exception it raises, so the key is scrubbed here.
+ `from None` keeps the unredacted original off the chained traceback too.
+ """
+ try:
+ return session.get(url, timeout=REQUEST_TIMEOUT_SECONDS)
+ except requests.RequestException as exc:
+ redacted = _redact_apikey(str(exc))
+ try:
+ # The concrete class is preserved so callers keep classifying the failure as before.
+ rebuilt: requests.RequestException = type(exc)(redacted)
+ except Exception:
+ # A subclass with a stricter signature (e.g. `JSONDecodeError`) still must not leak.
+ rebuilt = requests.RequestException(redacted)
+ raise rebuilt from None
+
+
+def _fetch(session: requests.Session, url: str) -> dict[str, Any]:
+ """Fetch one Open-Meteo response.
+
+ Retries for 429 and transient 5xx are handled by the tracked session's adapter, so nothing is
+ layered on top here. Open-Meteo answers a bad request with a 4xx whose body carries a `reason`
+ string; that is surfaced verbatim because it names the offending parameter.
+ """
+ response = _get_with_redacted_errors(session, url)
+
+ if not response.ok:
+ reason: str | None = None
+ try:
+ body = response.json()
+ if isinstance(body, dict):
+ raw_reason = body.get("reason")
+ reason = str(raw_reason) if raw_reason is not None else None
+ except ValueError:
+ reason = None
+
+ if response.status_code == 401:
+ raise requests.HTTPError(
+ f"Open-Meteo rejected the API key (status 401): {reason or response.reason}", response=response
+ )
+ if 400 <= response.status_code < 500 and response.status_code != 429:
+ raise requests.HTTPError(
+ f"Open-Meteo rejected the request (status {response.status_code}): {reason or response.reason}",
+ response=response,
+ )
+
+ try:
+ response.raise_for_status()
+ except requests.HTTPError as exc:
+ raise requests.HTTPError(_redact_apikey(str(exc)), response=exc.response) from None
+
+ return response.json()
+
+
+def parse_time(value: str) -> datetime:
+ """Turn an Open-Meteo timestamp into a tz-aware UTC datetime.
+
+ Values are `2026-01-01T00:00` for hourly blocks and `2026-01-01` for daily blocks; neither
+ carries an offset, and both are UTC because every request pins `timezone=GMT`.
+ """
+ parsed = datetime.fromisoformat(value)
+ return parsed.replace(tzinfo=UTC) if parsed.tzinfo is None else parsed.astimezone(UTC)
+
+
+def _base_row(payload: dict[str, Any], location: Location) -> dict[str, Any]:
+ """Columns stamped onto every row of a response.
+
+ The requested coordinates are stored as `latitude`/`longitude` (they are what the primary key is
+ built from and never move), while the grid cell Open-Meteo actually served is kept separately as
+ `resolved_latitude`/`resolved_longitude`.
+ """
+ return {
+ "location_id": location.id,
+ "latitude": location.latitude,
+ "longitude": location.longitude,
+ "location_label": location.label,
+ "resolved_latitude": payload.get("latitude"),
+ "resolved_longitude": payload.get("longitude"),
+ "elevation": payload.get("elevation"),
+ "timezone": payload.get("timezone"),
+ "utc_offset_seconds": payload.get("utc_offset_seconds"),
+ }
+
+
+def normalize_rows(
+ endpoint: OpenMeteoEndpointConfig, payload: dict[str, Any], location: Location
+) -> list[dict[str, Any]]:
+ """Pivot a column-oriented Open-Meteo response into one row per timestamp."""
+ block = payload.get(endpoint.block)
+ if not isinstance(block, dict):
+ return []
+
+ base = _base_row(payload, location)
+
+ if endpoint.block == "current":
+ # A `current` block without `time` has no partition key, so it is dropped rather than
+ # raising, matching how a missing `time` array is handled for the hourly/daily blocks below.
+ timestamp = block.get("time")
+ if timestamp is None:
+ return []
+ row = {**base, **block}
+ row["time_utc"] = parse_time(str(timestamp))
+ return [row]
+
+ times = block.get("time")
+ if not isinstance(times, list):
+ return []
+
+ series = {name: values for name, values in block.items() if name != "time" and isinstance(values, list)}
+ rows: list[dict[str, Any]] = []
+ for index, timestamp in enumerate(times):
+ row = {**base, "time": timestamp, "time_utc": parse_time(str(timestamp))}
+ for name, values in series.items():
+ row[name] = values[index] if index < len(values) else None
+ rows.append(row)
+ return rows
+
+
+def _date_windows(start: date, end: date) -> Iterator[tuple[date, date]]:
+ cursor = start
+ while cursor <= end:
+ window_end = min(cursor + timedelta(days=ARCHIVE_WINDOW_DAYS - 1), end)
+ yield cursor, window_end
+ cursor = window_end + timedelta(days=1)
+
+
+def _windowed_rows(
+ session: requests.Session,
+ endpoint: OpenMeteoEndpointConfig,
+ locations: list[Location],
+ api_key: str | None,
+ start: date,
+ end: date,
+ resumable_source_manager: ResumableSourceManager[OpenMeteoResumeConfig],
+ logger: FilteringBoundLogger,
+) -> Iterator[list[dict[str, Any]]]:
+ """Walk the archive in date windows, emitting one batch per window.
+
+ Date windows are the outer loop and locations the inner one so every batch is bounded above by
+ the window's end timestamp for *all* locations. With locations outermost the pipeline would
+ checkpoint the incremental watermark at the first location's newest row while later locations
+ still had history outstanding, and a mid-sync failure would skip it permanently.
+ """
+ host = base_url(endpoint, api_key)
+ for window_start, window_end in _date_windows(start, end):
+ rows: list[dict[str, Any]] = []
+ for location in locations:
+ params = build_params(endpoint, location, api_key, start=window_start, end=window_end)
+ payload = _fetch(session, f"{host}{endpoint.path}?{urlencode(params)}")
+ rows.extend(normalize_rows(endpoint, payload, location))
+
+ if rows:
+ yield rows
+
+ # Saved after the yield: a crash before the next window replays this one, and incremental
+ # merge dedupes it on the primary key.
+ next_start = window_end + timedelta(days=1)
+ resumable_source_manager.save_state(OpenMeteoResumeConfig(next_start_date=next_start.isoformat()))
+ logger.debug(f"Open-Meteo archive window complete. endpoint={endpoint.name}, through={window_end.isoformat()}")
+
+
+def _rolling_rows(
+ session: requests.Session,
+ endpoint: OpenMeteoEndpointConfig,
+ locations: list[Location],
+ api_key: str | None,
+ start_index: int,
+ resumable_source_manager: ResumableSourceManager[OpenMeteoResumeConfig],
+) -> Iterator[list[dict[str, Any]]]:
+ host = base_url(endpoint, api_key)
+ for index in range(start_index, len(locations)):
+ location = locations[index]
+ params = build_params(endpoint, location, api_key)
+ payload = _fetch(session, f"{host}{endpoint.path}?{urlencode(params)}")
+ rows = normalize_rows(endpoint, payload, location)
+ if rows:
+ yield rows
+ resumable_source_manager.save_state(OpenMeteoResumeConfig(location_index=index + 1))
+
+
+def resolve_archive_range(
+ configured_start: date | None,
+ db_incremental_field_last_value: Any,
+ today: date,
+) -> tuple[date, date]:
+ """Work out the archive date range for this run.
+
+ The incremental watermark wins when present; the framework has already shifted it back by the
+ schema's lookback, so recently revised ERA5 days get re-read. Otherwise the run starts at the
+ user's configured date, falling back to a bounded default rather than 1940.
+ """
+ start = configured_start or today - timedelta(days=DEFAULT_ARCHIVE_BACKFILL_DAYS)
+
+ if db_incremental_field_last_value is not None:
+ if isinstance(db_incremental_field_last_value, datetime):
+ start = db_incremental_field_last_value.astimezone(UTC).date()
+ elif isinstance(db_incremental_field_last_value, date):
+ start = db_incremental_field_last_value
+ else:
+ start = parse_time(str(db_incremental_field_last_value)).date()
+
+ return start, today
+
+
+def get_rows(
+ endpoint_name: str,
+ locations: list[Location],
+ api_key: str | None,
+ configured_start: date | None,
+ db_incremental_field_last_value: Any,
+ resumable_source_manager: ResumableSourceManager[OpenMeteoResumeConfig],
+ logger: FilteringBoundLogger,
+) -> Iterator[list[dict[str, Any]]]:
+ endpoint = OPEN_METEO_ENDPOINTS[endpoint_name]
+ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None
+
+ # One session reused across every request so urllib3 keeps the connection alive.
+ session = make_tracked_session(redact_values=(api_key,) if api_key else ())
+
+ if endpoint.windowed:
+ start, end = resolve_archive_range(configured_start, db_incremental_field_last_value, datetime.now(UTC).date())
+ if resume is not None and resume.next_start_date:
+ start = date.fromisoformat(resume.next_start_date)
+ if start > end:
+ logger.debug(f"Open-Meteo archive is already up to date. endpoint={endpoint.name}")
+ else:
+ yield from _windowed_rows(
+ session, endpoint, locations, api_key, start, end, resumable_source_manager, logger
+ )
+ else:
+ start_index = resume.location_index if resume is not None else 0
+ yield from _rolling_rows(session, endpoint, locations, api_key, start_index, resumable_source_manager)
+
+ resumable_source_manager.clear_state()
+
+
+def open_meteo_source(
+ endpoint_name: str,
+ locations_raw: str | None,
+ api_key: str | None,
+ start_date_raw: str | None,
+ db_incremental_field_last_value: Any,
+ resumable_source_manager: ResumableSourceManager[OpenMeteoResumeConfig],
+ logger: FilteringBoundLogger,
+) -> SourceResponse:
+ endpoint = OPEN_METEO_ENDPOINTS[endpoint_name]
+ locations = parse_locations(locations_raw)
+ configured_start = parse_start_date(start_date_raw)
+
+ return SourceResponse(
+ name=endpoint_name,
+ items=lambda: get_rows(
+ endpoint_name=endpoint_name,
+ locations=locations,
+ api_key=api_key,
+ configured_start=configured_start,
+ db_incremental_field_last_value=db_incremental_field_last_value,
+ resumable_source_manager=resumable_source_manager,
+ logger=logger,
+ ),
+ primary_keys=endpoint.primary_keys,
+ partition_count=1,
+ partition_size=1,
+ partition_mode="datetime",
+ partition_format=endpoint.partition_format,
+ partition_keys=["time_utc"],
+ # Archive batches are emitted one whole date window at a time (every location included), so
+ # each batch's newest timestamp is genuinely the high-water mark. Rolling endpoints return a
+ # single ascending time series per request.
+ sort_mode="asc",
+ )
+
+
+def validate_credentials(
+ locations_raw: str | None, api_key: str | None, start_date_raw: str | None
+) -> tuple[bool, str | None]:
+ """Probe the forecast endpoint with the first configured location.
+
+ Open-Meteo's core API is keyless, so this mostly checks that the location list is usable and the
+ API is reachable. When a commercial key is supplied it also proves the key works, because the
+ request then goes to the `customer-` host, which rejects an unknown key with a 401.
+ """
+ try:
+ locations = parse_locations(locations_raw)
+ parse_start_date(start_date_raw)
+ except ValueError as exc:
+ return False, str(exc)
+
+ endpoint = OPEN_METEO_ENDPOINTS["weather_current"]
+ params = build_params(endpoint, locations[0], api_key)
+ url = f"{base_url(endpoint, api_key)}{endpoint.path}?{urlencode(params)}"
+
+ session = make_tracked_session(redact_values=(api_key,) if api_key else ())
+ try:
+ response = session.get(url, timeout=REQUEST_TIMEOUT_SECONDS)
+ except Exception:
+ return False, "Could not reach the Open-Meteo API. Please try again."
+
+ if response.ok:
+ return True, None
+ if response.status_code == 401:
+ return False, "Open-Meteo rejected the API key. Check the key in your Open-Meteo customer account."
+
+ reason: str | None = None
+ try:
+ body = response.json()
+ if isinstance(body, dict) and body.get("reason") is not None:
+ reason = str(body["reason"])
+ except ValueError:
+ reason = None
+
+ return False, f"Open-Meteo returned status {response.status_code}{f': {reason}' if reason else ''}"
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/open_meteo/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/open_meteo/settings.py
new file mode 100644
index 000000000000..33a23fe859f2
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/open_meteo/settings.py
@@ -0,0 +1,268 @@
+from dataclasses import dataclass, field
+from typing import Any
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.schema import incremental_field
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import PartitionFormat
+from products.warehouse_sources.backend.types import IncrementalField, IncrementalFieldType
+
+# Open-Meteo splits its products across subdomains rather than paths. Commercial customers get a
+# `customer-` prefixed host with reserved capacity, selected by supplying an API key.
+# https://open-meteo.com/en/pricing
+HOSTS: dict[str, tuple[str, str]] = {
+ "forecast": ("https://api.open-meteo.com", "https://customer-api.open-meteo.com"),
+ "archive": ("https://archive-api.open-meteo.com", "https://customer-archive-api.open-meteo.com"),
+ "air_quality": ("https://air-quality-api.open-meteo.com", "https://customer-air-quality-api.open-meteo.com"),
+}
+
+# Every response carries a `time` series; the connector derives a tz-aware UTC datetime from it so
+# the incremental watermark and the datetime partitioner both get a real timestamp rather than the
+# API's abbreviated `2026-01-01T00:00` string.
+_TIME_INCREMENTAL_FIELDS: list[IncrementalField] = [
+ incremental_field("time_utc", IncrementalFieldType.DateTime),
+]
+
+# ERA5 reanalysis lands with roughly a five-day delay and recent days keep being revised, so each
+# incremental run re-reads a trailing week. Incremental merge makes the overlap idempotent.
+ARCHIVE_LOOKBACK_SECONDS = 7 * 24 * 60 * 60
+
+# Variable catalogs, taken from the endpoint docs linked on each entry below. Kept fixed rather than
+# user-supplied so the table columns (and their canonical descriptions) stay stable across teams.
+_ARCHIVE_HOURLY_VARIABLES = (
+ "temperature_2m",
+ "relative_humidity_2m",
+ "dew_point_2m",
+ "apparent_temperature",
+ "precipitation",
+ "rain",
+ "snowfall",
+ "snow_depth",
+ "weather_code",
+ "pressure_msl",
+ "surface_pressure",
+ "cloud_cover",
+ "wind_speed_10m",
+ "wind_direction_10m",
+ "wind_gusts_10m",
+ "shortwave_radiation",
+)
+
+_ARCHIVE_DAILY_VARIABLES = (
+ "weather_code",
+ "temperature_2m_max",
+ "temperature_2m_min",
+ "temperature_2m_mean",
+ "apparent_temperature_max",
+ "apparent_temperature_min",
+ "sunrise",
+ "sunset",
+ "daylight_duration",
+ "sunshine_duration",
+ "precipitation_sum",
+ "rain_sum",
+ "snowfall_sum",
+ "precipitation_hours",
+ "wind_speed_10m_max",
+ "wind_gusts_10m_max",
+ "wind_direction_10m_dominant",
+ "shortwave_radiation_sum",
+ "et0_fao_evapotranspiration",
+)
+
+_FORECAST_HOURLY_VARIABLES = (
+ "temperature_2m",
+ "relative_humidity_2m",
+ "dew_point_2m",
+ "apparent_temperature",
+ "precipitation_probability",
+ "precipitation",
+ "rain",
+ "showers",
+ "snowfall",
+ "snow_depth",
+ "weather_code",
+ "pressure_msl",
+ "surface_pressure",
+ "cloud_cover",
+ "visibility",
+ "wind_speed_10m",
+ "wind_direction_10m",
+ "wind_gusts_10m",
+ "uv_index",
+ "is_day",
+)
+
+_FORECAST_DAILY_VARIABLES = (
+ "weather_code",
+ "temperature_2m_max",
+ "temperature_2m_min",
+ "apparent_temperature_max",
+ "apparent_temperature_min",
+ "sunrise",
+ "sunset",
+ "daylight_duration",
+ "sunshine_duration",
+ "uv_index_max",
+ "precipitation_sum",
+ "rain_sum",
+ "showers_sum",
+ "snowfall_sum",
+ "precipitation_hours",
+ "precipitation_probability_max",
+ "wind_speed_10m_max",
+ "wind_gusts_10m_max",
+ "wind_direction_10m_dominant",
+ "shortwave_radiation_sum",
+ "et0_fao_evapotranspiration",
+)
+
+_CURRENT_VARIABLES = (
+ "temperature_2m",
+ "relative_humidity_2m",
+ "apparent_temperature",
+ "is_day",
+ "precipitation",
+ "rain",
+ "showers",
+ "snowfall",
+ "weather_code",
+ "cloud_cover",
+ "pressure_msl",
+ "surface_pressure",
+ "wind_speed_10m",
+ "wind_direction_10m",
+ "wind_gusts_10m",
+)
+
+_AIR_QUALITY_HOURLY_VARIABLES = (
+ "pm10",
+ "pm2_5",
+ "carbon_monoxide",
+ "nitrogen_dioxide",
+ "sulphur_dioxide",
+ "ozone",
+ "ammonia",
+ "dust",
+ "aerosol_optical_depth",
+ "uv_index",
+ "uv_index_clear_sky",
+ "european_aqi",
+ "us_aqi",
+)
+
+
+@dataclass(frozen=True)
+class OpenMeteoEndpointConfig:
+ name: str
+ # Key into `HOSTS`.
+ host: str
+ path: str
+ # Which block of the response holds the data: `hourly`/`daily` are column-oriented arrays that
+ # get pivoted into rows, `current` is a single flat object.
+ block: str
+ variables: tuple[str, ...]
+ description: str
+ # True for the archive endpoints, which take `start_date`/`end_date` and are therefore walked in
+ # date windows. False for the rolling forecast endpoints, which take `past_days`/`forecast_days`.
+ windowed: bool = False
+ incremental_fields: list[IncrementalField] = field(default_factory=list)
+ supports_incremental: bool = False
+ supports_append: bool = False
+ # `time_utc` alone is not unique table-wide because rows aggregate across every configured
+ # location, so the location is part of the key.
+ primary_keys: list[str] = field(default_factory=lambda: ["location_id", "time_utc"])
+ partition_format: PartitionFormat = "month"
+ default_incremental_lookback_seconds: int | None = None
+ # Merged into every request for this endpoint.
+ extra_params: dict[str, Any] = field(default_factory=dict)
+
+
+OPEN_METEO_ENDPOINTS: dict[str, OpenMeteoEndpointConfig] = {
+ "weather_archive_hourly": OpenMeteoEndpointConfig(
+ name="weather_archive_hourly",
+ host="archive",
+ path="/v1/archive",
+ block="hourly",
+ variables=_ARCHIVE_HOURLY_VARIABLES,
+ windowed=True,
+ incremental_fields=list(_TIME_INCREMENTAL_FIELDS),
+ supports_incremental=True,
+ supports_append=True,
+ partition_format="month",
+ default_incremental_lookback_seconds=ARCHIVE_LOOKBACK_SECONDS,
+ description="Hourly historical weather (ERA5 reanalysis, 1940 onwards) for each configured location. "
+ "https://open-meteo.com/en/docs/historical-weather-api",
+ ),
+ "weather_archive_daily": OpenMeteoEndpointConfig(
+ name="weather_archive_daily",
+ host="archive",
+ path="/v1/archive",
+ block="daily",
+ variables=_ARCHIVE_DAILY_VARIABLES,
+ windowed=True,
+ incremental_fields=list(_TIME_INCREMENTAL_FIELDS),
+ supports_incremental=True,
+ supports_append=True,
+ partition_format="month",
+ default_incremental_lookback_seconds=ARCHIVE_LOOKBACK_SECONDS,
+ description="Daily aggregated historical weather (ERA5 reanalysis, 1940 onwards) for each configured "
+ "location. https://open-meteo.com/en/docs/historical-weather-api",
+ ),
+ "weather_forecast_hourly": OpenMeteoEndpointConfig(
+ name="weather_forecast_hourly",
+ host="forecast",
+ path="/v1/forecast",
+ block="hourly",
+ variables=_FORECAST_HOURLY_VARIABLES,
+ partition_format="week",
+ description="Hourly weather forecast for each configured location, covering the past 7 days and the next "
+ "16 days. Full refresh only, because forecast values for a given hour are revised on every model run. "
+ "https://open-meteo.com/en/docs",
+ extra_params={"past_days": 7, "forecast_days": 16},
+ ),
+ "weather_forecast_daily": OpenMeteoEndpointConfig(
+ name="weather_forecast_daily",
+ host="forecast",
+ path="/v1/forecast",
+ block="daily",
+ variables=_FORECAST_DAILY_VARIABLES,
+ partition_format="week",
+ description="Daily weather forecast for each configured location, covering the past 7 days and the next "
+ "16 days. Full refresh only, because forecast values for a given day are revised on every model run. "
+ "https://open-meteo.com/en/docs",
+ extra_params={"past_days": 7, "forecast_days": 16},
+ ),
+ "weather_current": OpenMeteoEndpointConfig(
+ name="weather_current",
+ host="forecast",
+ path="/v1/forecast",
+ block="current",
+ variables=_CURRENT_VARIABLES,
+ incremental_fields=list(_TIME_INCREMENTAL_FIELDS),
+ # There is no server-side timestamp filter for current conditions, so this is not true
+ # incremental sync. Append works: each run polls one fresh snapshot per location and the
+ # observation time always moves forward, building a time series across runs.
+ supports_append=True,
+ partition_format="week",
+ description="Current weather conditions for each configured location. One row per location per sync; "
+ "use the append sync method to accumulate a time series. https://open-meteo.com/en/docs",
+ extra_params={"forecast_days": 1},
+ ),
+ "air_quality_hourly": OpenMeteoEndpointConfig(
+ name="air_quality_hourly",
+ host="air_quality",
+ path="/v1/air-quality",
+ block="hourly",
+ variables=_AIR_QUALITY_HOURLY_VARIABLES,
+ partition_format="week",
+ description="Hourly air quality (particulates, gases and AQI) for each configured location, covering the "
+ "past 7 days and the next 5 days. Full refresh only, because the CAMS values are revised on every model "
+ "run. https://open-meteo.com/en/docs/air-quality-api",
+ extra_params={"past_days": 7, "forecast_days": 5},
+ ),
+}
+
+ENDPOINTS = tuple(OPEN_METEO_ENDPOINTS.keys())
+
+INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {
+ name: config.incremental_fields for name, config in OPEN_METEO_ENDPOINTS.items()
+}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/open_meteo/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/open_meteo/source.py
index c24fcf3fd1de..ed538b3b339a 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/open_meteo/source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/open_meteo/source.py
@@ -1,21 +1,59 @@
-from typing import cast
+from typing import Optional, cast
from posthog.schema import (
DataWarehouseSourceCategory,
ExternalDataSourceType as SchemaExternalDataSourceType,
+ ReleaseStatus,
SourceConfig,
+ SourceFieldInputConfig,
+ SourceFieldInputConfigType,
)
-from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, SimpleSource
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, ResumableSource
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (
+ CanonicalDescriptions,
+)
from products.warehouse_sources.backend.temporal.data_imports.sources.common.registry import SourceRegistry
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.schema import SourceSchema
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceInputs, SourceResponse
from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.openmeteo import (
OpenMeteoSourceConfig,
)
+from products.warehouse_sources.backend.temporal.data_imports.sources.open_meteo.open_meteo import (
+ OpenMeteoResumeConfig,
+ open_meteo_source,
+ validate_credentials as validate_open_meteo_credentials,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.open_meteo.settings import (
+ ENDPOINTS,
+ OPEN_METEO_ENDPOINTS,
+)
from products.warehouse_sources.backend.types import ExternalDataSourceType
+CAPTION = """Pull weather and air quality data from [Open-Meteo](https://open-meteo.com) into the PostHog Data warehouse, so you can join it against your own events.
+
+Open-Meteo is free for non-commercial use and needs no API key. Commercial plans issue a key that also routes requests to Open-Meteo's reserved-capacity hosts, so add one below if you have it.
+
+Open-Meteo has no endpoint that lists locations, so enter one location per line as `latitude,longitude`. An optional label is allowed: `latitude,longitude,label`. For example:
+
+```
+51.5074,-0.1278,London
+40.7128,-74.0060,New York
+```
+
+The archive tables backfill hourly and daily history from the start date you set, then sync incrementally. The forecast and air quality tables always hold the current rolling window, because their values are revised on every model run.
+
+Free use is licensed CC BY 4.0 and requires attribution to Open-Meteo."""
+
@SourceRegistry.register
-class OpenMeteoSource(SimpleSource[OpenMeteoSourceConfig]):
+class OpenMeteoSource(ResumableSource[OpenMeteoSourceConfig, OpenMeteoResumeConfig]):
+ lists_tables_without_credentials = True # static endpoint catalog, safe for public docs
+ # Open-Meteo has only ever served `/v1/` and does not document it as a version users can choose
+ # between, so there is nothing meaningful to pin.
+ api_docs_url = "https://open-meteo.com/en/docs"
+
@property
def source_type(self) -> ExternalDataSourceType:
return ExternalDataSourceType.OPENMETEO
@@ -26,7 +64,113 @@ class OpenMeteoSource(SimpleSource[OpenMeteoSourceConfig]):
name=SchemaExternalDataSourceType.OPEN_METEO,
category=DataWarehouseSourceCategory.ANALYTICS,
label="Open-Meteo",
+ releaseStatus=ReleaseStatus.ALPHA,
+ keywords=["weather", "forecast", "climate", "air quality"],
+ caption=CAPTION,
iconPath="/static/services/open_meteo.png",
- fields=cast(list[FieldType], []),
- unreleasedSource=True,
+ docsUrl="https://open-meteo.com/en/docs",
+ fields=cast(
+ list[FieldType],
+ [
+ SourceFieldInputConfig(
+ name="locations",
+ label="Locations",
+ type=SourceFieldInputConfigType.TEXTAREA,
+ required=True,
+ placeholder="51.5074,-0.1278,London\n40.7128,-74.0060,New York",
+ secret=False,
+ ),
+ SourceFieldInputConfig(
+ name="start_date",
+ label="Historical start date",
+ type=SourceFieldInputConfigType.TEXT,
+ required=False,
+ placeholder="2024-01-01",
+ secret=False,
+ ),
+ SourceFieldInputConfig(
+ name="api_key",
+ label="API key (commercial plans only)",
+ type=SourceFieldInputConfigType.PASSWORD,
+ required=False,
+ placeholder="",
+ secret=True,
+ ),
+ ],
+ ),
+ )
+
+ def get_canonical_descriptions(self) -> CanonicalDescriptions:
+ from products.warehouse_sources.backend.temporal.data_imports.sources.open_meteo.canonical_descriptions import ( # noqa: PLC0415
+ CANONICAL_DESCRIPTIONS,
+ )
+
+ return CANONICAL_DESCRIPTIONS
+
+ def get_non_retryable_errors(self) -> dict[str, str | None]:
+ return {
+ "Open-Meteo rejected the API key": "Open-Meteo rejected the API key. Check the key in your Open-Meteo customer account, then reconnect.",
+ # A 4xx here means a parameter Open-Meteo will not accept (an out-of-range coordinate, a
+ # start date before the archive begins). Retrying can never satisfy it.
+ "Open-Meteo rejected the request": "Open-Meteo rejected the request. Check the locations and historical start date on this source, then reconnect.",
+ }
+
+ def get_schemas(
+ self,
+ config: OpenMeteoSourceConfig,
+ team_id: int,
+ with_counts: bool = False,
+ names: list[str] | None = None,
+ force_refresh: bool = False,
+ api_version: str | None = None,
+ ) -> list[SourceSchema]:
+ schemas = [
+ SourceSchema(
+ name=endpoint.name,
+ supports_incremental=endpoint.supports_incremental,
+ supports_append=endpoint.supports_append,
+ incremental_fields=endpoint.incremental_fields,
+ description=endpoint.description,
+ default_incremental_lookback_seconds=endpoint.default_incremental_lookback_seconds,
+ detected_primary_keys=endpoint.primary_keys,
+ )
+ for endpoint in (OPEN_METEO_ENDPOINTS[name] for name in ENDPOINTS)
+ ]
+ if names is not None:
+ names_set = set(names)
+ schemas = [s for s in schemas if s.name in names_set]
+ return schemas
+
+ def validate_credentials(
+ self,
+ config: OpenMeteoSourceConfig,
+ team_id: int,
+ schema_name: Optional[str] = None,
+ api_version: str | None = None,
+ ) -> tuple[bool, str | None]:
+ return validate_open_meteo_credentials(config.locations, config.api_key, config.start_date)
+
+ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[OpenMeteoResumeConfig]:
+ # Endpoints store incompatible cursors (a date for the archive, a location index for the
+ # rolling ones), so each keeps its resume state in its own namespace.
+ return ResumableSourceManager[OpenMeteoResumeConfig](
+ inputs, OpenMeteoResumeConfig, namespace=inputs.schema_name
+ )
+
+ def source_for_pipeline(
+ self,
+ config: OpenMeteoSourceConfig,
+ resumable_source_manager: ResumableSourceManager[OpenMeteoResumeConfig],
+ inputs: SourceInputs,
+ ) -> SourceResponse:
+ return open_meteo_source(
+ endpoint_name=inputs.schema_name,
+ locations_raw=config.locations,
+ api_key=config.api_key,
+ start_date_raw=config.start_date,
+ db_incremental_field_last_value=inputs.db_incremental_field_last_value
+ if inputs.should_use_incremental_field
+ else None,
+ resumable_source_manager=resumable_source_manager,
+ logger=inputs.logger,
)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/open_meteo/tests/test_open_meteo.py b/products/warehouse_sources/backend/temporal/data_imports/sources/open_meteo/tests/test_open_meteo.py
new file mode 100644
index 000000000000..76a16c794055
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/open_meteo/tests/test_open_meteo.py
@@ -0,0 +1,634 @@
+import json
+from datetime import UTC, date, datetime
+from typing import Any
+from urllib.parse import parse_qs, urlparse
+
+import pytest
+from freezegun import freeze_time
+from unittest import mock
+
+import requests
+import structlog
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from products.warehouse_sources.backend.temporal.data_imports.sources.open_meteo.open_meteo import (
+ ARCHIVE_WINDOW_DAYS,
+ DEFAULT_ARCHIVE_BACKFILL_DAYS,
+ MAX_LABEL_LENGTH,
+ MAX_LOCATIONS,
+ Location,
+ OpenMeteoResumeConfig,
+ _fetch,
+ _redact_apikey,
+ base_url,
+ build_params,
+ get_rows,
+ normalize_rows,
+ open_meteo_source,
+ parse_locations,
+ parse_start_date,
+ parse_time,
+ resolve_archive_range,
+ validate_credentials,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.open_meteo.settings import OPEN_METEO_ENDPOINTS
+
+MODULE = "products.warehouse_sources.backend.temporal.data_imports.sources.open_meteo.open_meteo"
+
+LONDON = Location(51.5074, -0.1278, "London")
+NEW_YORK = Location(40.7128, -74.006)
+
+
+class FakeResumeManager(ResumableSourceManager[OpenMeteoResumeConfig]):
+ def __init__(self, state: OpenMeteoResumeConfig | None = None) -> None:
+ self.state = state
+ self.saved: list[OpenMeteoResumeConfig] = []
+ self.cleared = False
+
+ def can_resume(self) -> bool:
+ return self.state is not None
+
+ def load_state(self) -> OpenMeteoResumeConfig | None:
+ return self.state
+
+ def save_state(self, data: OpenMeteoResumeConfig) -> None:
+ self.saved.append(data)
+
+ def clear_state(self) -> None:
+ self.cleared = True
+
+
+def _response(status: int = 200, body: dict[str, Any] | None = None) -> mock.MagicMock:
+ response = mock.MagicMock()
+ response.status_code = status
+ response.ok = 200 <= status < 300
+ response.reason = "Bad Request" if status == 400 else "Unauthorized" if status == 401 else "OK"
+ response.json.return_value = body if body is not None else {}
+ response.text = json.dumps(body or {})
+ response.raise_for_status.side_effect = (
+ None
+ if response.ok
+ else requests.HTTPError(
+ f"{status} Server Error for url: https://api.open-meteo.com/v1/forecast?apikey=secret",
+ response=requests.Response(),
+ )
+ )
+ return response
+
+
+def _hourly_body(times: list[str], **series: list[Any]) -> dict[str, Any]:
+ return {
+ "latitude": 51.5,
+ "longitude": -0.125,
+ "elevation": 23.0,
+ "timezone": "GMT",
+ "utc_offset_seconds": 0,
+ "hourly": {"time": times, **series},
+ }
+
+
+def _fake_session(responses: list[mock.MagicMock]) -> mock.MagicMock:
+ session = mock.MagicMock()
+ session.get.side_effect = responses
+ return session
+
+
+def _requested_urls(session: mock.MagicMock) -> list[str]:
+ return [call.args[0] for call in session.get.call_args_list]
+
+
+def _query(url: str) -> dict[str, list[str]]:
+ return parse_qs(urlparse(url).query)
+
+
+class TestParseLocations:
+ @pytest.mark.parametrize(
+ "raw,expected",
+ [
+ ("51.5,-0.12", [Location(51.5, -0.12, None)]),
+ ("51.5,-0.12,London", [Location(51.5, -0.12, "London")]),
+ (" 51.5 , -0.12 , London ", [Location(51.5, -0.12, "London")]),
+ ("51.5,-0.12\n\n \n40.7,-74.0", [Location(51.5, -0.12), Location(40.7, -74.0)]),
+ ("40.7,-74.0,New York, NY", [Location(40.7, -74.0, "New York, NY")]),
+ ],
+ )
+ def test_valid(self, raw: str, expected: list[Location]) -> None:
+ assert parse_locations(raw) == expected
+
+ @pytest.mark.parametrize(
+ "raw,message",
+ [
+ (None, "At least one location"),
+ ("", "At least one location"),
+ (" \n ", "At least one location"),
+ ("51.5", "must be in the form"),
+ ("abc,def", "non-numeric"),
+ ("91,0", "out of range"),
+ ("0,181", "out of range"),
+ # Two identical coordinates would share a `location_id` and merge into a single row.
+ ("51.5,-0.12,London\n51.5,-0.12,Londres", "repeats a location"),
+ ],
+ )
+ def test_invalid_raises(self, raw: str | None, message: str) -> None:
+ with pytest.raises(ValueError, match=message):
+ parse_locations(raw)
+
+ def test_rejects_more_than_max_locations(self) -> None:
+ raw = "\n".join(f"{index}.5,0" for index in range(MAX_LOCATIONS + 1))
+ with pytest.raises(ValueError, match="Too many locations"):
+ parse_locations(raw)
+
+ def test_allows_exactly_max_locations(self) -> None:
+ raw = "\n".join(f"{index}.5,0" for index in range(MAX_LOCATIONS))
+ assert len(parse_locations(raw)) == MAX_LOCATIONS
+
+ def test_rejects_an_oversized_label(self) -> None:
+ # The label is copied onto every row of every batch, so an unbounded one is amplified by the
+ # batch's row count and can exhaust the worker.
+ with pytest.raises(ValueError, match="label of"):
+ parse_locations(f"51.5,-0.12,{'x' * (MAX_LABEL_LENGTH + 1)}")
+
+ def test_allows_a_label_of_exactly_the_maximum_length(self) -> None:
+ label = "x" * MAX_LABEL_LENGTH
+ assert parse_locations(f"51.5,-0.12,{label}") == [Location(51.5, -0.12, label)]
+
+
+class TestParseStartDate:
+ @pytest.mark.parametrize("raw,expected", [(None, None), ("", None), (" ", None), ("2024-01-01", date(2024, 1, 1))])
+ def test_valid(self, raw: str | None, expected: date | None) -> None:
+ assert parse_start_date(raw) == expected
+
+ @pytest.mark.parametrize("raw", ["01/01/2024", "2024-13-01", "yesterday"])
+ def test_invalid_raises(self, raw: str) -> None:
+ with pytest.raises(ValueError, match="YYYY-MM-DD"):
+ parse_start_date(raw)
+
+
+class TestParseTime:
+ @pytest.mark.parametrize(
+ "raw,expected",
+ [
+ ("2026-01-02T03:00", datetime(2026, 1, 2, 3, 0, tzinfo=UTC)),
+ ("2026-01-02", datetime(2026, 1, 2, 0, 0, tzinfo=UTC)),
+ ],
+ )
+ def test_returns_utc_aware_datetime(self, raw: str, expected: datetime) -> None:
+ parsed = parse_time(raw)
+ assert parsed == expected
+ # A naive datetime would be incomparable with the stored watermark.
+ assert parsed.tzinfo is not None
+
+
+class TestRequestBuilding:
+ @pytest.mark.parametrize(
+ "endpoint_name,api_key,expected_host",
+ [
+ ("weather_forecast_hourly", None, "https://api.open-meteo.com"),
+ ("weather_forecast_hourly", "key", "https://customer-api.open-meteo.com"),
+ ("weather_archive_hourly", None, "https://archive-api.open-meteo.com"),
+ ("weather_archive_hourly", "key", "https://customer-archive-api.open-meteo.com"),
+ ("air_quality_hourly", None, "https://air-quality-api.open-meteo.com"),
+ ("air_quality_hourly", "key", "https://customer-air-quality-api.open-meteo.com"),
+ ],
+ )
+ def test_commercial_host_only_used_with_an_api_key(
+ self, endpoint_name: str, api_key: str | None, expected_host: str
+ ) -> None:
+ assert base_url(OPEN_METEO_ENDPOINTS[endpoint_name], api_key) == expected_host
+
+ def test_params_carry_the_endpoint_block_and_variables(self) -> None:
+ endpoint = OPEN_METEO_ENDPOINTS["weather_archive_daily"]
+ params = build_params(endpoint, LONDON, None, start=date(2026, 1, 1), end=date(2026, 1, 31))
+
+ assert params["latitude"] == LONDON.latitude
+ assert params["longitude"] == LONDON.longitude
+ assert params["daily"] == ",".join(endpoint.variables)
+ assert "hourly" not in params
+ assert params["timezone"] == "GMT"
+ assert params["start_date"] == "2026-01-01"
+ assert params["end_date"] == "2026-01-31"
+ assert "apikey" not in params
+
+ def test_rolling_params_have_no_date_window_and_carry_the_key(self) -> None:
+ params = build_params(OPEN_METEO_ENDPOINTS["air_quality_hourly"], LONDON, "secret")
+
+ assert "start_date" not in params
+ assert "end_date" not in params
+ assert params["past_days"] == 7
+ assert params["forecast_days"] == 5
+ assert params["apikey"] == "secret"
+
+ def test_redacts_the_api_key(self) -> None:
+ assert _redact_apikey("...?latitude=1&apikey=secret&hourly=x") == "...?latitude=1&apikey=REDACTED&hourly=x"
+
+
+class TestNormalizeRows:
+ def test_pivots_parallel_arrays_into_one_row_per_timestamp(self) -> None:
+ payload = _hourly_body(
+ ["2026-01-01T00:00", "2026-01-01T01:00"],
+ temperature_2m=[1.5, 2.5],
+ wind_speed_10m=[10.0, 11.0],
+ )
+
+ rows = normalize_rows(OPEN_METEO_ENDPOINTS["weather_archive_hourly"], payload, LONDON)
+
+ assert [row["time"] for row in rows] == ["2026-01-01T00:00", "2026-01-01T01:00"]
+ assert [row["temperature_2m"] for row in rows] == [1.5, 2.5]
+ assert [row["wind_speed_10m"] for row in rows] == [10.0, 11.0]
+ assert [row["time_utc"] for row in rows] == [
+ datetime(2026, 1, 1, 0, 0, tzinfo=UTC),
+ datetime(2026, 1, 1, 1, 0, tzinfo=UTC),
+ ]
+
+ def test_stamps_requested_coordinates_and_keeps_the_served_grid_cell_separate(self) -> None:
+ payload = _hourly_body(["2026-01-01T00:00"], temperature_2m=[1.5])
+
+ row = normalize_rows(OPEN_METEO_ENDPOINTS["weather_archive_hourly"], payload, LONDON)[0]
+
+ # The primary key is built from the configured coordinates, so they must survive verbatim
+ # rather than being overwritten by the grid cell Open-Meteo snapped to.
+ assert row["location_id"] == "51.5074,-0.1278"
+ assert row["latitude"] == 51.5074
+ assert row["longitude"] == -0.1278
+ assert row["location_label"] == "London"
+ assert row["resolved_latitude"] == 51.5
+ assert row["resolved_longitude"] == -0.125
+ assert row["elevation"] == 23.0
+
+ def test_pads_a_short_series_rather_than_shifting_later_values(self) -> None:
+ payload = _hourly_body(
+ ["2026-01-01T00:00", "2026-01-01T01:00", "2026-01-01T02:00"],
+ temperature_2m=[1.5, 2.5],
+ )
+
+ rows = normalize_rows(OPEN_METEO_ENDPOINTS["weather_archive_hourly"], payload, LONDON)
+
+ assert [row["temperature_2m"] for row in rows] == [1.5, 2.5, None]
+
+ def test_current_block_yields_a_single_flat_row(self) -> None:
+ payload = {
+ "latitude": 51.5,
+ "longitude": -0.125,
+ "current": {"time": "2026-01-01T00:15", "interval": 900, "temperature_2m": 4.2},
+ }
+
+ rows = normalize_rows(OPEN_METEO_ENDPOINTS["weather_current"], payload, LONDON)
+
+ assert len(rows) == 1
+ assert rows[0]["temperature_2m"] == 4.2
+ assert rows[0]["interval"] == 900
+ assert rows[0]["time_utc"] == datetime(2026, 1, 1, 0, 15, tzinfo=UTC)
+
+ @pytest.mark.parametrize("payload", [{}, {"hourly": None}, {"hourly": {"time": None}}])
+ def test_missing_block_yields_no_rows(self, payload: dict[str, Any]) -> None:
+ assert normalize_rows(OPEN_METEO_ENDPOINTS["weather_archive_hourly"], payload, LONDON) == []
+
+ @pytest.mark.parametrize("payload", [{}, {"current": None}, {"current": {"temperature_2m": 4.2}}])
+ def test_current_block_without_a_timestamp_yields_no_rows(self, payload: dict[str, Any]) -> None:
+ # `time_utc` is the partition key, so a row without one is unusable. Dropping it matches the
+ # hourly/daily path rather than raising a `KeyError` out of the middle of a sync.
+ assert normalize_rows(OPEN_METEO_ENDPOINTS["weather_current"], payload, LONDON) == []
+
+
+class TestFetch:
+ def test_maps_401_to_the_permanent_api_key_error(self) -> None:
+ session = _fake_session([_response(401, {"error": True, "reason": "Invalid API key"})])
+
+ with pytest.raises(requests.HTTPError, match="Open-Meteo rejected the API key"):
+ _fetch(session, "https://customer-api.open-meteo.com/v1/forecast")
+
+ @pytest.mark.parametrize("status", [400, 404])
+ def test_maps_other_4xx_to_the_permanent_request_error_with_the_reason(self, status: int) -> None:
+ session = _fake_session(
+ [_response(status, {"error": True, "reason": "Latitude must be in range of -90 to 90"})]
+ )
+
+ with pytest.raises(requests.HTTPError, match="Latitude must be in range"):
+ _fetch(session, "https://archive-api.open-meteo.com/v1/archive")
+
+ @pytest.mark.parametrize("status", [429, 500, 503])
+ def test_transient_statuses_are_not_reported_as_permanent_rejections(self, status: int) -> None:
+ # The tracked session's adapter already retried these; surfacing them under the
+ # `get_non_retryable_errors` wording would permanently disable the source instead.
+ session = _fake_session([_response(status, {})])
+
+ with pytest.raises(requests.HTTPError) as excinfo:
+ _fetch(session, "https://api.open-meteo.com/v1/forecast")
+
+ assert "Open-Meteo rejected" not in str(excinfo.value)
+ assert "apikey=REDACTED" in str(excinfo.value)
+
+ def test_falls_back_to_the_http_reason_when_the_error_body_is_not_json(self) -> None:
+ response = _response(400, {})
+ response.json.side_effect = ValueError("no json here")
+ session = _fake_session([response])
+
+ with pytest.raises(requests.HTTPError, match="Bad Request"):
+ _fetch(session, "https://archive-api.open-meteo.com/v1/archive")
+
+ @pytest.mark.parametrize(
+ "error",
+ [
+ requests.ConnectionError(
+ "HTTPSConnectionPool(host='customer-api.open-meteo.com', port=443): Max retries exceeded "
+ "with url: /v1/forecast?latitude=51.5&apikey=super-secret&hourly=temperature_2m"
+ ),
+ requests.Timeout("Read timed out for url: /v1/forecast?apikey=super-secret"),
+ requests.exceptions.RetryError("too many retries: /v1/archive?apikey=super-secret&start_date=2024-01-01"),
+ ],
+ )
+ def test_transport_errors_never_carry_the_api_key(self, error: Exception) -> None:
+ # These propagate out of the sync into `ExternalDataJob.latest_error` and the logs, so the
+ # commercial key must not survive in the message. The exception type is kept intact so
+ # callers classify the failure exactly as they did before.
+ session = mock.MagicMock()
+ session.get.side_effect = error
+
+ with pytest.raises(requests.RequestException) as excinfo:
+ _fetch(session, "https://customer-api.open-meteo.com/v1/forecast?apikey=super-secret")
+
+ assert isinstance(excinfo.value, type(error))
+ assert "super-secret" not in str(excinfo.value)
+ assert "apikey=REDACTED" in str(excinfo.value)
+ # The original, unredacted exception must not ride along as the chained cause either.
+ assert excinfo.value.__cause__ is None
+ assert excinfo.value.__context__ is None or excinfo.value.__suppress_context__
+
+ def test_a_subclass_that_cannot_be_rebuilt_still_has_the_key_stripped(self) -> None:
+ # Some `RequestException` subclasses take a stricter signature than a single message
+ # (`JSONDecodeError`, for one). Losing the exact class is acceptable; leaking the key is not.
+ class StrictError(requests.RequestException):
+ def __init__(self, message: str, code: int) -> None:
+ super().__init__(message)
+ self.code = code
+
+ session = mock.MagicMock()
+ session.get.side_effect = StrictError("failed for url: /v1/forecast?apikey=super-secret", 7)
+
+ with pytest.raises(requests.RequestException) as excinfo:
+ _fetch(session, "https://customer-api.open-meteo.com/v1/forecast?apikey=super-secret")
+
+ assert "super-secret" not in str(excinfo.value)
+ assert "apikey=REDACTED" in str(excinfo.value)
+
+
+class TestResolveArchiveRange:
+ TODAY = date(2026, 6, 1)
+
+ def test_falls_back_to_a_bounded_backfill_when_nothing_is_configured(self) -> None:
+ start, end = resolve_archive_range(None, None, self.TODAY)
+
+ assert end == self.TODAY
+ assert (self.TODAY - start).days == DEFAULT_ARCHIVE_BACKFILL_DAYS
+
+ def test_uses_the_configured_start_date(self) -> None:
+ assert resolve_archive_range(date(2020, 1, 1), None, self.TODAY) == (date(2020, 1, 1), self.TODAY)
+
+ @pytest.mark.parametrize(
+ "watermark",
+ [datetime(2026, 5, 20, 6, 0, tzinfo=UTC), date(2026, 5, 20), "2026-05-20T06:00"],
+ )
+ def test_watermark_wins_over_the_configured_start(self, watermark: Any) -> None:
+ start, end = resolve_archive_range(date(2020, 1, 1), watermark, self.TODAY)
+
+ assert start == date(2026, 5, 20)
+ assert end == self.TODAY
+
+ def test_returns_an_empty_range_once_the_watermark_reaches_today(self) -> None:
+ start, end = resolve_archive_range(None, datetime(2026, 6, 2, tzinfo=UTC), self.TODAY)
+
+ assert start > end
+
+
+class TestArchiveWindowing:
+ def _run(
+ self, manager: FakeResumeManager, responses: list[mock.MagicMock], start: str
+ ) -> tuple[list[list[dict[str, Any]]], mock.MagicMock]:
+ session = _fake_session(responses)
+ with mock.patch(f"{MODULE}.make_tracked_session", return_value=session):
+ batches = list(
+ get_rows(
+ endpoint_name="weather_archive_hourly",
+ locations=[LONDON, NEW_YORK],
+ api_key=None,
+ configured_start=date.fromisoformat(start),
+ db_incremental_field_last_value=None,
+ resumable_source_manager=manager,
+ logger=structlog.get_logger(),
+ )
+ )
+ return batches, session
+
+ @freeze_time("2026-03-01")
+ def test_covers_every_location_within_a_window_before_advancing(self) -> None:
+ manager = FakeResumeManager()
+ responses = [_response(200, _hourly_body(["2026-01-01T00:00"], temperature_2m=[1.0])) for _ in range(4)]
+
+ batches, session = self._run(manager, responses, "2026-01-01")
+
+ windows = [(_query(url)["start_date"][0], _query(url)["end_date"][0]) for url in _requested_urls(session)]
+ latitudes = [_query(url)["latitude"][0] for url in _requested_urls(session)]
+
+ # Windows outermost, locations innermost. Locations outermost would let the pipeline
+ # checkpoint the watermark at London's newest row while New York still had history to fetch.
+ assert windows == [
+ ("2026-01-01", "2026-01-31"),
+ ("2026-01-01", "2026-01-31"),
+ ("2026-02-01", "2026-03-01"),
+ ("2026-02-01", "2026-03-01"),
+ ]
+ assert latitudes == ["51.5074", "40.7128", "51.5074", "40.7128"]
+ # One batch per window, holding both locations' rows.
+ assert [len(batch) for batch in batches] == [2, 2]
+
+ @freeze_time("2026-03-01")
+ def test_windows_are_contiguous_and_never_overlap(self) -> None:
+ manager = FakeResumeManager()
+ responses = [_response(200, _hourly_body(["2026-01-01T00:00"], temperature_2m=[1.0])) for _ in range(4)]
+
+ _, session = self._run(manager, responses, "2026-01-01")
+
+ boundaries = [
+ (date.fromisoformat(_query(url)["start_date"][0]), date.fromisoformat(_query(url)["end_date"][0]))
+ for url in _requested_urls(session)
+ ]
+ first, second = boundaries[0], boundaries[2]
+ assert (first[1] - first[0]).days == ARCHIVE_WINDOW_DAYS - 1
+ assert (second[0] - first[1]).days == 1
+
+ @freeze_time("2026-03-01")
+ def test_checkpoints_after_each_window_and_clears_on_completion(self) -> None:
+ manager = FakeResumeManager()
+ responses = [_response(200, _hourly_body(["2026-01-01T00:00"], temperature_2m=[1.0])) for _ in range(4)]
+
+ self._run(manager, responses, "2026-01-01")
+
+ assert [state.next_start_date for state in manager.saved] == ["2026-02-01", "2026-03-02"]
+ assert manager.cleared is True
+
+ @freeze_time("2026-03-01")
+ def test_resumes_from_the_saved_window(self) -> None:
+ manager = FakeResumeManager(OpenMeteoResumeConfig(next_start_date="2026-02-01"))
+ responses = [_response(200, _hourly_body(["2026-02-01T00:00"], temperature_2m=[1.0])) for _ in range(2)]
+
+ _, session = self._run(manager, responses, "2026-01-01")
+
+ assert [_query(url)["start_date"][0] for url in _requested_urls(session)] == ["2026-02-01", "2026-02-01"]
+
+ @freeze_time("2026-03-01")
+ def test_makes_no_requests_when_the_watermark_is_already_current(self) -> None:
+ manager = FakeResumeManager()
+ session = _fake_session([])
+
+ with mock.patch(f"{MODULE}.make_tracked_session", return_value=session):
+ batches = list(
+ get_rows(
+ endpoint_name="weather_archive_hourly",
+ locations=[LONDON],
+ api_key=None,
+ configured_start=None,
+ db_incremental_field_last_value=datetime(2026, 3, 5, tzinfo=UTC),
+ resumable_source_manager=manager,
+ logger=structlog.get_logger(),
+ )
+ )
+
+ assert batches == []
+ assert session.get.call_count == 0
+
+
+class TestRollingEndpoints:
+ def _run(
+ self, manager: FakeResumeManager, responses: list[mock.MagicMock], locations: list[Location]
+ ) -> tuple[list[list[dict[str, Any]]], mock.MagicMock]:
+ session = _fake_session(responses)
+ with mock.patch(f"{MODULE}.make_tracked_session", return_value=session):
+ batches = list(
+ get_rows(
+ endpoint_name="weather_forecast_hourly",
+ locations=locations,
+ api_key=None,
+ configured_start=None,
+ db_incremental_field_last_value=None,
+ resumable_source_manager=manager,
+ logger=structlog.get_logger(),
+ )
+ )
+ return batches, session
+
+ def test_one_request_and_batch_per_location_with_no_date_window(self) -> None:
+ manager = FakeResumeManager()
+ responses = [_response(200, _hourly_body(["2026-01-01T00:00"], temperature_2m=[1.0])) for _ in range(2)]
+
+ batches, session = self._run(manager, responses, [LONDON, NEW_YORK])
+
+ assert len(batches) == 2
+ assert all("start_date" not in _query(url) for url in _requested_urls(session))
+ assert [state.location_index for state in manager.saved] == [1, 2]
+ assert manager.cleared is True
+
+ def test_resumes_from_the_saved_location_index(self) -> None:
+ manager = FakeResumeManager(OpenMeteoResumeConfig(location_index=1))
+ responses = [_response(200, _hourly_body(["2026-01-01T00:00"], temperature_2m=[1.0]))]
+
+ _, session = self._run(manager, responses, [LONDON, NEW_YORK])
+
+ assert [_query(url)["latitude"][0] for url in _requested_urls(session)] == ["40.7128"]
+
+
+class TestOpenMeteoSourceResponse:
+ @pytest.mark.parametrize("endpoint_name", sorted(OPEN_METEO_ENDPOINTS))
+ def test_response_metadata_matches_the_endpoint_catalog(self, endpoint_name: str) -> None:
+ response = open_meteo_source(
+ endpoint_name=endpoint_name,
+ locations_raw="51.5,-0.12",
+ api_key=None,
+ start_date_raw=None,
+ db_incremental_field_last_value=None,
+ resumable_source_manager=FakeResumeManager(),
+ logger=structlog.get_logger(),
+ )
+
+ endpoint = OPEN_METEO_ENDPOINTS[endpoint_name]
+ assert response.name == endpoint_name
+ assert response.primary_keys == endpoint.primary_keys
+ assert response.partition_mode == "datetime"
+ assert response.partition_keys == ["time_utc"]
+ assert response.partition_format == endpoint.partition_format
+ assert response.sort_mode == "asc"
+
+ def test_bad_locations_fail_before_any_request_is_made(self) -> None:
+ with pytest.raises(ValueError, match="out of range"):
+ open_meteo_source(
+ endpoint_name="weather_current",
+ locations_raw="91,0",
+ api_key=None,
+ start_date_raw=None,
+ db_incremental_field_last_value=None,
+ resumable_source_manager=FakeResumeManager(),
+ logger=structlog.get_logger(),
+ )
+
+
+class TestValidateCredentials:
+ @pytest.mark.parametrize(
+ "locations,start_date,message",
+ [
+ ("", None, "At least one location"),
+ ("91,0", None, "out of range"),
+ ("51.5,-0.12", "01/01/2024", "YYYY-MM-DD"),
+ ],
+ )
+ def test_rejects_bad_config_without_calling_the_api(
+ self, locations: str, start_date: str | None, message: str
+ ) -> None:
+ with mock.patch(f"{MODULE}.make_tracked_session") as make_session:
+ ok, error = validate_credentials(locations, None, start_date)
+
+ assert ok is False
+ assert error is not None and message in error
+ assert make_session.call_count == 0
+
+ @pytest.mark.parametrize(
+ "status,body,expected_ok,expected_message",
+ [
+ (200, {}, True, None),
+ (401, {"reason": "Invalid API key"}, False, "rejected the API key"),
+ (400, {"reason": "Latitude must be in range of -90 to 90"}, False, "Latitude must be in range"),
+ (500, {}, False, "status 500"),
+ ],
+ )
+ def test_maps_status_codes(
+ self, status: int, body: dict[str, Any], expected_ok: bool, expected_message: str | None
+ ) -> None:
+ session = _fake_session([_response(status, body)])
+
+ with mock.patch(f"{MODULE}.make_tracked_session", return_value=session):
+ ok, error = validate_credentials("51.5,-0.12", None, None)
+
+ assert ok is expected_ok
+ if expected_message is None:
+ assert error is None
+ else:
+ assert error is not None and expected_message in error
+
+ def test_non_json_error_body_still_reports_the_status(self) -> None:
+ response = _response(500, {})
+ response.json.side_effect = ValueError("not json")
+ session = _fake_session([response])
+
+ with mock.patch(f"{MODULE}.make_tracked_session", return_value=session):
+ ok, error = validate_credentials("51.5,-0.12", None, None)
+
+ assert ok is False
+ assert error == "Open-Meteo returned status 500"
+
+ def test_unreachable_api_is_reported_as_a_retryable_message(self) -> None:
+ session = mock.MagicMock()
+ session.get.side_effect = requests.ConnectionError("boom")
+
+ with mock.patch(f"{MODULE}.make_tracked_session", return_value=session):
+ ok, error = validate_credentials("51.5,-0.12", None, None)
+
+ assert ok is False
+ assert error == "Could not reach the Open-Meteo API. Please try again."
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/open_meteo/tests/test_open_meteo_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/open_meteo/tests/test_open_meteo_source.py
new file mode 100644
index 000000000000..c1c667a40743
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/open_meteo/tests/test_open_meteo_source.py
@@ -0,0 +1,185 @@
+from collections.abc import Iterable
+from typing import Any, cast
+
+import pytest
+from unittest import mock
+
+import structlog
+
+from posthog.schema import ReleaseStatus, SourceFieldInputConfig, SourceFieldInputConfigType
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import error_message_matches
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceInputs
+from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.openmeteo import (
+ OpenMeteoSourceConfig,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.open_meteo.canonical_descriptions import (
+ CANONICAL_DESCRIPTIONS,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.open_meteo.open_meteo import OpenMeteoResumeConfig
+from products.warehouse_sources.backend.temporal.data_imports.sources.open_meteo.settings import (
+ ARCHIVE_LOOKBACK_SECONDS,
+ ENDPOINTS,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.open_meteo.source import OpenMeteoSource
+from products.warehouse_sources.backend.types import ExternalDataSourceType
+
+SOURCE_MODULE = "products.warehouse_sources.backend.temporal.data_imports.sources.open_meteo.source"
+
+
+def _inputs(
+ schema_name: str = "weather_archive_hourly",
+ should_use_incremental_field: bool = False,
+ db_incremental_field_last_value: Any = None,
+) -> SourceInputs:
+ return SourceInputs(
+ schema_name=schema_name,
+ schema_id="schema-id",
+ source_id="source-id",
+ team_id=123,
+ should_use_incremental_field=should_use_incremental_field,
+ db_incremental_field_last_value=db_incremental_field_last_value,
+ db_incremental_field_earliest_value=None,
+ incremental_field="time_utc",
+ incremental_field_type=None,
+ job_id="job-id",
+ logger=structlog.get_logger(),
+ reset_pipeline=False,
+ )
+
+
+class TestOpenMeteoSource:
+ def setup_method(self) -> None:
+ self.source = OpenMeteoSource()
+ self.team_id = 123
+ self.config = OpenMeteoSourceConfig(locations="51.5,-0.12,London", start_date="2024-01-01", api_key=None)
+
+ def test_source_type(self) -> None:
+ assert self.source.source_type == ExternalDataSourceType.OPENMETEO
+
+ def test_source_config_is_released_as_alpha(self) -> None:
+ config = self.source.get_source_config
+
+ # `unreleasedSource` hides the connector from users entirely, so a finished source must not set it.
+ assert config.unreleasedSource is None
+ assert config.releaseStatus == ReleaseStatus.ALPHA
+ assert config.name.value == "OpenMeteo"
+ assert config.label == "Open-Meteo"
+ assert config.iconPath == "/static/services/open_meteo.png"
+
+ def test_source_config_fields(self) -> None:
+ fields = self.source.get_source_config.fields
+ by_name = {field.name: field for field in fields if isinstance(field, SourceFieldInputConfig)}
+
+ assert set(by_name) == {"locations", "start_date", "api_key"}
+ assert by_name["locations"].type == SourceFieldInputConfigType.TEXTAREA
+ assert by_name["locations"].required is True
+ # Open-Meteo's core API is keyless, so a commercial key must stay optional.
+ assert by_name["api_key"].required is False
+ assert by_name["api_key"].type == SourceFieldInputConfigType.PASSWORD
+ assert by_name["api_key"].secret is True
+ assert by_name["start_date"].required is False
+ assert by_name["start_date"].secret is False
+
+ def test_get_schemas_lists_every_endpoint(self) -> None:
+ schemas = self.source.get_schemas(self.config, self.team_id)
+
+ assert [schema.name for schema in schemas] == list(ENDPOINTS)
+ assert all(schema.detected_primary_keys == ["location_id", "time_utc"] for schema in schemas)
+
+ @pytest.mark.parametrize(
+ "schema_name,supports_incremental,supports_append,lookback",
+ [
+ ("weather_archive_hourly", True, True, ARCHIVE_LOOKBACK_SECONDS),
+ ("weather_archive_daily", True, True, ARCHIVE_LOOKBACK_SECONDS),
+ # Forecast values for a given timestamp are revised on every model run and the newest
+ # timestamp is in the future, so neither a merge watermark nor an append cursor works.
+ ("weather_forecast_hourly", False, False, None),
+ ("weather_forecast_daily", False, False, None),
+ ("air_quality_hourly", False, False, None),
+ # No server-side timestamp filter exists for current conditions, so append only.
+ ("weather_current", False, True, None),
+ ],
+ )
+ def test_sync_capabilities_per_schema(
+ self, schema_name: str, supports_incremental: bool, supports_append: bool, lookback: int | None
+ ) -> None:
+ schema = self.source.get_schemas(self.config, self.team_id, names=[schema_name])[0]
+
+ assert schema.supports_incremental is supports_incremental
+ assert schema.supports_append is supports_append
+ assert schema.default_incremental_lookback_seconds == lookback
+ assert bool(schema.incremental_fields) is (supports_incremental or supports_append)
+
+ def test_get_schemas_filters_by_name(self) -> None:
+ schemas = self.source.get_schemas(self.config, self.team_id, names=["weather_current", "air_quality_hourly"])
+
+ assert {schema.name for schema in schemas} == {"weather_current", "air_quality_hourly"}
+
+ def test_documented_tables_are_listed_without_credentials(self) -> None:
+ tables = self.source.get_documented_tables()
+
+ assert [table["name"] for table in tables] == list(ENDPOINTS)
+ assert all(table["description"] for table in tables)
+
+ def test_canonical_descriptions_cover_every_schema(self) -> None:
+ assert set(CANONICAL_DESCRIPTIONS) == set(ENDPOINTS)
+
+ @pytest.mark.parametrize(
+ "raised_message",
+ [
+ "Open-Meteo rejected the API key (status 401): Invalid API key",
+ "Open-Meteo rejected the request (status 400): Latitude must be in range of -90 to 90",
+ ],
+ )
+ def test_transport_errors_match_the_non_retryable_patterns(self, raised_message: str) -> None:
+ # The transport builds these strings; a reworded message there would silently make the source
+ # retry a permanent failure forever.
+ assert error_message_matches(raised_message, self.source.get_non_retryable_errors().keys())
+
+ def test_validate_credentials_delegates_to_the_transport(self) -> None:
+ with mock.patch(f"{SOURCE_MODULE}.validate_open_meteo_credentials", return_value=(True, None)) as validate:
+ assert self.source.validate_credentials(self.config, self.team_id) == (True, None)
+
+ validate.assert_called_once_with("51.5,-0.12,London", None, "2024-01-01")
+
+ def test_resumable_manager_is_namespaced_per_schema(self) -> None:
+ manager = self.source.get_resumable_source_manager(_inputs("weather_current"))
+
+ assert isinstance(manager, ResumableSourceManager)
+ assert manager._data_class is OpenMeteoResumeConfig
+ # The archive stores a date and the rolling endpoints a location index. Sharing one Redis key
+ # would let a retry that switches schema load a cursor the other endpoint cannot use.
+ assert manager._namespace == "weather_current"
+
+ @pytest.mark.parametrize(
+ "should_use_incremental_field,expected_last_value",
+ [(True, "2026-01-01T00:00"), (False, None)],
+ )
+ def test_source_for_pipeline_only_passes_the_watermark_on_incremental_runs(
+ self, should_use_incremental_field: bool, expected_last_value: str | None
+ ) -> None:
+ inputs = _inputs(
+ should_use_incremental_field=should_use_incremental_field,
+ db_incremental_field_last_value="2026-01-01T00:00",
+ )
+ manager = mock.MagicMock()
+
+ with mock.patch(f"{SOURCE_MODULE}.open_meteo_source") as open_meteo_source:
+ self.source.source_for_pipeline(self.config, manager, inputs)
+
+ kwargs = open_meteo_source.call_args.kwargs
+ assert kwargs["endpoint_name"] == "weather_archive_hourly"
+ assert kwargs["locations_raw"] == "51.5,-0.12,London"
+ assert kwargs["start_date_raw"] == "2024-01-01"
+ assert kwargs["db_incremental_field_last_value"] == expected_last_value
+
+ def test_source_for_pipeline_returns_a_lazy_response(self) -> None:
+ response = self.source.source_for_pipeline(self.config, mock.MagicMock(), _inputs("weather_current"))
+
+ assert response.name == "weather_current"
+ assert response.primary_keys == ["location_id", "time_utc"]
+ # Building the response must not reach the API; only iterating it does.
+ assert callable(response.items)
+ assert isinstance(cast("Iterable[Any]", response.items()), Iterable)