: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.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(data-warehouse): add Meteostat import source (#84373)
Tom Owers6e764a18d097
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/meteostat.py b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/meteostat.pyindex 75d4db204e52..1107191a2dc9 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/meteostat.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/meteostat.py@@ -1,9 +1,14 @@# This file is automatically generated from `SourceRegistry.get_all_sources()`# Do not edit manually - run `pnpm generate:source-configs` to regenerate.+from typing import Literal+from products.warehouse_sources.backend.temporal.data_imports.sources.common import config@config.configclass MeteostatSourceConfig(config.Config):- pass+ api_key: str+ station_ids: str+ units: Literal["metric", "imperial", "scientific"] = config.value(default="metric")+ start_date: str | None = Nonediff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/meteostat/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/meteostat/canonical_descriptions.pynew file mode 100644index 000000000000..2e87fef1be03--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/meteostat/canonical_descriptions.py@@ -0,0 +1,73 @@+"""Canonical, documentation-sourced descriptions for Meteostat endpoints and columns.++Sourced from the official Meteostat JSON API reference (https://dev.meteostat.net/api). Keyed by+the resource names in `settings.py` `ENDPOINTS`, which match the `ExternalDataSchema.name` of a+synced Meteostat table. Columns absent here fall back to LLM enrichment.+"""++from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (+ CanonicalDescriptions,+)++_STATION_ID_COLUMN = "Meteostat weather station ID this record belongs to, as configured in the source settings."++CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {+ "Hourly": {+ "description": "Historical hourly weather observations for a station, with gaps optionally filled "+ "by statistically optimized model data.",+ "docs_url": "https://dev.meteostat.net/api/stations/hourly",+ "columns": {+ "station_id": _STATION_ID_COLUMN,+ "time": "Time of observation (YYYY-MM-DD hh:mm:ss).",+ "temp": "The air temperature in °C.",+ "dwpt": "The dew point in °C.",+ "rhum": "The relative humidity in percent (%).",+ "prcp": "The one hour precipitation total in mm.",+ "snow": "The snow depth in mm.",+ "wdir": "The wind direction in degrees (°).",+ "wspd": "The average wind speed in km/h.",+ "wpgt": "The peak wind gust in km/h.",+ "pres": "The sea-level air pressure in hPa.",+ "tsun": "The one hour sunshine total in minutes (m).",+ "coco": "The weather condition code.",+ },+ },+ "Daily": {+ "description": "Historical daily weather statistics for a station, aggregated from observations and "+ "model data.",+ "docs_url": "https://dev.meteostat.net/api/stations/daily",+ "columns": {+ "station_id": _STATION_ID_COLUMN,+ "date": "The date (YYYY-MM-DD).",+ "tavg": "The average air temperature in °C.",+ "tmin": "The minimum air temperature in °C.",+ "tmax": "The maximum air temperature in °C.",+ "prcp": "The daily precipitation total in mm.",+ "snow": "The maximum snow depth in mm.",+ "wdir": "The average wind direction in degrees (°).",+ "wspd": "The average wind speed in km/h.",+ "wpgt": "The peak wind gust in km/h.",+ "pres": "The average sea-level air pressure in hPa.",+ "tsun": "The daily sunshine total in minutes (m).",+ },+ },+ "Monthly": {+ "description": "Historical monthly weather statistics for a station, aggregated from hourly "+ "observations, daily records, and model data.",+ "docs_url": "https://dev.meteostat.net/api/stations/monthly",+ "columns": {+ "station_id": _STATION_ID_COLUMN,+ "date": "The first date (YYYY-MM-DD) of the month.",+ "tavg": "The average daily air temperature in °C.",+ "tmin": "The average daily minimum air temperature in °C.",+ "tmax": "The average daily maximum air temperature in °C.",+ "prcp": "The monthly precipitation total in mm.",+ "snow": "The maximum snow depth in mm.",+ "wdir": "The average wind direction in degrees (°).",+ "wspd": "The average wind speed in km/h.",+ "wpgt": "The peak wind gust in km/h.",+ "pres": "The average sea-level air pressure in hPa.",+ "tsun": "The monthly sunshine total in minutes (m).",+ },+ },+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/meteostat/meteostat.py b/products/warehouse_sources/backend/temporal/data_imports/sources/meteostat/meteostat.pynew file mode 100644index 000000000000..5470430c0bc9--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/meteostat/meteostat.py@@ -0,0 +1,252 @@+import dataclasses+from collections.abc import Iterator+from datetime import UTC, date, datetime, timedelta+from typing import Any, Optional+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.meteostat.settings import (+ BASE_URL,+ DEFAULT_START_DATE,+ DEFAULT_UNITS,+ INCREMENTAL_OVERLAP_DAYS,+ MAX_STATIONS,+ METEOSTAT_ENDPOINTS,+ MINIMUM_START_DATE,+ MeteostatEndpointConfig,+)++REQUEST_TIMEOUT_SECONDS = 60++NO_STATIONS_ERROR = "No weather station IDs configured"++_TIME_FORMATS = ("%Y-%m-%d %H:%M:%S", "%Y-%m-%d")++[email protected](frozen=True)+class MeteostatResumeConfig:+ # Index into the configured station list of the station currently being fetched.+ station_index: int+ # ISO date (YYYY-MM-DD) of the first day the next window should fetch for that station.+ next_start: str+++def _parse_station_ids(station_ids: Optional[str]) -> list[str]:+ if not station_ids:+ return []+ # Bound the number of parts split() ever materializes, regardless of how many commas the+ # input contains, so a pathological string can't burn worker memory before the MAX_STATIONS+ # check downstream ever runs.+ stations: list[str] = []+ seen: set[str] = set()+ for raw in station_ids.split(",", MAX_STATIONS)[: MAX_STATIONS + 1]:+ station = raw.strip()+ if station and station not in seen:+ seen.add(station)+ stations.append(station)+ return stations+++def _coerce_date(value: Any) -> Optional[date]:+ if isinstance(value, datetime):+ return value.date()+ if isinstance(value, date):+ return value+ if isinstance(value, str):+ try:+ return date.fromisoformat(value.strip())+ except ValueError:+ return None+ return None+++def start_date_error(start_date: Optional[str]) -> Optional[str]:+ """Validation-time check for a too-old `start_date`.++ A parsed value earlier than `MINIMUM_START_DATE` is rejected here (credential validation)+ so a new source can't be configured to run away, and re-checked in `_get_rows` so a+ previously stored configuration can't either. An unparseable value is left to the existing+ per-field validation rather than duplicated here.+ """+ parsed = _coerce_date(start_date) if start_date else None+ if parsed is not None and parsed < MINIMUM_START_DATE:+ return f"Start date can't be earlier than {MINIMUM_START_DATE.isoformat()}."+ return None+++def _parse_timestamp(value: Any) -> Any:+ """Parse a Meteostat `time`/`date` string into a `datetime` for correct downstream typing.++ Falls back to the raw value when it doesn't match either observed format, so an+ unexpected response shape doesn't drop the row.+ """+ if not isinstance(value, str):+ return value+ for fmt in _TIME_FORMATS:+ try:+ return datetime.strptime(value, fmt)+ except ValueError:+ continue+ return value+++def _request_headers(api_key: str) -> dict[str, str]:+ return {"x-rapidapi-key": api_key, "x-rapidapi-host": "meteostat.p.rapidapi.com"}+++def _fetch_window(+ session: requests.Session,+ headers: dict[str, str],+ endpoint: MeteostatEndpointConfig,+ station_id: str,+ window_start: date,+ window_end: date,+ units: str,+) -> list[dict[str, Any]]:+ params: dict[str, str] = {+ "station": station_id,+ "start": window_start.isoformat(),+ "end": window_end.isoformat(),+ }+ if units != DEFAULT_UNITS:+ params["units"] = units+ url = f"{BASE_URL}{endpoint.path}?{urlencode(params)}"+ response = session.get(url, headers=headers, timeout=REQUEST_TIMEOUT_SECONDS)+ response.raise_for_status()++ data = response.json().get("data")+ return data if isinstance(data, list) else []+++def _get_rows(+ api_key: str,+ station_ids: str,+ endpoint: MeteostatEndpointConfig,+ units: str,+ start_date: Optional[str],+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[MeteostatResumeConfig],+ should_use_incremental_field: bool,+ db_incremental_field_last_value: Any,+) -> Iterator[list[dict[str, Any]]]:+ stations = _parse_station_ids(station_ids)+ if not stations:+ raise ValueError(NO_STATIONS_ERROR)+ if len(stations) > MAX_STATIONS:+ logger.warning(f"Meteostat: {len(stations)} station IDs configured, syncing only the first {MAX_STATIONS}")+ stations = stations[:MAX_STATIONS]++ session = make_tracked_session(redact_values=(api_key,))+ headers = _request_headers(api_key)++ # Re-checked here (not just at credential validation) so a configuration stored before this+ # floor existed can't schedule a runaway backfill either.+ base_start = max(_coerce_date(start_date) or DEFAULT_START_DATE, MINIMUM_START_DATE)+ if should_use_incremental_field:+ last_value = _coerce_date(db_incremental_field_last_value)+ if last_value is not None:+ # Re-fetch a trailing overlap window: weather services can revise recent records+ # for days after they first land, and merge dedupes on the primary key.+ base_start = max(base_start, last_value - timedelta(days=INCREMENTAL_OVERLAP_DAYS))++ end_boundary = datetime.now(UTC).date()++ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None+ start_index = resume.station_index if resume is not None else 0++ for index in range(start_index, len(stations)):+ station_id = stations[index]++ cursor = base_start+ if resume is not None and index == start_index:+ resumed_start = _coerce_date(resume.next_start)+ if resumed_start is not None:+ cursor = resumed_start+ logger.debug(f"Meteostat: resuming {endpoint.name} for station {station_id} from {cursor.isoformat()}")++ while cursor <= end_boundary:+ window_end = min(cursor + timedelta(days=endpoint.window_days - 1), end_boundary)+ data = _fetch_window(session, headers, endpoint, station_id, cursor, window_end, units)++ if data:+ rows = []+ for row in data:+ row = dict(row)+ row["station_id"] = station_id+ row[endpoint.date_field] = _parse_timestamp(row.get(endpoint.date_field))+ rows.append(row)+ yield rows++ cursor = window_end + timedelta(days=1)+ # Save AFTER yielding so a crash re-fetches (and merge dedupes) the last window+ # instead of skipping it.+ resumable_source_manager.save_state(+ MeteostatResumeConfig(station_index=index, next_start=cursor.isoformat())+ )+++def meteostat_source(+ api_key: str,+ station_ids: str,+ units: str,+ start_date: Optional[str],+ endpoint_name: str,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[MeteostatResumeConfig],+ should_use_incremental_field: bool = False,+ db_incremental_field_last_value: Optional[Any] = None,+) -> SourceResponse:+ endpoint = METEOSTAT_ENDPOINTS[endpoint_name]++ return SourceResponse(+ name=endpoint.name,+ items=lambda: _get_rows(+ api_key=api_key,+ station_ids=station_ids,+ endpoint=endpoint,+ units=units,+ start_date=start_date,+ logger=logger,+ resumable_source_manager=resumable_source_manager,+ should_use_incremental_field=should_use_incremental_field,+ db_incremental_field_last_value=db_incremental_field_last_value,+ ),+ primary_keys=endpoint.primary_keys,+ partition_count=1,+ partition_size=1,+ partition_mode="datetime",+ partition_format="month",+ partition_keys=[endpoint.date_field],+ sort_mode="asc",+ )+++def validate_station(api_key: str, station_id: str) -> tuple[bool, Optional[str]]:+ session = make_tracked_session(redact_values=(api_key,))+ try:+ response = session.get(+ f"{BASE_URL}/stations/meta",+ params={"id": station_id},+ headers=_request_headers(api_key),+ timeout=REQUEST_TIMEOUT_SECONDS,+ )+ except requests.RequestException as e:+ return False, f"Could not reach the Meteostat API ({e}). Please retry."++ if response.status_code == 200:+ return True, None+ if response.status_code == 401:+ return False, "Invalid RapidAPI key. Check the key and try again."+ if response.status_code == 403:+ return (+ False,+ "This RapidAPI key isn't subscribed to the Meteostat API. Subscribe on RapidAPI and try again.",+ )+ if response.status_code == 404:+ return False, f"Weather station '{station_id}' was not found. Check the station ID and try again."+ return False, f"Unexpected response from the Meteostat API (status {response.status_code})."diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/meteostat/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/meteostat/settings.pynew file mode 100644index 000000000000..ce37a00226c4--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/meteostat/settings.py@@ -0,0 +1,92 @@+from dataclasses import dataclass+from datetime import date++from products.warehouse_sources.backend.temporal.data_imports.sources.common.schema import incremental_field+from products.warehouse_sources.backend.types import IncrementalField++BASE_URL = "https://meteostat.p.rapidapi.com"+API_HOST = "meteostat.p.rapidapi.com"++HOURLY_ENDPOINT = "Hourly"+DAILY_ENDPOINT = "Daily"+MONTHLY_ENDPOINT = "Monthly"+++@dataclass(frozen=True)+class MeteostatEndpointConfig:+ name: str+ path: str+ date_field: str+ # Per-request date-range cap the vendor enforces, expressed as a chunk size so a+ # multi-year backfill is split into requests the API will actually accept.+ window_days: int+ primary_keys: list[str]+ description: str+++METEOSTAT_ENDPOINTS: dict[str, MeteostatEndpointConfig] = {+ HOURLY_ENDPOINT: MeteostatEndpointConfig(+ name=HOURLY_ENDPOINT,+ path="/stations/hourly",+ date_field="time",+ # Vendor docs: "Hourly data can be queried for a maximum of 30 days per request."+ window_days=30,+ primary_keys=["station_id", "time"],+ description="Historical hourly weather observations for a station, with optional model gap-filling.",+ ),+ DAILY_ENDPOINT: MeteostatEndpointConfig(+ name=DAILY_ENDPOINT,+ path="/stations/daily",+ date_field="date",+ # Vendor docs: "Daily data can be queried for a maximum of 10 years per request."+ window_days=365 * 10,+ primary_keys=["station_id", "date"],+ description="Historical daily weather statistics for a station, aggregated from observations and model data.",+ ),+ MONTHLY_ENDPOINT: MeteostatEndpointConfig(+ name=MONTHLY_ENDPOINT,+ path="/stations/monthly",+ date_field="date",+ # The vendor's monthly docs don't publish an explicit per-request range cap; reuse the+ # documented daily cap as a conservative window size rather than guessing a larger one.+ window_days=365 * 10,+ primary_keys=["station_id", "date"],+ description="Historical monthly weather statistics for a station, aggregated from observations, daily records, and model data.",+ ),+}++ENDPOINTS = tuple(METEOSTAT_ENDPOINTS.keys())++INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {+ name: [incremental_field(config.date_field)] for name, config in METEOSTAT_ENDPOINTS.items()+}++UNITS_OPTIONS = (+ ("metric", "Metric (°C, mm, km/h)"),+ ("imperial", "Imperial (°F, in, mph)"),+ ("scientific", "Scientific (K, mm, m/s)"),+)+DEFAULT_UNITS = "metric"++# A weather station has no PostHog-visible creation date, so there's no vendor-documented+# earliest-record date to default to. This bounds how far back a first (full-refresh) sync+# reaches, keeping the request count predictable against the RapidAPI free tier's 500+# requests/month cap. Users can set an earlier start date once they've sized their plan.+DEFAULT_START_DATE = date(2015, 1, 1)++# Hard floor for any configured start date, including previously stored configurations. Without+# this, an authenticated user (or a stale stored config) can set an arbitrarily old start date —+# e.g. `0001-01-01` — and, fanned out across MAX_STATIONS, schedule an effectively unbounded+# number of sequential request windows and Redis checkpoints against a single resumable sync.+# Automated station networks with any meaningful density don't predate this by much, so it costs+# little real history while keeping the worst case bounded and predictable.+MINIMUM_START_DATE = date(1950, 1, 1)++# Historical values can be revised by the underlying weather services for several days after+# they first land, so incremental syncs re-fetch a trailing window instead of resuming exactly+# at the last synced date.+INCREMENTAL_OVERLAP_DAYS = 7++# Each station costs at least one request per date window; an unbounded list can silently burn+# a whole month's free-tier quota in a single sync.+MAX_STATIONS = 25diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/meteostat/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/meteostat/source.pyindex 764c209ab366..edc0d527f164 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/meteostat/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/meteostat/source.py@@ -1,32 +1,186 @@-from typing import cast+from typing import Optional, castfrom posthog.schema import (DataWarehouseSourceCategory,ExternalDataSourceType as SchemaExternalDataSourceType,+ ReleaseStatus,SourceConfig,+ SourceFieldInputConfig,+ SourceFieldInputConfigType,+ SourceFieldSelectConfig,+ SourceFieldSelectConfigOption,)-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,+ build_endpoint_schemas,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceInputs, SourceResponsefrom products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.meteostat import (MeteostatSourceConfig,)+from products.warehouse_sources.backend.temporal.data_imports.sources.meteostat.meteostat import (+ NO_STATIONS_ERROR,+ MeteostatResumeConfig,+ _parse_station_ids,+ meteostat_source,+ start_date_error,+ validate_station,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.meteostat.settings import (+ ENDPOINTS,+ INCREMENTAL_FIELDS,+ MAX_STATIONS,+ UNITS_OPTIONS,+)from products.warehouse_sources.backend.types import ExternalDataSourceType@SourceRegistry.register-class MeteostatSource(SimpleSource[MeteostatSourceConfig]):+class MeteostatSource(ResumableSource[MeteostatSourceConfig, MeteostatResumeConfig]):+ lists_tables_without_credentials = True # static endpoint catalog — safe for public docs+ # No meaningful vendor versioning: the RapidAPI-hosted JSON API has never published a+ # version token (path segment, header, or query param) to pin.+ api_docs_url = "https://dev.meteostat.net/api"+@propertydef source_type(self) -> ExternalDataSourceType:return ExternalDataSourceType.METEOSTAT+ def get_non_retryable_errors(self) -> dict[str, str | None]:+ return {+ "401 Client Error": "Invalid RapidAPI key. Check the key and reconnect the source.",+ "403 Client Error": (+ "This RapidAPI key isn't subscribed to the Meteostat API. Subscribe on RapidAPI and reconnect."+ ),+ NO_STATIONS_ERROR: "Add at least one weather station ID in the source settings to sync this table.",+ }++ def get_canonical_descriptions(self) -> CanonicalDescriptions:+ from products.warehouse_sources.backend.temporal.data_imports.sources.meteostat.canonical_descriptions import (+ CANONICAL_DESCRIPTIONS,+ )++ return CANONICAL_DESCRIPTIONS++ def get_schemas(+ self,+ config: MeteostatSourceConfig,+ team_id: int,+ with_counts: bool = False,+ names: list[str] | None = None,+ force_refresh: bool = False,+ api_version: str | None = None,+ ) -> list[SourceSchema]:+ return build_endpoint_schemas(ENDPOINTS, INCREMENTAL_FIELDS, names)++ def validate_credentials(+ self,+ config: MeteostatSourceConfig,+ team_id: int,+ schema_name: Optional[str] = None,+ api_version: str | None = None,+ ) -> tuple[bool, str | None]:+ stations = _parse_station_ids(config.station_ids)+ if not stations:+ return False, "Add at least one weather station ID to sync."+ if len(stations) > MAX_STATIONS:+ return False, f"Too many station IDs. List at most {MAX_STATIONS}."++ error = start_date_error(config.start_date)+ if error is not None:+ return False, error++ return validate_station(config.api_key, stations[0])++ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[MeteostatResumeConfig]:+ return ResumableSourceManager[MeteostatResumeConfig](inputs, MeteostatResumeConfig)++ def source_for_pipeline(+ self,+ config: MeteostatSourceConfig,+ resumable_source_manager: ResumableSourceManager[MeteostatResumeConfig],+ inputs: SourceInputs,+ ) -> SourceResponse:+ return meteostat_source(+ api_key=config.api_key,+ station_ids=config.station_ids,+ units=config.units,+ start_date=config.start_date,+ endpoint_name=inputs.schema_name,+ logger=inputs.logger,+ resumable_source_manager=resumable_source_manager,+ should_use_incremental_field=inputs.should_use_incremental_field,+ db_incremental_field_last_value=inputs.db_incremental_field_last_value+ if inputs.should_use_incremental_field+ else None,+ )+@propertydef get_source_config(self) -> SourceConfig:return SourceConfig(name=SchemaExternalDataSourceType.METEOSTAT,category=DataWarehouseSourceCategory.ANALYTICS,label="Meteostat",+ keywords=["weather", "climate", "historical weather"],+ caption=(+ "Sync historical weather and climate data for weather stations from the Meteostat JSON API "+ "(hosted on RapidAPI). Get a free API key by subscribing to the "+ "[Meteostat API listing](https://rapidapi.com/meteostat/api/meteostat/) on RapidAPI — the free "+ "plan includes 500 requests per month.\n\n"+ "Meteostat has no account-scoped list of stations, so list the "+ "[weather station IDs](https://meteostat.net) you want to sync."+ ),+ docsUrl="https://posthog.com/docs/cdp/sources/meteostat",iconPath="/static/services/meteostat.png",- fields=cast(list[FieldType], []),- unreleasedSource=True,+ fields=cast(+ list[FieldType],+ [+ SourceFieldInputConfig(+ name="api_key",+ label="RapidAPI key",+ type=SourceFieldInputConfigType.PASSWORD,+ required=True,+ placeholder="",+ secret=True,+ ),+ SourceFieldInputConfig(+ name="station_ids",+ label="Weather station IDs",+ type=SourceFieldInputConfigType.TEXT,+ required=True,+ placeholder="10637, 71508",+ secret=False,+ caption=f"Comma-separated list of Meteostat station IDs. Up to {MAX_STATIONS} stations.",+ ),+ SourceFieldSelectConfig(+ name="units",+ label="Unit system",+ required=True,+ defaultValue="metric",+ options=[+ SourceFieldSelectConfigOption(label=label, value=value) for value, label in UNITS_OPTIONS+ ],+ ),+ SourceFieldInputConfig(+ name="start_date",+ label="Start date",+ type=SourceFieldInputConfigType.TEXT,+ required=False,+ placeholder="2015-01-01",+ secret=False,+ caption=(+ "Earliest day to sync (YYYY-MM-DD). Defaults to 2015-01-01 to keep the initial sync "+ "within a typical RapidAPI free-tier quota."+ ),+ ),+ ],+ ),+ releaseStatus=ReleaseStatus.ALPHA,)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/meteostat/tests/test_meteostat.py b/products/warehouse_sources/backend/temporal/data_imports/sources/meteostat/tests/test_meteostat.pynew file mode 100644index 000000000000..592306bafc70--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/meteostat/tests/test_meteostat.py@@ -0,0 +1,328 @@+from datetime import UTC, date, datetime, timedelta+from typing import Any, Optional++import pytest+from freezegun import freeze_time+from unittest import mock++import requests+from parameterized import parameterized++from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from products.warehouse_sources.backend.temporal.data_imports.sources.meteostat.meteostat import (+ NO_STATIONS_ERROR,+ MeteostatResumeConfig,+ _coerce_date,+ _get_rows,+ _parse_station_ids,+ _parse_timestamp,+ meteostat_source,+ start_date_error,+ validate_station,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.meteostat.settings import (+ DAILY_ENDPOINT,+ HOURLY_ENDPOINT,+ MAX_STATIONS,+ METEOSTAT_ENDPOINTS,+ MINIMUM_START_DATE,+ MONTHLY_ENDPOINT,+)++MODULE = "products.warehouse_sources.backend.temporal.data_imports.sources.meteostat.meteostat"+++def _response(status: int = 200, json_body: Any = None) -> mock.MagicMock:+ response = mock.MagicMock(spec=requests.Response)+ response.status_code = status+ response.json.return_value = json_body if json_body is not None else {}+ if status >= 400:+ response.raise_for_status.side_effect = requests.HTTPError(f"{status} error", response=response)+ return response+++def _manager(resume_state: Optional[MeteostatResumeConfig] = None) -> mock.MagicMock:+ manager = mock.MagicMock(spec=ResumableSourceManager)+ manager.can_resume.return_value = resume_state is not None+ manager.load_state.return_value = resume_state+ return manager+++def _run(+ endpoint_name: str,+ session: mock.MagicMock,+ manager: Optional[mock.MagicMock] = None,+ station_ids: str = "10637",+ units: str = "metric",+ start_date: Optional[str] = None,+ should_use_incremental_field: bool = False,+ db_incremental_field_last_value: Any = None,+) -> list[list[dict[str, Any]]]:+ with mock.patch(f"{MODULE}.make_tracked_session", return_value=session):+ return list(+ _get_rows(+ api_key="key-123",+ station_ids=station_ids,+ endpoint=METEOSTAT_ENDPOINTS[endpoint_name],+ units=units,+ start_date=start_date,+ logger=mock.MagicMock(),+ resumable_source_manager=manager if manager is not None else _manager(),+ should_use_incremental_field=should_use_incremental_field,+ db_incremental_field_last_value=db_incremental_field_last_value,+ )+ )+++def _requested_params(session: mock.MagicMock) -> list[dict[str, str]]:+ params = []+ for call in session.get.call_args_list:+ url = call.args[0]+ query = url.split("?", 1)[1]+ pairs = dict(pair.split("=", 1) for pair in query.split("&"))+ params.append(pairs)+ return params+++class TestHelpers:+ @parameterized.expand(+ [+ ("none", None, []),+ ("empty", "", []),+ ("single", "10637", ["10637"]),+ ("commas_and_spaces", "10637, 71508 ,D1234", ["10637", "71508", "D1234"]),+ ("dedupes_repeats", "10637,10637,71508", ["10637", "71508"]),+ ]+ )+ def test_parse_station_ids(self, _name, value, expected):+ assert _parse_station_ids(value) == expected++ def test_parse_station_ids_bounds_split_regardless_of_input_size(self):+ # A pathological input with millions of commas must not make split() materialize+ # millions of parts before the caller's MAX_STATIONS check ever runs.+ station_ids = ",".join(str(i) for i in range(2_000_000))+ stations = _parse_station_ids(station_ids)+ assert len(stations) == MAX_STATIONS + 1+ assert stations[:5] == ["0", "1", "2", "3", "4"]++ @parameterized.expand(+ [+ ("datetime", datetime(2026, 7, 1, 5, tzinfo=UTC), date(2026, 7, 1)),+ ("date", date(2026, 7, 1), date(2026, 7, 1)),+ ("iso", "2026-07-01", date(2026, 7, 1)),+ ("garbage", "not-a-date", None),+ ("none", None, None),+ ]+ )+ def test_coerce_date(self, _name, value, expected):+ assert _coerce_date(value) == expected++ @parameterized.expand(+ [+ ("too_old", "0001-01-01", False),+ ("exactly_at_floor", MINIMUM_START_DATE.isoformat(), True),+ ("comfortably_after_floor", "2015-01-01", True),+ ("none", None, True),+ ("unparsable_left_to_other_validation", "not-a-date", True),+ ]+ )+ def test_start_date_error(self, _name, value, expect_none):+ error = start_date_error(value)+ if expect_none:+ assert error is None+ else:+ assert error is not None and MINIMUM_START_DATE.isoformat() in error++ @parameterized.expand(+ [+ ("hourly", "2019-12-31 23:00:00", datetime(2019, 12, 31, 23, 0, 0)),+ ("daily", "2020-02-01", datetime(2020, 2, 1)),+ ("unparsable", "not-a-timestamp", "not-a-timestamp"),+ ("non_string", 42, 42),+ ("none", None, None),+ ]+ )+ def test_parse_timestamp(self, _name, value, expected):+ assert _parse_timestamp(value) == expected+++class TestGetRows:+ @freeze_time("2026-07-21")+ def test_single_window_rows_tagged_with_station_and_state_saved_after_yield(self):+ session = mock.MagicMock(spec=requests.Session)+ session.get.return_value = _response(json_body={"data": [{"date": "2026-07-18", "tavg": 20.5}]})+ manager = _manager()++ batches = _run(DAILY_ENDPOINT, session, manager, station_ids="10637", start_date="2026-07-18")++ params = _requested_params(session)+ assert params == [{"station": "10637", "start": "2026-07-18", "end": "2026-07-21"}]+ assert len(batches) == 1+ row = batches[0][0]+ assert row["station_id"] == "10637"+ assert row["date"] == datetime(2026, 7, 18)++ saved = [call.args[0] for call in manager.save_state.call_args_list]+ assert saved == [MeteostatResumeConfig(station_index=0, next_start="2026-07-22")]++ @freeze_time("2026-07-21")+ def test_multiple_stations_are_each_queried_across_the_full_range(self):+ session = mock.MagicMock(spec=requests.Session)+ session.get.return_value = _response(json_body={"data": [{"date": "2026-07-18", "tavg": 5.0}]})++ batches = _run(DAILY_ENDPOINT, session, station_ids="10637, 71508", start_date="2026-07-18")++ params = _requested_params(session)+ assert [p["station"] for p in params] == ["10637", "71508"]+ assert [batch[0]["station_id"] for batch in batches] == ["10637", "71508"]++ @freeze_time("2026-08-15")+ def test_long_range_is_chunked_into_contiguous_windows_within_the_vendor_cap(self):+ session = mock.MagicMock(spec=requests.Session)+ session.get.return_value = _response(json_body={"data": []})++ _run(HOURLY_ENDPOINT, session, station_ids="10637", start_date="2026-06-01")++ params = _requested_params(session)+ # Hourly's documented cap is 30 days per request; each window must respect it.+ for entry in params:+ span = date.fromisoformat(entry["end"]) - date.fromisoformat(entry["start"])+ assert span.days <= 29+ # Windows are contiguous: each window starts the day after the previous one ends.+ for previous, current in zip(params, params[1:]):+ assert date.fromisoformat(current["start"]) == date.fromisoformat(previous["end"]) + timedelta(days=1)+ assert date.fromisoformat(params[-1]["end"]) == date(2026, 8, 15)++ @freeze_time("2026-07-21")+ def test_incremental_start_uses_overlap_window(self):+ session = mock.MagicMock(spec=requests.Session)+ session.get.return_value = _response(json_body={"data": []})++ _run(+ DAILY_ENDPOINT,+ session,+ station_ids="10637",+ should_use_incremental_field=True,+ db_incremental_field_last_value=datetime(2026, 7, 15, tzinfo=UTC),+ )++ params = _requested_params(session)+ # Re-fetches a 7 day trailing overlap so late corrections get picked up; merge dedupes.+ assert params == [{"station": "10637", "start": "2026-07-08", "end": "2026-07-21"}]++ @freeze_time("2026-07-21")+ def test_resume_state_skips_completed_stations_and_resumes_the_current_one(self):+ session = mock.MagicMock(spec=requests.Session)+ session.get.return_value = _response(json_body={"data": []})+ manager = _manager(resume_state=MeteostatResumeConfig(station_index=1, next_start="2026-07-19"))++ _run(DAILY_ENDPOINT, session, manager, station_ids="10637,71508", start_date="2026-01-01")++ params = _requested_params(session)+ # Station 0 already finished in a prior attempt; only station 1 is queried, resuming+ # from its saved cursor rather than restarting at start_date.+ assert params == [{"station": "71508", "start": "2026-07-19", "end": "2026-07-21"}]++ def test_raises_without_configured_stations(self):+ with pytest.raises(ValueError, match=NO_STATIONS_ERROR):+ _run(DAILY_ENDPOINT, mock.MagicMock(spec=requests.Session), station_ids=" , ")++ @freeze_time("2026-07-21")+ def test_station_count_is_capped_at_runtime(self):+ session = mock.MagicMock(spec=requests.Session)+ session.get.return_value = _response(json_body={"data": []})+ station_ids = ",".join(str(i) for i in range(MAX_STATIONS + 5))++ _run(DAILY_ENDPOINT, session, station_ids=station_ids, start_date="2026-07-20")++ assert session.get.call_count == MAX_STATIONS++ @parameterized.expand(+ [+ ("metric_omits_units_param", "metric", False),+ ("imperial_includes_units_param", "imperial", True),+ ("scientific_includes_units_param", "scientific", True),+ ]+ )+ @freeze_time("2026-07-21")+ def test_units_param_only_sent_for_non_default_unit_system(self, _name, units, expect_param):+ session = mock.MagicMock(spec=requests.Session)+ session.get.return_value = _response(json_body={"data": []})++ _run(DAILY_ENDPOINT, session, station_ids="10637", units=units, start_date="2026-07-20")++ params = _requested_params(session)+ assert ("units" in params[0]) is expect_param+ if expect_param:+ assert params[0]["units"] == units++ @freeze_time("2026-07-21")+ def test_non_ok_status_raises(self):+ session = mock.MagicMock(spec=requests.Session)+ session.get.return_value = _response(status=500)++ with pytest.raises(requests.HTTPError):+ _run(DAILY_ENDPOINT, session, station_ids="10637", start_date="2026-07-20")++ @freeze_time("2026-07-21")+ def test_start_date_before_floor_is_clamped(self):+ # A too-old start_date is re-checked (not just rejected at credential validation) so a+ # previously stored configuration can't schedule a runaway backfill either.+ session = mock.MagicMock(spec=requests.Session)+ session.get.return_value = _response(json_body={"data": []})++ _run(DAILY_ENDPOINT, session, station_ids="10637", start_date="0001-01-01")++ params = _requested_params(session)+ assert params[0]["start"] == MINIMUM_START_DATE.isoformat()+++class TestMeteostatSourceResponse:+ @parameterized.expand([(name,) for name in (HOURLY_ENDPOINT, DAILY_ENDPOINT, MONTHLY_ENDPOINT)])+ def test_primary_keys_and_partitioning_per_endpoint(self, endpoint_name):+ endpoint = METEOSTAT_ENDPOINTS[endpoint_name]+ response = meteostat_source(+ api_key="key-123",+ station_ids="10637",+ units="metric",+ start_date=None,+ endpoint_name=endpoint_name,+ logger=mock.MagicMock(),+ resumable_source_manager=mock.MagicMock(spec=ResumableSourceManager),+ )++ assert response.name == endpoint_name+ assert response.primary_keys == endpoint.primary_keys+ assert "station_id" in (response.primary_keys or [])+ assert response.partition_keys == [endpoint.date_field]+ assert response.sort_mode == "asc"+++class TestValidateStation:+ @parameterized.expand(+ [+ ("ok", 200, True),+ ("unauthorized", 401, False),+ ("forbidden", 403, False),+ ("not_found", 404, False),+ ("server_error", 500, False),+ ]+ )+ def test_status_mapping(self, _name, status, expected_valid):+ with mock.patch(f"{MODULE}.make_tracked_session") as make_session:+ make_session.return_value.get.return_value = _response(status=status)+ is_valid, message = validate_station("key-123", "10637")++ assert is_valid is expected_valid+ if expected_valid:+ assert message is None+ else:+ assert message is not None++ def test_network_error_is_not_valid(self):+ with mock.patch(f"{MODULE}.make_tracked_session") as make_session:+ make_session.return_value.get.side_effect = requests.ConnectionError("boom")+ is_valid, message = validate_station("key-123", "10637")++ assert is_valid is False+ assert message is not None and "Could not reach" in messagediff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/meteostat/tests/test_meteostat_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/meteostat/tests/test_meteostat_source.pynew file mode 100644index 000000000000..a80b28f3bf59--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/meteostat/tests/test_meteostat_source.py@@ -0,0 +1,179 @@+from types import SimpleNamespace+from typing import cast++from unittest import mock++from parameterized import parameterized++from posthog.schema import ReleaseStatus, SourceFieldInputConfig, SourceFieldSelectConfig++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.meteostat import (+ MeteostatSourceConfig,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.meteostat.meteostat import (+ NO_STATIONS_ERROR,+ MeteostatResumeConfig,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.meteostat.settings import (+ DAILY_ENDPOINT,+ ENDPOINTS,+ MAX_STATIONS,+ METEOSTAT_ENDPOINTS,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.meteostat.source import MeteostatSource+from products.warehouse_sources.backend.types import ExternalDataSourceType++MODULE = "products.warehouse_sources.backend.temporal.data_imports.sources.meteostat.source"+++class TestMeteostatSource:+ def setup_method(self):+ self.source = MeteostatSource()+ self.team_id = 123+ self.config = MeteostatSourceConfig(api_key="key-123", station_ids="10637")++ def test_source_type(self):+ assert self.source.source_type == ExternalDataSourceType.METEOSTAT++ def test_get_source_config_is_released(self):+ config = self.source.get_source_config++ assert not config.unreleasedSource+ assert config.releaseStatus == ReleaseStatus.ALPHA+ assert config.name.value == "Meteostat"+ assert config.iconPath == "/static/services/meteostat.png"++ fields_by_name = {field.name: field for field in config.fields}+ assert set(fields_by_name) == {"api_key", "station_ids", "units", "start_date"}++ api_key = cast(SourceFieldInputConfig, fields_by_name["api_key"])+ assert api_key.required is True+ assert api_key.secret is True++ station_ids = cast(SourceFieldInputConfig, fields_by_name["station_ids"])+ assert station_ids.required is True++ units = fields_by_name["units"]+ assert isinstance(units, SourceFieldSelectConfig)+ assert units.defaultValue == "metric"++ assert cast(SourceFieldInputConfig, fields_by_name["start_date"]).required is False++ def test_get_schemas_returns_every_endpoint_with_matching_incremental_field(self):+ schemas = self.source.get_schemas(self.config, self.team_id)++ assert {schema.name for schema in schemas} == set(ENDPOINTS)+ for schema in schemas:+ assert schema.supports_incremental is True+ expected_field = METEOSTAT_ENDPOINTS[schema.name].date_field+ assert {field["field"] for field in schema.incremental_fields} == {expected_field}++ def test_get_schemas_filtered_by_names(self):+ schemas = self.source.get_schemas(self.config, self.team_id, names=[DAILY_ENDPOINT])+ assert [schema.name for schema in schemas] == [DAILY_ENDPOINT]++ def test_non_retryable_errors_cover_missing_stations_and_auth(self):+ errors = self.source.get_non_retryable_errors()+ assert NO_STATIONS_ERROR in errors+ assert any("401" in key for key in errors)+ assert any("403" in key for key in errors)++ def test_validate_credentials_rejects_no_stations(self):+ config = MeteostatSourceConfig(api_key="key-123", station_ids="")+ is_valid, message = self.source.validate_credentials(config, self.team_id)+ assert is_valid is False+ assert message is not None and "station" in message.lower()++ def test_validate_credentials_rejects_too_many_stations(self):+ station_ids = ",".join(str(i) for i in range(MAX_STATIONS + 1))+ config = MeteostatSourceConfig(api_key="key-123", station_ids=station_ids)+ is_valid, message = self.source.validate_credentials(config, self.team_id)+ assert is_valid is False+ assert message is not None and str(MAX_STATIONS) in message++ def test_validate_credentials_rejects_start_date_before_floor(self):+ config = MeteostatSourceConfig(api_key="key-123", station_ids="10637", start_date="0001-01-01")+ is_valid, message = self.source.validate_credentials(config, self.team_id)+ assert is_valid is False+ assert message is not None and "start date" in message.lower()++ @mock.patch(f"{MODULE}.validate_station")+ def test_validate_credentials_probes_the_first_configured_station(self, mock_validate):+ mock_validate.return_value = (True, None)+ config = MeteostatSourceConfig(api_key="key-123", station_ids="10637, 71508")++ is_valid, message = self.source.validate_credentials(config, self.team_id)++ assert is_valid is True+ assert message is None+ mock_validate.assert_called_once_with("key-123", "10637")++ def test_get_resumable_source_manager_is_bound_to_resume_config(self):+ manager = self.source.get_resumable_source_manager(mock.MagicMock())++ assert isinstance(manager, ResumableSourceManager)+ assert manager._data_class is MeteostatResumeConfig++ @mock.patch(f"{MODULE}.meteostat_source")+ def test_source_for_pipeline_plumbs_inputs(self, mock_source):+ mock_source.return_value = SimpleNamespace(name=DAILY_ENDPOINT)+ manager = mock.MagicMock(spec=ResumableSourceManager)+ logger = mock.MagicMock()+ inputs = SimpleNamespace(+ schema_name=DAILY_ENDPOINT,+ team_id=self.team_id,+ job_id="job-1",+ logger=logger,+ should_use_incremental_field=True,+ incremental_field="date",+ db_incremental_field_last_value="2026-07-01",+ )++ response = self.source.source_for_pipeline(self.config, manager, cast(SourceInputs, inputs))++ mock_source.assert_called_once_with(+ api_key="key-123",+ station_ids="10637",+ units="metric",+ start_date=None,+ endpoint_name=DAILY_ENDPOINT,+ logger=logger,+ resumable_source_manager=manager,+ should_use_incremental_field=True,+ db_incremental_field_last_value="2026-07-01",+ )+ assert response is mock_source.return_value++ @mock.patch(f"{MODULE}.meteostat_source")+ def test_source_for_pipeline_drops_last_value_on_full_refresh(self, mock_source):+ mock_source.return_value = SimpleNamespace(name=DAILY_ENDPOINT)+ inputs = SimpleNamespace(+ schema_name=DAILY_ENDPOINT,+ team_id=self.team_id,+ job_id="job-2",+ logger=mock.MagicMock(),+ should_use_incremental_field=False,+ incremental_field=None,+ db_incremental_field_last_value="2026-07-01",+ )++ self.source.source_for_pipeline(+ self.config, mock.MagicMock(spec=ResumableSourceManager), cast(SourceInputs, inputs)+ )++ assert mock_source.call_args.kwargs["db_incremental_field_last_value"] is None++ def test_documented_tables_render_without_credentials(self):+ tables = self.source.get_documented_tables()+ assert {table["name"] for table in tables} == set(ENDPOINTS)+ for table in tables:+ assert table["description"]++ @parameterized.expand([(name,) for name in ENDPOINTS])+ def test_canonical_descriptions_cover_every_endpoint(self, endpoint_name):+ descriptions = self.source.get_canonical_descriptions()+ assert endpoint_name in descriptions+ assert descriptions[endpoint_name]["description"]+ assert "station_id" in descriptions[endpoint_name]["columns"]