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): implement openweather import source (#65640)

Tom Owersdbc622d6b609
diff --git a/posthog/temporal/data_imports/sources/SOURCES.md b/posthog/temporal/data_imports/sources/SOURCES.md
index f0a96fdb11bb..5cb13be4e921 100644
--- a/posthog/temporal/data_imports/sources/SOURCES.md
+++ b/posthog/temporal/data_imports/sources/SOURCES.md
@@ -155,6 +155,7 @@ the row lists both.
| notion | HTTP | requests | ✅ |
| omnisend | HTTP | requests | ✅ |
| orb | HTTP | requests + `rest_source.RESTClient` | ✅ |
+| openweather | HTTP | requests | ✅ |
| ortto | HTTP | requests | ✅ |
| oura | HTTP | requests | ✅ |
| outbrain | HTTP | requests | ✅ |
@@ -530,7 +531,6 @@ doesn't conflict with concurrent PRs.
- open_exchange_rates
- openaq
- openfda
-- openweather
- opinion_stage
- opsgenie
- opuswatch
diff --git a/posthog/temporal/data_imports/sources/common/http/url_utils.py b/posthog/temporal/data_imports/sources/common/http/url_utils.py
index ad456435d125..01c0ea23cb29 100644
--- a/posthog/temporal/data_imports/sources/common/http/url_utils.py
+++ b/posthog/temporal/data_imports/sources/common/http/url_utils.py
@@ -23,6 +23,7 @@ _REDACT_PARAM_NAMES: Final[frozenset[str]] = frozenset(
# Generic auth/secret param names
"api_key",
"apikey",
+ "appid", # OpenWeather passes the API key as the `appid` query param
"access_token",
"auth",
"auth_token",
diff --git a/posthog/temporal/data_imports/sources/generated_configs.py b/posthog/temporal/data_imports/sources/generated_configs.py
index b4f6065e9187..fa032a6e352a 100644
--- a/posthog/temporal/data_imports/sources/generated_configs.py
+++ b/posthog/temporal/data_imports/sources/generated_configs.py
@@ -2141,7 +2141,8 @@ class OpenFDASourceConfig(config.Config):
@config.config
class OpenWeatherSourceConfig(config.Config):
- pass
+ api_key: str
+ locations: str
@config.config
diff --git a/posthog/temporal/data_imports/sources/openweather/canonical_descriptions.py b/posthog/temporal/data_imports/sources/openweather/canonical_descriptions.py
new file mode 100644
index 000000000000..c9853a59ddec
--- /dev/null
+++ b/posthog/temporal/data_imports/sources/openweather/canonical_descriptions.py
@@ -0,0 +1,72 @@
+from posthog.temporal.data_imports.sources.common.canonical_descriptions import CanonicalDescriptions
+
+# Injected by the connector on every row (not part of the raw API response).
+_INJECTED_COLUMNS = {
+ "lat": "Requested latitude of the location (as configured, not the station OpenWeather snapped to).",
+ "lon": "Requested longitude of the location (as configured, not the station OpenWeather snapped to).",
+ "location_label": "Optional user-supplied label for the configured location.",
+ "dt_iso": "ISO 8601 UTC timestamp derived from `dt`; used as the partition key.",
+ "dt": "Time of the data, Unix UTC timestamp.",
+}
+
+CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
+ "current_weather": {
+ "description": "Current weather snapshot for a configured location, from the OpenWeather Current Weather Data API.",
+ "docs_url": "https://openweathermap.org/current",
+ "columns": {
+ **_INJECTED_COLUMNS,
+ "coord": "Location coordinates echoed by the API ({lon, lat}).",
+ "weather": "List of weather condition objects (id, main, description, icon).",
+ "main": "Main measurements: temp, feels_like, temp_min, temp_max, pressure, humidity.",
+ "visibility": "Visibility in metres (max 10000).",
+ "wind": "Wind data: speed, deg, gust.",
+ "clouds": "Cloudiness, as a percentage.",
+ "rain": "Rain volume for the last 1h/3h, where available.",
+ "snow": "Snow volume for the last 1h/3h, where available.",
+ "sys": "System data: country, sunrise, sunset.",
+ "timezone": "Shift in seconds from UTC for the location.",
+ "id": "OpenWeather city ID.",
+ "name": "City name resolved by OpenWeather.",
+ "cod": "Internal API response code.",
+ },
+ },
+ "forecast": {
+ "description": "5 day / 3 hour weather forecast for a configured location; one row per 3-hour slot.",
+ "docs_url": "https://openweathermap.org/forecast5",
+ "columns": {
+ **_INJECTED_COLUMNS,
+ "dt": "Time of the forecasted data slot, Unix UTC timestamp.",
+ "main": "Forecasted measurements: temp, feels_like, pressure, humidity, temp_kf.",
+ "weather": "List of weather condition objects for the slot.",
+ "clouds": "Cloudiness, as a percentage.",
+ "wind": "Wind data: speed, deg, gust.",
+ "visibility": "Average visibility in metres.",
+ "pop": "Probability of precipitation, from 0 to 1.",
+ "rain": "Rain volume for the 3-hour slot, where available.",
+ "snow": "Snow volume for the 3-hour slot, where available.",
+ "sys": "Part of day (`pod`): `n` for night, `d` for day.",
+ "dt_txt": "Forecast slot time as a human-readable UTC string.",
+ "city": "City metadata for the forecast (id, name, coord, country, timezone, sunrise, sunset).",
+ },
+ },
+ "air_pollution": {
+ "description": "Current air quality (AQI and pollutant concentrations) for a configured location.",
+ "docs_url": "https://openweathermap.org/api/air-pollution",
+ "columns": {
+ **_INJECTED_COLUMNS,
+ "dt": "Time of the air-quality data, Unix UTC timestamp.",
+ "main": "Air Quality Index: `aqi` from 1 (Good) to 5 (Very Poor).",
+ "components": "Pollutant concentrations in μg/m³: co, no, no2, o3, so2, pm2_5, pm10, nh3.",
+ },
+ },
+ "air_pollution_forecast": {
+ "description": "Hourly air-quality forecast for a configured location.",
+ "docs_url": "https://openweathermap.org/api/air-pollution",
+ "columns": {
+ **_INJECTED_COLUMNS,
+ "dt": "Time of the forecasted air-quality slot, Unix UTC timestamp.",
+ "main": "Forecasted Air Quality Index: `aqi` from 1 (Good) to 5 (Very Poor).",
+ "components": "Forecasted pollutant concentrations in μg/m³: co, no, no2, o3, so2, pm2_5, pm10, nh3.",
+ },
+ },
+}
diff --git a/posthog/temporal/data_imports/sources/openweather/openweather.py b/posthog/temporal/data_imports/sources/openweather/openweather.py
new file mode 100644
index 000000000000..94e81ee1bc74
--- /dev/null
+++ b/posthog/temporal/data_imports/sources/openweather/openweather.py
@@ -0,0 +1,228 @@
+import re
+import dataclasses
+from collections.abc import Iterator
+from datetime import UTC, datetime
+from typing import Any
+from urllib.parse import urlencode
+
+import requests
+from structlog.types import FilteringBoundLogger
+from tenacity import retry, retry_if_exception_type, stop_after_attempt, wait_exponential_jitter
+
+from posthog.temporal.data_imports.pipelines.pipeline.typings import SourceResponse
+from posthog.temporal.data_imports.sources.common.http import make_tracked_session
+from posthog.temporal.data_imports.sources.openweather.settings import OPENWEATHER_ENDPOINTS, OpenWeatherEndpointConfig
+
+OPENWEATHER_BASE_URL = "https://api.openweathermap.org"
+
+REQUEST_TIMEOUT_SECONDS = 30
+MAX_RETRY_ATTEMPTS = 5
+
+# Each location costs one request per enabled endpoint on every sync, so cap the config to bound
+# worker time and outbound fan-out — a malformed/abusive config can't tie up the pipeline.
+MAX_LOCATIONS = 100
+
+
+class OpenWeatherRetryableError(Exception):
+ pass
+
+
[email protected](frozen=True)
+class Location:
+ lat: float
+ lon: float
+ label: str | None = None
+
+
+def parse_locations(raw: str | None) -> list[Location]:
+ """Parse the user's free-text ``locations`` field into coordinate pairs.
+
+ Each non-empty line is ``lat,lon`` 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 (lat,lon) is required.")
+
+ locations: list[Location] = []
+ 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 'lat,lon' or 'lat,lon,label'.")
+
+ try:
+ lat = float(parts[0].strip())
+ lon = 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 <= lat <= 90.0) or not (-180.0 <= lon <= 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
+ locations.append(Location(lat=lat, lon=lon, label=label or None))
+
+ 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 (lat,lon) is required.")
+
+ return locations
+
+
+def _build_url(path: str, params: dict[str, Any]) -> str:
+ return f"{OPENWEATHER_BASE_URL}{path}?{urlencode(params)}"
+
+
+# The API key is passed as the `appid` query param, so it ends up in `response.url`. `raise_for_status()`
+# embeds that URL in its message, which would otherwise leak the key into the sync's stored error and logs.
+_APPID_RE = re.compile(r"(appid=)[^&\s]+", re.IGNORECASE)
+
+
+def _redact_appid(text: str) -> str:
+ return _APPID_RE.sub(r"\1REDACTED", text)
+
+
+@retry(
+ retry=retry_if_exception_type((OpenWeatherRetryableError, requests.ReadTimeout, requests.ConnectionError)),
+ stop=stop_after_attempt(MAX_RETRY_ATTEMPTS),
+ wait=wait_exponential_jitter(initial=1, max=30),
+ reraise=True,
+)
+def _fetch(session: requests.Session, url: str, logger: FilteringBoundLogger) -> dict[str, Any]:
+ response = session.get(url, timeout=REQUEST_TIMEOUT_SECONDS)
+
+ # 429 (free tier is 60 req/min) and transient 5xx are retryable; back off and try again.
+ if response.status_code == 429 or response.status_code >= 500:
+ raise OpenWeatherRetryableError(f"OpenWeather API error (retryable): status={response.status_code}")
+
+ if not response.ok:
+ logger.error(f"OpenWeather API error: status={response.status_code}, body={response.text}")
+ try:
+ response.raise_for_status()
+ except requests.HTTPError as exc:
+ # Re-raise with the `appid` redacted so the key never reaches stored errors / logs, keeping the
+ # `... for url: https://api.openweathermap.org` prefix intact for `get_non_retryable_errors()`.
+ raise requests.HTTPError(_redact_appid(str(exc)), response=exc.response) from None
+
+ return response.json()
+
+
+def _dt_to_iso(dt: Any) -> str | None:
+ """Convert an OpenWeather Unix timestamp into an ISO 8601 UTC string for partitioning."""
+ if not isinstance(dt, int | float):
+ return None
+ return datetime.fromtimestamp(int(dt), tz=UTC).isoformat()
+
+
+def _normalize_rows(
+ config: OpenWeatherEndpointConfig, response: dict[str, Any], location: Location
+) -> list[dict[str, Any]]:
+ """Turn an API response into flat rows, stamping each with the requested coordinates.
+
+ We inject the *requested* lat/lon (not the response's echoed ``coord``, which can snap to the
+ nearest station and drift between syncs) so the ``[lat, lon, dt]`` primary key stays stable.
+ """
+ if config.data_key is None:
+ items: list[dict[str, Any]] = [dict(response)]
+ else:
+ items = [dict(item) for item in response.get(config.data_key, []) if isinstance(item, dict)]
+ # The forecast response carries city metadata alongside the per-slot list; attach it so
+ # rows are self-describing.
+ city = response.get("city")
+ if city is not None:
+ for item in items:
+ item.setdefault("city", city)
+
+ for item in items:
+ item["lat"] = location.lat
+ item["lon"] = location.lon
+ item["location_label"] = location.label
+ # `dt` is part of the primary key, so a row without it is degenerate — read it directly
+ # so a missing field fails loudly rather than flowing a null partition key into the merge.
+ item["dt_iso"] = _dt_to_iso(item["dt"])
+
+ return items
+
+
+def validate_credentials(api_key: str, locations_raw: str | None) -> tuple[bool, str | None]:
+ """Probe the current-weather endpoint with the first configured location.
+
+ OpenWeather returns 401 for a missing/invalid key (and, since paid products live behind the
+ same auth, for a key not yet subscribed to a product). A freshly created key can take up to a
+ couple of hours to activate, so the message points users at that.
+ """
+ try:
+ locations = parse_locations(locations_raw)
+ except ValueError as exc:
+ return False, str(exc)
+
+ location = locations[0]
+ url = _build_url(
+ OPENWEATHER_ENDPOINTS["current_weather"].path,
+ {"lat": location.lat, "lon": location.lon, "appid": api_key},
+ )
+
+ try:
+ response = make_tracked_session().get(url, timeout=REQUEST_TIMEOUT_SECONDS)
+ except Exception:
+ return False, "Could not reach the OpenWeather API. Please try again."
+
+ if response.status_code == 200:
+ return True, None
+ if response.status_code == 401:
+ return False, (
+ "Invalid OpenWeather API key. Note that a newly created key can take up to a couple of hours to activate."
+ )
+
+ return False, f"OpenWeather API returned an unexpected status code: {response.status_code}"
+
+
+def get_rows(
+ api_key: str,
+ endpoint: str,
+ locations: list[Location],
+ logger: FilteringBoundLogger,
+) -> Iterator[list[dict[str, Any]]]:
+ config = OPENWEATHER_ENDPOINTS[endpoint]
+ # One session reused across every location so urllib3 keeps the connection alive.
+ session = make_tracked_session()
+
+ for location in locations:
+ url = _build_url(config.path, {"lat": location.lat, "lon": location.lon, "appid": api_key})
+ response = _fetch(session, url, logger)
+ rows = _normalize_rows(config, response, location)
+ if rows:
+ yield rows
+
+
+def openweather_source(
+ api_key: str,
+ endpoint: str,
+ locations_raw: str | None,
+ logger: FilteringBoundLogger,
+) -> SourceResponse:
+ config = OPENWEATHER_ENDPOINTS[endpoint]
+ locations = parse_locations(locations_raw)
+
+ return SourceResponse(
+ name=endpoint,
+ items=lambda: get_rows(api_key=api_key, endpoint=endpoint, locations=locations, logger=logger),
+ primary_keys=config.primary_keys,
+ partition_count=1,
+ partition_size=1,
+ partition_mode="datetime",
+ partition_format="week",
+ partition_keys=[config.partition_key],
+ # Forecast rows arrive in ascending `dt` order; single-snapshot endpoints have one row.
+ sort_mode="asc",
+ )
diff --git a/posthog/temporal/data_imports/sources/openweather/settings.py b/posthog/temporal/data_imports/sources/openweather/settings.py
new file mode 100644
index 000000000000..d2a03e8b8f18
--- /dev/null
+++ b/posthog/temporal/data_imports/sources/openweather/settings.py
@@ -0,0 +1,70 @@
+from dataclasses import dataclass, field
+from typing import Optional
+
+from products.data_warehouse.backend.types import IncrementalField, IncrementalFieldType
+
+# Every OpenWeather row carries a `dt` (Unix UTC timestamp) describing the point in time the
+# observation/forecast slot refers to. It never changes for a given row, so it doubles as the
+# append cursor and a stable partition key. We expose it both as the raw integer (`dt`) and as a
+# derived ISO 8601 string (`dt_iso`) so the datetime partitioner has a parseable column.
+_DT_INCREMENTAL_FIELDS: list[IncrementalField] = [
+ {
+ "label": "dt",
+ "type": IncrementalFieldType.Integer,
+ "field": "dt",
+ "field_type": IncrementalFieldType.Integer,
+ },
+]
+
+
+@dataclass
+class OpenWeatherEndpointConfig:
+ name: str
+ path: str
+ # Where rows live in the JSON response. ``None`` means the response *is* the row
+ # (current weather), ``"list"`` means rows are the elements of the ``list`` array
+ # (forecast, air pollution).
+ data_key: Optional[str]
+ incremental_fields: list[IncrementalField] = field(default_factory=lambda: list(_DT_INCREMENTAL_FIELDS))
+ # ``dt`` alone is not unique table-wide because rows aggregate across every configured
+ # location, so the requested coordinates are part of the key.
+ primary_keys: list[str] = field(default_factory=lambda: ["lat", "lon", "dt"])
+ # Stable datetime column used for partitioning (derived from ``dt``).
+ partition_key: str = "dt_iso"
+ should_sync_default: bool = True
+ description: Optional[str] = None
+
+
+OPENWEATHER_ENDPOINTS: dict[str, OpenWeatherEndpointConfig] = {
+ "current_weather": OpenWeatherEndpointConfig(
+ name="current_weather",
+ path="/data/2.5/weather",
+ data_key=None,
+ description="Current weather snapshot for each configured location. One row per location per sync; "
+ "use append sync to accumulate a time series.",
+ ),
+ "forecast": OpenWeatherEndpointConfig(
+ name="forecast",
+ path="/data/2.5/forecast",
+ data_key="list",
+ description="5 day / 3 hour weather forecast. One row per 3-hour slot per location.",
+ ),
+ "air_pollution": OpenWeatherEndpointConfig(
+ name="air_pollution",
+ path="/data/2.5/air_pollution",
+ data_key="list",
+ description="Current air quality (AQI and pollutant concentrations) for each configured location.",
+ ),
+ "air_pollution_forecast": OpenWeatherEndpointConfig(
+ name="air_pollution_forecast",
+ path="/data/2.5/air_pollution/forecast",
+ data_key="list",
+ description="Hourly air-quality forecast for each configured location.",
+ ),
+}
+
+ENDPOINTS = tuple(OPENWEATHER_ENDPOINTS.keys())
+
+INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {
+ name: config.incremental_fields for name, config in OPENWEATHER_ENDPOINTS.items()
+}
diff --git a/posthog/temporal/data_imports/sources/openweather/source.py b/posthog/temporal/data_imports/sources/openweather/source.py
index 8eed692eefc3..a98b8ba43c8b 100644
--- a/posthog/temporal/data_imports/sources/openweather/source.py
+++ b/posthog/temporal/data_imports/sources/openweather/source.py
@@ -1,14 +1,29 @@
-from typing import cast
+from typing import Optional, cast
from posthog.schema import (
DataWarehouseSourceCategory,
ExternalDataSourceType as SchemaExternalDataSourceType,
+ ReleaseStatus,
SourceConfig,
+ SourceFieldInputConfig,
+ SourceFieldInputConfigType,
)
+from posthog.temporal.data_imports.pipelines.pipeline.typings import SourceInputs, SourceResponse
from posthog.temporal.data_imports.sources.common.base import FieldType, SimpleSource
+from posthog.temporal.data_imports.sources.common.canonical_descriptions import CanonicalDescriptions
from posthog.temporal.data_imports.sources.common.registry import SourceRegistry
+from posthog.temporal.data_imports.sources.common.schema import SourceSchema
from posthog.temporal.data_imports.sources.generated_configs import OpenWeatherSourceConfig
+from posthog.temporal.data_imports.sources.openweather.openweather import (
+ openweather_source,
+ validate_credentials as validate_openweather_credentials,
+)
+from posthog.temporal.data_imports.sources.openweather.settings import (
+ ENDPOINTS,
+ INCREMENTAL_FIELDS,
+ OPENWEATHER_ENDPOINTS,
+)
from products.data_warehouse.backend.types import ExternalDataSourceType
@@ -25,7 +40,96 @@ class OpenWeatherSource(SimpleSource[OpenWeatherSourceConfig]):
name=SchemaExternalDataSourceType.OPEN_WEATHER,
category=DataWarehouseSourceCategory.ANALYTICS,
label="OpenWeather",
- iconPath="/static/services/openweather.png",
- fields=cast(list[FieldType], []),
+ releaseStatus=ReleaseStatus.ALPHA,
unreleasedSource=True,
+ caption="""Enter your OpenWeather API key and the locations you want to track to pull weather data into the PostHog Data warehouse.
+
+Create an API key in your [OpenWeather account](https://home.openweathermap.org/api_keys). A newly created key can take a couple of hours to activate.
+
+OpenWeather has no list endpoint — every request is for a single coordinate — so enter one location per line as `lat,lon` (an optional label is allowed: `lat,lon,label`). For example:
+
+```
+51.5074,-0.1278,London
+40.7128,-74.0060,New York
+```
+
+Each sync polls every location once. To accumulate a history of point-in-time snapshots, pick the **append** sync method on the table.
+""",
+ iconPath="/static/services/openweather.png",
+ docsUrl="https://openweathermap.org/api",
+ fields=cast(
+ list[FieldType],
+ [
+ SourceFieldInputConfig(
+ name="api_key",
+ label="API key",
+ type=SourceFieldInputConfigType.PASSWORD,
+ required=True,
+ placeholder="Your OpenWeather API key",
+ secret=True,
+ ),
+ SourceFieldInputConfig(
+ name="locations",
+ label="Locations",
+ type=SourceFieldInputConfigType.TEXTAREA,
+ required=True,
+ placeholder="51.5074,-0.1278,London\n40.7128,-74.0060,New York",
+ secret=False,
+ ),
+ ],
+ ),
+ )
+
+ def get_canonical_descriptions(self) -> CanonicalDescriptions:
+ from posthog.temporal.data_imports.sources.openweather.canonical_descriptions import ( # noqa: PLC0415
+ CANONICAL_DESCRIPTIONS,
+ )
+
+ return CANONICAL_DESCRIPTIONS
+
+ def get_non_retryable_errors(self) -> dict[str, str | None]:
+ return {
+ # A missing/invalid key (or a key not subscribed to the requested product) surfaces as a
+ # 401 when `_fetch` calls `raise_for_status()`. Retrying can never satisfy it.
+ "401 Client Error: Unauthorized for url: https://api.openweathermap.org": "Your OpenWeather API key is invalid, not yet activated, or not subscribed to this product. Check the key in your OpenWeather account, then reconnect.",
+ }
+
+ def get_schemas(
+ self,
+ config: OpenWeatherSourceConfig,
+ team_id: int,
+ with_counts: bool = False,
+ names: list[str] | None = None,
+ force_refresh: bool = False,
+ ) -> list[SourceSchema]:
+ schemas = [
+ SourceSchema(
+ name=endpoint,
+ # No server-side timestamp filter exists, so this is not true incremental sync.
+ # Append is supported: each sync re-polls the (cheap) snapshot and merge dedupes on
+ # `[lat, lon, dt]`, accumulating a time series across runs.
+ supports_incremental=False,
+ supports_append=True,
+ incremental_fields=INCREMENTAL_FIELDS.get(endpoint, []),
+ should_sync_default=OPENWEATHER_ENDPOINTS[endpoint].should_sync_default,
+ description=OPENWEATHER_ENDPOINTS[endpoint].description,
+ )
+ for endpoint 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: OpenWeatherSourceConfig, team_id: int, schema_name: Optional[str] = None
+ ) -> tuple[bool, str | None]:
+ return validate_openweather_credentials(config.api_key, config.locations)
+
+ def source_for_pipeline(self, config: OpenWeatherSourceConfig, inputs: SourceInputs) -> SourceResponse:
+ return openweather_source(
+ api_key=config.api_key,
+ endpoint=inputs.schema_name,
+ locations_raw=config.locations,
+ logger=inputs.logger,
)
diff --git a/posthog/temporal/data_imports/sources/openweather/tests/test_openweather.py b/posthog/temporal/data_imports/sources/openweather/tests/test_openweather.py
new file mode 100644
index 000000000000..f66aa612d6bd
--- /dev/null
+++ b/posthog/temporal/data_imports/sources/openweather/tests/test_openweather.py
@@ -0,0 +1,301 @@
+import json
+from typing import Any, Optional
+
+import pytest
+from unittest import mock
+
+import requests
+import structlog
+
+from posthog.temporal.data_imports.sources.openweather.openweather import (
+ MAX_LOCATIONS,
+ OPENWEATHER_BASE_URL,
+ Location,
+ OpenWeatherRetryableError,
+ _build_url,
+ _dt_to_iso,
+ _fetch,
+ _normalize_rows,
+ _redact_appid,
+ get_rows,
+ openweather_source,
+ parse_locations,
+ validate_credentials,
+)
+from posthog.temporal.data_imports.sources.openweather.settings import OPENWEATHER_ENDPOINTS
+
+MODULE = "posthog.temporal.data_imports.sources.openweather.openweather"
+
+
+def _response(status: int = 200, body: Optional[dict[str, Any]] = None) -> mock.MagicMock:
+ resp = mock.MagicMock()
+ resp.status_code = status
+ resp.ok = 200 <= status < 300
+ resp.json.return_value = body or {}
+ resp.text = json.dumps(body or {})
+ if not resp.ok:
+ resp.raise_for_status.side_effect = requests.HTTPError(
+ f"{status} Client Error for url: {OPENWEATHER_BASE_URL}", response=requests.Response()
+ )
+ return resp
+
+
+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,London\n40.7,-74.0", [Location(51.5, -0.12, "London"), Location(40.7, -74.0, None)]),
+ ("51.5,-0.12\n\n \n40.7,-74.0", [Location(51.5, -0.12, None), Location(40.7, -74.0, None)]),
+ # Labels containing commas are preserved.
+ ("40.7,-74.0,New York, NY", [Location(40.7, -74.0, "New York, NY")]),
+ ],
+ )
+ def test_valid(self, raw, expected):
+ assert parse_locations(raw) == expected
+
+ @pytest.mark.parametrize(
+ "raw",
+ [
+ None,
+ "",
+ " \n ",
+ "51.5", # missing longitude
+ "abc,def", # non-numeric
+ "91,0", # latitude out of range
+ "0,181", # longitude out of range
+ ],
+ )
+ def test_invalid_raises(self, raw):
+ with pytest.raises(ValueError):
+ parse_locations(raw)
+
+ def test_rejects_too_many_locations(self):
+ raw = "\n".join(f"{i % 90},0" for i in range(MAX_LOCATIONS + 1))
+ with pytest.raises(ValueError, match="Too many locations"):
+ parse_locations(raw)
+
+ def test_allows_max_locations(self):
+ raw = "\n".join(f"{i % 90},0" for i in range(MAX_LOCATIONS))
+ assert len(parse_locations(raw)) == MAX_LOCATIONS
+
+
+class TestDtToIso:
+ @pytest.mark.parametrize(
+ "dt, expected",
+ [
+ (1719158400, "2024-06-23T16:00:00+00:00"),
+ (1719158400.0, "2024-06-23T16:00:00+00:00"),
+ (None, None),
+ ("not-a-number", None),
+ ],
+ )
+ def test_dt_to_iso(self, dt, expected):
+ assert _dt_to_iso(dt) == expected
+
+
+class TestRedactAppid:
+ @pytest.mark.parametrize(
+ "text, expected",
+ [
+ ("https://x/?lat=1&appid=secret", "https://x/?lat=1&appid=REDACTED"),
+ ("https://x/?appid=secret&lat=1", "https://x/?appid=REDACTED&lat=1"),
+ ("APPID=secret", "APPID=REDACTED"), # case-insensitive
+ ("no key here", "no key here"),
+ ],
+ )
+ def test_redact(self, text, expected):
+ assert _redact_appid(text) == expected
+
+
+class TestBuildUrl:
+ def test_includes_coords_and_appid(self):
+ url = _build_url("/data/2.5/weather", {"lat": 51.5, "lon": -0.12, "appid": "secret-key"})
+
+ assert url.startswith(f"{OPENWEATHER_BASE_URL}/data/2.5/weather?")
+ assert "lat=51.5" in url
+ assert "lon=-0.12" in url
+ assert "appid=secret-key" in url
+
+
+class TestNormalizeRows:
+ def test_current_weather_injects_requested_coords(self):
+ # The API echoes coord snapped to the nearest station; we keep the *requested* coords on the row.
+ response = {"coord": {"lat": 51.51, "lon": -0.13}, "main": {"temp": 280}, "dt": 1719158400, "name": "London"}
+ rows = _normalize_rows(OPENWEATHER_ENDPOINTS["current_weather"], response, Location(51.5, -0.12, "London"))
+
+ assert len(rows) == 1
+ row = rows[0]
+ assert row["lat"] == 51.5
+ assert row["lon"] == -0.12
+ assert row["location_label"] == "London"
+ assert row["dt_iso"] == "2024-06-23T16:00:00+00:00"
+ assert row["main"] == {"temp": 280}
+
+ def test_forecast_yields_one_row_per_slot_with_city(self):
+ response = {
+ "list": [{"dt": 1719158400, "main": {"temp": 280}}, {"dt": 1719169200, "main": {"temp": 281}}],
+ "city": {"id": 1, "name": "London"},
+ }
+ rows = _normalize_rows(OPENWEATHER_ENDPOINTS["forecast"], response, Location(51.5, -0.12, None))
+
+ assert [row["dt"] for row in rows] == [1719158400, 1719169200]
+ assert all(row["city"] == {"id": 1, "name": "London"} for row in rows)
+ assert all(row["lat"] == 51.5 and row["lon"] == -0.12 for row in rows)
+
+ def test_air_pollution_list_rows(self):
+ response = {"coord": {"lat": 51.5, "lon": -0.12}, "list": [{"main": {"aqi": 2}, "dt": 1719158400}]}
+ rows = _normalize_rows(OPENWEATHER_ENDPOINTS["air_pollution"], response, Location(51.5, -0.12, None))
+
+ assert len(rows) == 1
+ assert rows[0]["main"] == {"aqi": 2}
+ assert rows[0]["dt_iso"] == "2024-06-23T16:00:00+00:00"
+
+ def test_row_without_dt_raises(self):
+ # `dt` is part of the primary key; a row missing it must fail loudly, not yield a null key.
+ response = {"main": {"temp": 280}}
+ with pytest.raises(KeyError):
+ _normalize_rows(OPENWEATHER_ENDPOINTS["current_weather"], response, Location(51.5, -0.12, None))
+
+
+# The undecorated `_fetch` (tenacity exposes the original via `__wrapped__`) so the status
+# classification can be asserted without waiting through retry backoff.
+_fetch_once = _fetch.__wrapped__ # type: ignore[attr-defined]
+
+
+class TestFetch:
+ def test_ok_returns_body(self):
+ session = mock.MagicMock()
+ session.get.return_value = _response(200, {"dt": 1})
+
+ assert _fetch_once(session, "https://example.com", structlog.get_logger()) == {"dt": 1}
+
+ @pytest.mark.parametrize("status", [429, 500, 503])
+ def test_retryable_statuses_raise_retryable(self, status):
+ session = mock.MagicMock()
+ session.get.return_value = _response(status)
+
+ with pytest.raises(OpenWeatherRetryableError):
+ _fetch_once(session, "https://example.com", structlog.get_logger())
+
+ def test_client_error_raises_for_status(self):
+ session = mock.MagicMock()
+ session.get.return_value = _response(404)
+
+ with pytest.raises(requests.HTTPError):
+ _fetch_once(session, "https://example.com", structlog.get_logger())
+
+ def test_error_message_redacts_appid(self):
+ # The API key is passed as `appid`, so the raise_for_status URL must not leak it into the error.
+ resp = mock.MagicMock()
+ resp.status_code = 401
+ resp.ok = False
+ resp.text = '{"cod":401,"message":"Invalid API key."}'
+ resp.raise_for_status.side_effect = requests.HTTPError(
+ "401 Client Error: Unauthorized for url: "
+ "https://api.openweathermap.org/data/2.5/weather?lat=51.5&lon=-0.12&appid=SUPERSECRETKEY",
+ response=requests.Response(),
+ )
+ session = mock.MagicMock()
+ session.get.return_value = resp
+
+ with pytest.raises(requests.HTTPError) as exc_info:
+ _fetch_once(session, "https://example.com", structlog.get_logger())
+
+ message = str(exc_info.value)
+ assert "SUPERSECRETKEY" not in message
+ assert "appid=REDACTED" in message
+ # The host prefix is preserved so non-retryable-error matching still works.
+ assert "for url: https://api.openweathermap.org" in message
+
+
+class TestValidateCredentials:
+ @pytest.mark.parametrize(
+ "status, expected_valid",
+ [
+ (200, True),
+ (401, False),
+ (500, False),
+ ],
+ )
+ def test_status_mapping(self, status, expected_valid):
+ with mock.patch(f"{MODULE}.make_tracked_session") as mock_session:
+ mock_session.return_value.get.return_value = _response(status)
+
+ is_valid, _ = validate_credentials("test-key", "51.5,-0.12")
+
+ assert is_valid is expected_valid
+
+ def test_malformed_locations_is_invalid_without_request(self):
+ with mock.patch(f"{MODULE}.make_tracked_session") as mock_session:
+ is_valid, message = validate_credentials("test-key", "not-a-location")
+
+ assert is_valid is False
+ assert message is not None
+ mock_session.return_value.get.assert_not_called()
+
+ def test_network_error_is_invalid(self):
+ with mock.patch(f"{MODULE}.make_tracked_session") as mock_session:
+ mock_session.return_value.get.side_effect = Exception("boom")
+
+ is_valid, message = validate_credentials("test-key", "51.5,-0.12")
+
+ assert is_valid is False
+ assert message is not None
+
+ def test_probes_current_weather_with_first_location(self):
+ with mock.patch(f"{MODULE}.make_tracked_session") as mock_session:
+ mock_session.return_value.get.return_value = _response(200)
+
+ validate_credentials("test-key", "51.5,-0.12,London\n40.7,-74.0")
+
+ called_url = mock_session.return_value.get.call_args[0][0]
+
+ assert called_url.startswith(f"{OPENWEATHER_BASE_URL}/data/2.5/weather?")
+ assert "lat=51.5" in called_url
+
+
+class TestGetRows:
+ def test_yields_one_batch_per_location_and_targets_each(self):
+ locations = [Location(51.5, -0.12, "London"), Location(40.7, -74.0, "New York")]
+ with mock.patch(f"{MODULE}.make_tracked_session") as mock_session:
+ mock_session.return_value.get.side_effect = [
+ _response(200, {"dt": 1, "main": {"temp": 280}}),
+ _response(200, {"dt": 2, "main": {"temp": 290}}),
+ ]
+
+ batches = list(get_rows("test-key", "current_weather", locations, structlog.get_logger()))
+
+ called_urls = [call.args[0] for call in mock_session.return_value.get.call_args_list]
+
+ assert len(batches) == 2
+ assert batches[0][0]["lat"] == 51.5
+ assert batches[1][0]["lat"] == 40.7
+ assert "lat=51.5" in called_urls[0]
+ assert "lat=40.7" in called_urls[1]
+
+ def test_skips_empty_responses(self):
+ with mock.patch(f"{MODULE}.make_tracked_session") as mock_session:
+ mock_session.return_value.get.return_value = _response(200, {"list": []})
+
+ batches = list(get_rows("test-key", "forecast", [Location(51.5, -0.12, None)], structlog.get_logger()))
+
+ assert batches == []
+
+
+class TestOpenWeatherSource:
+ @pytest.mark.parametrize("endpoint", list(OPENWEATHER_ENDPOINTS))
+ def test_source_response_shape(self, endpoint):
+ response = openweather_source("test-key", endpoint, "51.5,-0.12,London", structlog.get_logger())
+
+ assert response.name == endpoint
+ assert response.primary_keys == ["lat", "lon", "dt"]
+ assert response.partition_mode == "datetime"
+ assert response.partition_keys == ["dt_iso"]
+ assert response.sort_mode == "asc"
+
+ def test_invalid_locations_raise(self):
+ with pytest.raises(ValueError):
+ openweather_source("test-key", "current_weather", "garbage", structlog.get_logger())
diff --git a/posthog/temporal/data_imports/sources/openweather/tests/test_openweather_source.py b/posthog/temporal/data_imports/sources/openweather/tests/test_openweather_source.py
new file mode 100644
index 000000000000..bfea0cd6b0dc
--- /dev/null
+++ b/posthog/temporal/data_imports/sources/openweather/tests/test_openweather_source.py
@@ -0,0 +1,130 @@
+import pytest
+from unittest import mock
+
+import structlog
+
+from posthog.schema import ReleaseStatus, SourceFieldInputConfig, SourceFieldInputConfigType
+
+from posthog.temporal.data_imports.pipelines.pipeline.typings import SourceInputs
+from posthog.temporal.data_imports.sources.generated_configs import OpenWeatherSourceConfig
+from posthog.temporal.data_imports.sources.openweather.settings import ENDPOINTS
+from posthog.temporal.data_imports.sources.openweather.source import OpenWeatherSource
+
+from products.data_warehouse.backend.types import ExternalDataSourceType
+
+
+def _make_inputs(schema_name: str = "current_weather") -> SourceInputs:
+ return SourceInputs(
+ schema_name=schema_name,
+ schema_id="schema-id",
+ source_id="source-id",
+ team_id=123,
+ should_use_incremental_field=False,
+ db_incremental_field_last_value=None,
+ db_incremental_field_earliest_value=None,
+ incremental_field=None,
+ incremental_field_type=None,
+ job_id="job-id",
+ logger=structlog.get_logger(),
+ reset_pipeline=False,
+ )
+
+
+class TestOpenWeatherSource:
+ def setup_method(self):
+ self.source = OpenWeatherSource()
+ self.team_id = 123
+ self.config = OpenWeatherSourceConfig(api_key="test-key", locations="51.5,-0.12,London")
+
+ def test_source_type(self):
+ assert self.source.source_type == ExternalDataSourceType.OPENWEATHER
+
+ def test_get_source_config(self):
+ config = self.source.get_source_config
+
+ assert config.name.value == "OpenWeather"
+ assert config.label == "OpenWeather"
+ assert config.releaseStatus == ReleaseStatus.ALPHA
+ assert config.unreleasedSource is True
+ assert config.iconPath == "/static/services/openweather.png"
+
+ def test_get_source_config_fields(self):
+ fields = self.source.get_source_config.fields
+
+ for field in fields:
+ assert isinstance(field, SourceFieldInputConfig)
+ by_name = {field.name: field for field in fields if isinstance(field, SourceFieldInputConfig)}
+ assert set(by_name) == {"api_key", "locations"}
+
+ api_key_field = by_name["api_key"]
+ assert api_key_field.type == SourceFieldInputConfigType.PASSWORD
+ assert api_key_field.required is True
+ assert api_key_field.secret is True
+
+ locations_field = by_name["locations"]
+ assert locations_field.type == SourceFieldInputConfigType.TEXTAREA
+ assert locations_field.required is True
+ assert locations_field.secret is False
+
+ def test_get_schemas_lists_all_endpoints(self):
+ schemas = self.source.get_schemas(self.config, self.team_id)
+
+ assert {schema.name for schema in schemas} == set(ENDPOINTS)
+
+ @pytest.mark.parametrize("endpoint", list(ENDPOINTS))
+ def test_get_schemas_supports_append_not_incremental(self, endpoint):
+ # No endpoint exposes a server-side timestamp filter, so none is truly incremental;
+ # all support append so users can accumulate snapshots over time.
+ schemas = {schema.name: schema for schema in self.source.get_schemas(self.config, self.team_id)}
+
+ assert schemas[endpoint].supports_incremental is False
+ assert schemas[endpoint].supports_append is True
+ assert [f["field"] for f in schemas[endpoint].incremental_fields] == ["dt"]
+
+ def test_get_schemas_filtered_by_names(self):
+ schemas = self.source.get_schemas(self.config, self.team_id, names=["forecast"])
+
+ assert [schema.name for schema in schemas] == ["forecast"]
+
+ def test_get_schemas_filtered_unknown_name_returns_empty(self):
+ assert self.source.get_schemas(self.config, self.team_id, names=["nonexistent"]) == []
+
+ def test_non_retryable_errors_includes_unauthorized(self):
+ errors = self.source.get_non_retryable_errors()
+
+ assert any("401 Client Error: Unauthorized" in key for key in errors)
+
+ def test_canonical_descriptions_cover_every_endpoint(self):
+ descriptions = self.source.get_canonical_descriptions()
+
+ assert set(descriptions) == set(ENDPOINTS)
+
+ @pytest.mark.parametrize(
+ "mock_return, expected_valid, expected_message",
+ [
+ ((True, None), True, None),
+ ((False, "Invalid OpenWeather API key"), False, "Invalid OpenWeather API key"),
+ ],
+ )
+ @mock.patch("posthog.temporal.data_imports.sources.openweather.source.validate_openweather_credentials")
+ def test_validate_credentials(self, mock_validate, mock_return, expected_valid, expected_message):
+ mock_validate.return_value = mock_return
+
+ is_valid, error_message = self.source.validate_credentials(self.config, self.team_id, "current_weather")
+
+ assert is_valid is expected_valid
+ assert error_message == expected_message
+ mock_validate.assert_called_once_with(self.config.api_key, self.config.locations)
+
+ @mock.patch("posthog.temporal.data_imports.sources.openweather.source.openweather_source")
+ def test_source_for_pipeline_plumbs_args(self, mock_openweather_source):
+ inputs = _make_inputs(schema_name="forecast")
+
+ self.source.source_for_pipeline(self.config, inputs)
+
+ mock_openweather_source.assert_called_once_with(
+ api_key="test-key",
+ endpoint="forecast",
+ locations_raw="51.5,-0.12,London",
+ logger=inputs.logger,
+ )