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(warehouse_sources): support OpenWeather API version 3.0 (#80095)

Tom Owers7279e30169f3
diff --git a/.agents/skills/warehouse-source-new-version/SKILL.md b/.agents/skills/warehouse-source-new-version/SKILL.md
index 1b91f880d540..8489d74fa4dd 100644
--- a/.agents/skills/warehouse-source-new-version/SKILL.md
+++ b/.agents/skills/warehouse-source-new-version/SKILL.md
@@ -92,6 +92,7 @@ Add it when any of these hold:
- When the vendor renames a collection between versions, keep the schema/table name set identical across versions and put the rename in a per-version path on the endpoint config — otherwise discovery diffs orphan the table on repin.
- When the new version has no equivalent for an old endpoint (a dropped collection, not a rename), keep that table only on the versions that serve it and let the table set differ by version — never map it to a guessed path just to keep the sets equal, since docs are the sole source of truth and an unverified path makes a new source surface a table that 404s at sync time.
- A source with no dispatch may currently read its version from a constant on a shared model (e.g. the OAuth `Integration` model) that also drives version-independent flows like OAuth token minting. Repoint only the sync request path onto the resolved pin; leave that constant, since bumping it changes those other flows' version with a blast radius beyond this source.
+- The opposite holds when the new version is a genuinely different vendor product rather than a renamed collection (the old and new labels serve different endpoints and tables): give the new version its own disjoint table set, don't force the old names onto it. That divergence is safe only because sources are never repinned — so a 2.5→3.0-style move is lossy, and its migration is documented-not-scripted, exactly like a rename that changes primary keys.
## Self-improvement
diff --git a/products/warehouse_sources/backend/migrations/0129_pin_openweather_v2_5.py b/products/warehouse_sources/backend/migrations/0129_pin_openweather_v2_5.py
new file mode 100644
index 000000000000..03486492b634
--- /dev/null
+++ b/products/warehouse_sources/backend/migrations/0129_pin_openweather_v2_5.py
@@ -0,0 +1,37 @@
+from django.db import migrations
+
+# OpenWeather now defaults to 3.0 (the One Call API). 3.0 serves a different product from the 2.5
+# general-purpose APIs — different request paths (`/data/3.0/onecall`) and a different table set
+# (current/hourly/daily instead of current_weather/forecast/air_pollution) — so moving a source
+# from 2.5 to 3.0 is a lossy transition, not an in-place `api_version` flip, and also needs a One
+# Call 3.0 subscription the stored key may not carry. That migration is therefore intentionally NOT
+# scripted — existing sources keep their 2.5 pin.
+#
+# This migration only backs out the NULL cohort from the default flip. A NULL `api_version` resolves
+# to `default_version`, which just moved 2.5 -> 3.0, so any OpenWeather source created without an
+# explicit pin (direct-ORM/seeder paths that bypass the API's create-time stamping) would silently
+# jump onto 3.0's divergent table set. Pinning those rows to 2.5 keeps them on the version they were
+# syncing.
+OPENWEATHER_SOURCE_TYPE = "OpenWeather"
+V2_5_VERSION = "2.5"
+
+
+def pin_openweather_v2_5(apps, schema_editor):
+ ExternalDataSource = apps.get_model("warehouse_sources", "ExternalDataSource")
+
+ # Source-level pins only. Filtering on NULL keeps this idempotent — a re-run matches nothing,
+ # and rows already carrying an explicit pin (2.5 or 3.0) are left as their owner set them.
+ # Schema-level overrides (`ExternalDataSchema.api_version`) are customer-managed and untouched.
+ ExternalDataSource.objects.filter(source_type=OPENWEATHER_SOURCE_TYPE, api_version__isnull=True).update(
+ api_version=V2_5_VERSION
+ )
+
+
+class Migration(migrations.Migration):
+ dependencies = [("warehouse_sources", "0128_repin_adobe_analytics_api_version_2_0")]
+
+ operations = [
+ # Reverse is a no-op: once pinned, a 2.5 row is indistinguishable from one natively stamped
+ # 2.5, so re-nulling would wrongly clear legitimate explicit pins too.
+ migrations.RunPython(pin_openweather_v2_5, migrations.RunPython.noop, elidable=False),
+ ]
diff --git a/products/warehouse_sources/backend/migrations/max_migration.txt b/products/warehouse_sources/backend/migrations/max_migration.txt
index d0ac491c7d6b..75fc4698b7da 100644
--- a/products/warehouse_sources/backend/migrations/max_migration.txt
+++ b/products/warehouse_sources/backend/migrations/max_migration.txt
@@ -1 +1 @@
-0128_repin_adobe_analytics_api_version_2_0
+0129_pin_openweather_v2_5
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/openweather/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/openweather/canonical_descriptions.py
index 685a070cab8d..eaf79510d0bf 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/openweather/canonical_descriptions.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/openweather/canonical_descriptions.py
@@ -71,4 +71,77 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
"components": "Forecasted pollutant concentrations in μg/m³: co, no, no2, o3, so2, pm2_5, pm10, nh3.",
},
},
+ # One Call API 3.0 tables. Each row is one section of the shared `/data/3.0/onecall` response.
+ "current": {
+ "description": "Current weather snapshot for a configured location, from the OpenWeather One Call API 3.0.",
+ "docs_url": "https://openweathermap.org/api/one-call-3",
+ "columns": {
+ **_INJECTED_COLUMNS,
+ "temp": "Temperature (units depend on the `units` request parameter; standard is Kelvin).",
+ "feels_like": "Human-perceived temperature accounting for wind and humidity.",
+ "pressure": "Atmospheric pressure at sea level, hPa.",
+ "humidity": "Humidity, as a percentage.",
+ "dew_point": "Atmospheric temperature below which dew forms.",
+ "uvi": "UV index.",
+ "clouds": "Cloudiness, as a percentage.",
+ "visibility": "Average visibility in metres (max 10000).",
+ "wind_speed": "Wind speed.",
+ "wind_gust": "Wind gust, where available.",
+ "wind_deg": "Wind direction, degrees (meteorological).",
+ "rain": "Rain volume for the last 1h, where available (`1h`).",
+ "snow": "Snow volume for the last 1h, where available (`1h`).",
+ "sunrise": "Sunrise time, Unix UTC timestamp.",
+ "sunset": "Sunset time, Unix UTC timestamp.",
+ "weather": "List of weather condition objects (id, main, description, icon).",
+ },
+ },
+ "hourly": {
+ "description": "Hourly weather forecast (48 hours) for a configured location; one row per hour.",
+ "docs_url": "https://openweathermap.org/api/one-call-3",
+ "columns": {
+ **_INJECTED_COLUMNS,
+ "temp": "Forecasted temperature for the hour.",
+ "feels_like": "Human-perceived temperature for the hour.",
+ "pressure": "Atmospheric pressure at sea level, hPa.",
+ "humidity": "Humidity, as a percentage.",
+ "dew_point": "Atmospheric temperature below which dew forms.",
+ "uvi": "UV index.",
+ "clouds": "Cloudiness, as a percentage.",
+ "visibility": "Average visibility in metres.",
+ "wind_speed": "Wind speed.",
+ "wind_gust": "Wind gust, where available.",
+ "wind_deg": "Wind direction, degrees (meteorological).",
+ "pop": "Probability of precipitation, from 0 to 1.",
+ "rain": "Rain volume for the hour, where available (`1h`).",
+ "snow": "Snow volume for the hour, where available (`1h`).",
+ "weather": "List of weather condition objects for the hour.",
+ },
+ },
+ "daily": {
+ "description": "Daily weather forecast (8 days) for a configured location; one row per day.",
+ "docs_url": "https://openweathermap.org/api/one-call-3",
+ "columns": {
+ **_INJECTED_COLUMNS,
+ "summary": "Human-readable summary of the day's weather.",
+ "temp": "Daily temperatures: morn, day, eve, night, min, max.",
+ "feels_like": "Human-perceived temperatures: morn, day, eve, night.",
+ "pressure": "Atmospheric pressure at sea level, hPa.",
+ "humidity": "Humidity, as a percentage.",
+ "dew_point": "Atmospheric temperature below which dew forms.",
+ "wind_speed": "Wind speed.",
+ "wind_gust": "Wind gust, where available.",
+ "wind_deg": "Wind direction, degrees (meteorological).",
+ "clouds": "Cloudiness, as a percentage.",
+ "uvi": "Maximum UV index for the day.",
+ "pop": "Probability of precipitation, from 0 to 1.",
+ "rain": "Precipitation volume, where available, mm.",
+ "snow": "Snow volume, where available, mm.",
+ "sunrise": "Sunrise time, Unix UTC timestamp.",
+ "sunset": "Sunset time, Unix UTC timestamp.",
+ "moonrise": "Moonrise time, Unix UTC timestamp.",
+ "moonset": "Moonset time, Unix UTC timestamp.",
+ "moon_phase": "Moon phase, from 0 to 1.",
+ "weather": "List of weather condition objects for the day.",
+ },
+ },
}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/openweather/openweather.py b/products/warehouse_sources/backend/temporal/data_imports/sources/openweather/openweather.py
index ec5607c0a3b9..4184b88d8c88 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/openweather/openweather.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/openweather/openweather.py
@@ -12,8 +12,9 @@ from tenacity import retry, retry_if_exception_type, stop_after_attempt, wait_ex
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.typings import SourceResponse
from products.warehouse_sources.backend.temporal.data_imports.sources.openweather.settings import (
- OPENWEATHER_ENDPOINTS,
+ PROBE_ENDPOINT_BY_VERSION,
OpenWeatherEndpointConfig,
+ endpoints_for_version,
)
OPENWEATHER_BASE_URL = "https://api.openweathermap.org"
@@ -138,8 +139,16 @@ def _normalize_rows(
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
+ section = response.get(config.data_key)
+ # A section is either a list of rows (forecast slots, One Call hourly/daily) or a single
+ # object (One Call `current`); anything else (missing/null) yields no rows.
+ if isinstance(section, list):
+ items = [dict(item) for item in section if isinstance(item, dict)]
+ elif isinstance(section, dict):
+ items = [dict(section)]
+ else:
+ items = []
+ # The 2.5 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:
@@ -157,12 +166,14 @@ def _normalize_rows(
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.
+def validate_credentials(api_key: str, locations_raw: str | None, api_version: str) -> tuple[bool, str | None]:
+ """Probe the version's 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.
+ couple of hours to activate, so the message points users at that. Probing the version's own
+ endpoint means a key not subscribed to that product (e.g. One Call 3.0) fails here rather than
+ passing and 404ing at sync time.
"""
try:
locations = parse_locations(locations_raw)
@@ -170,8 +181,9 @@ def validate_credentials(api_key: str, locations_raw: str | None) -> tuple[bool,
return False, str(exc)
location = locations[0]
+ endpoints = endpoints_for_version(api_version)
url = _build_url(
- OPENWEATHER_ENDPOINTS["current_weather"].path,
+ endpoints[PROBE_ENDPOINT_BY_VERSION[api_version]].path,
{"lat": location.lat, "lon": location.lon, "appid": api_key},
)
@@ -195,8 +207,9 @@ def get_rows(
endpoint: str,
locations: list[Location],
logger: FilteringBoundLogger,
+ api_version: str,
) -> Iterator[list[dict[str, Any]]]:
- config = OPENWEATHER_ENDPOINTS[endpoint]
+ config = endpoints_for_version(api_version)[endpoint]
# One session reused across every location so urllib3 keeps the connection alive.
session = make_tracked_session()
@@ -213,13 +226,16 @@ def openweather_source(
endpoint: str,
locations_raw: str | None,
logger: FilteringBoundLogger,
+ api_version: str,
) -> SourceResponse:
- config = OPENWEATHER_ENDPOINTS[endpoint]
+ config = endpoints_for_version(api_version)[endpoint]
locations = parse_locations(locations_raw)
return SourceResponse(
name=endpoint,
- items=lambda: get_rows(api_key=api_key, endpoint=endpoint, locations=locations, logger=logger),
+ items=lambda: get_rows(
+ api_key=api_key, endpoint=endpoint, locations=locations, logger=logger, api_version=api_version
+ ),
primary_keys=config.primary_keys,
partition_count=1,
partition_size=1,
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/openweather/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/openweather/settings.py
index 7e1698ccbb20..b437fee2220c 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/openweather/settings.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/openweather/settings.py
@@ -35,6 +35,13 @@ class OpenWeatherEndpointConfig:
description: Optional[str] = None
+# Opaque vendor version labels (never parsed or ordered). The Current Weather, 5 Day / 3 Hour
+# Forecast and Air Pollution APIs are served under `2.5`; the One Call product's current stable
+# release is `3.0` (One Call 2.5 was closed in June 2024).
+API_VERSION_2_5 = "2.5"
+API_VERSION_3_0 = "3.0"
+
+# The 2.5 general-purpose APIs. Each endpoint is its own request per location per sync.
OPENWEATHER_ENDPOINTS: dict[str, OpenWeatherEndpointConfig] = {
"current_weather": OpenWeatherEndpointConfig(
name="current_weather",
@@ -63,8 +70,52 @@ OPENWEATHER_ENDPOINTS: dict[str, OpenWeatherEndpointConfig] = {
),
}
-ENDPOINTS = tuple(OPENWEATHER_ENDPOINTS.keys())
+# The One Call API 3.0 serves current weather plus forecasts from a single `/data/3.0/onecall`
+# response; each table extracts one section (`current` object, `hourly`/`daily` lists) and every
+# item carries its own `dt`, so the shared `[lat, lon, dt]` key and `dt_iso` partition still apply.
+_ONECALL_PATH = "/data/3.0/onecall"
+OPENWEATHER_ENDPOINTS_3_0: dict[str, OpenWeatherEndpointConfig] = {
+ "current": OpenWeatherEndpointConfig(
+ name="current",
+ path=_ONECALL_PATH,
+ data_key="current",
+ description="Current weather snapshot for each configured location, from the One Call API 3.0. "
+ "One row per location per sync; use append sync to accumulate a time series.",
+ ),
+ "hourly": OpenWeatherEndpointConfig(
+ name="hourly",
+ path=_ONECALL_PATH,
+ data_key="hourly",
+ description="Hourly weather forecast (48 hours) for each configured location. One row per hour.",
+ ),
+ "daily": OpenWeatherEndpointConfig(
+ name="daily",
+ path=_ONECALL_PATH,
+ data_key="daily",
+ description="Daily weather forecast (8 days) for each configured location. One row per day.",
+ ),
+}
+
+OPENWEATHER_ENDPOINTS_BY_VERSION: dict[str, dict[str, OpenWeatherEndpointConfig]] = {
+ API_VERSION_2_5: OPENWEATHER_ENDPOINTS,
+ API_VERSION_3_0: OPENWEATHER_ENDPOINTS_3_0,
+}
-INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {
- name: config.incremental_fields for name, config in OPENWEATHER_ENDPOINTS.items()
+# The endpoint each version's credential probe hits — chosen so it exercises the same product
+# (and subscription) the sync reads, not just any key-accepting endpoint.
+PROBE_ENDPOINT_BY_VERSION: dict[str, str] = {
+ API_VERSION_2_5: "current_weather",
+ API_VERSION_3_0: "current",
}
+
+
+def endpoints_for_version(api_version: str) -> dict[str, OpenWeatherEndpointConfig]:
+ """Endpoint set for a resolved vendor API version.
+
+ Raises on an unknown label rather than falling back to a default — sending the wrong version's
+ request paths would silently drift a pinned source off its version.
+ """
+ try:
+ return OPENWEATHER_ENDPOINTS_BY_VERSION[api_version]
+ except KeyError:
+ raise ValueError(f"Unsupported OpenWeather API version: {api_version!r}")
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/openweather/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/openweather/source.py
index 7474c76a4fb0..f475bee8dea4 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/openweather/source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/openweather/source.py
@@ -24,17 +24,17 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.openweathe
validate_credentials as validate_openweather_credentials,
)
from products.warehouse_sources.backend.temporal.data_imports.sources.openweather.settings import (
- ENDPOINTS,
- INCREMENTAL_FIELDS,
- OPENWEATHER_ENDPOINTS,
+ API_VERSION_2_5,
+ API_VERSION_3_0,
+ endpoints_for_version,
)
from products.warehouse_sources.backend.types import ExternalDataSourceType
@SourceRegistry.register
class OpenWeatherSource(SimpleSource[OpenWeatherSourceConfig]):
- supported_versions = ("2.5",)
- default_version = "2.5"
+ supported_versions = (API_VERSION_2_5, API_VERSION_3_0)
+ default_version = API_VERSION_3_0
api_docs_url = "https://openweathermap.org/api"
@property
@@ -109,6 +109,7 @@ Each sync polls every location once. To accumulate a history of point-in-time sn
force_refresh: bool = False,
api_version: str | None = None,
) -> list[SourceSchema]:
+ endpoints = endpoints_for_version(self.resolve_api_version(api_version))
schemas = [
SourceSchema(
name=endpoint,
@@ -117,11 +118,11 @@ Each sync polls every location once. To accumulate a history of point-in-time sn
# `[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,
+ incremental_fields=config.incremental_fields,
+ should_sync_default=config.should_sync_default,
+ description=config.description,
)
- for endpoint in ENDPOINTS
+ for endpoint, config in endpoints.items()
]
if names is not None:
names_set = set(names)
@@ -135,7 +136,7 @@ Each sync polls every location once. To accumulate a history of point-in-time sn
schema_name: Optional[str] = None,
api_version: str | None = None,
) -> tuple[bool, str | None]:
- return validate_openweather_credentials(config.api_key, config.locations)
+ return validate_openweather_credentials(config.api_key, config.locations, self.resolve_api_version(api_version))
def source_for_pipeline(self, config: OpenWeatherSourceConfig, inputs: SourceInputs) -> SourceResponse:
return openweather_source(
@@ -143,4 +144,5 @@ Each sync polls every location once. To accumulate a history of point-in-time sn
endpoint=inputs.schema_name,
locations_raw=config.locations,
logger=inputs.logger,
+ api_version=self.resolve_api_version(inputs.api_version),
)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/openweather/tests/test_openweather.py b/products/warehouse_sources/backend/temporal/data_imports/sources/openweather/tests/test_openweather.py
index 691a79fb82da..171cb82e5e57 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/openweather/tests/test_openweather.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/openweather/tests/test_openweather.py
@@ -22,7 +22,18 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.openweathe
parse_locations,
validate_credentials,
)
-from products.warehouse_sources.backend.temporal.data_imports.sources.openweather.settings import OPENWEATHER_ENDPOINTS
+from products.warehouse_sources.backend.temporal.data_imports.sources.openweather.settings import (
+ API_VERSION_2_5,
+ API_VERSION_3_0,
+ OPENWEATHER_ENDPOINTS,
+ endpoints_for_version,
+)
+
+# (version, endpoint) pairs across every supported version, so the request-path dispatch is
+# exercised for each.
+_ALL_VERSIONED_ENDPOINTS = [
+ (version, endpoint) for version in (API_VERSION_2_5, API_VERSION_3_0) for endpoint in endpoints_for_version(version)
+]
MODULE = "products.warehouse_sources.backend.temporal.data_imports.sources.openweather.openweather"
@@ -153,6 +164,25 @@ class TestNormalizeRows:
assert rows[0]["main"] == {"aqi": 2}
assert rows[0]["dt_iso"] == "2024-06-23T16:00:00+00:00"
+ def test_onecall_current_object_yields_single_row(self):
+ # One Call 3.0 nests the current snapshot as an object (not a list); it must become one row.
+ endpoints = endpoints_for_version(API_VERSION_3_0)
+ response = {"lat": 51.51, "lon": -0.13, "current": {"dt": 1719158400, "temp": 280}}
+ rows = _normalize_rows(endpoints["current"], response, Location(51.5, -0.12, "London"))
+
+ assert len(rows) == 1
+ assert rows[0]["temp"] == 280
+ assert rows[0]["lat"] == 51.5 and rows[0]["lon"] == -0.12
+ assert rows[0]["dt_iso"] == "2024-06-23T16:00:00+00:00"
+
+ def test_onecall_daily_list_rows(self):
+ endpoints = endpoints_for_version(API_VERSION_3_0)
+ response = {"daily": [{"dt": 1719158400, "temp": {"day": 280}}, {"dt": 1719244800, "temp": {"day": 281}}]}
+ rows = _normalize_rows(endpoints["daily"], response, Location(51.5, -0.12, None))
+
+ assert [row["dt"] for row in rows] == [1719158400, 1719244800]
+ assert all(row["lat"] == 51.5 and row["lon"] == -0.12 for row in rows)
+
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}}
@@ -224,13 +254,13 @@ class TestValidateCredentials:
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")
+ is_valid, _ = validate_credentials("test-key", "51.5,-0.12", API_VERSION_2_5)
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")
+ is_valid, message = validate_credentials("test-key", "not-a-location", API_VERSION_2_5)
assert is_valid is False
assert message is not None
@@ -240,20 +270,28 @@ class TestValidateCredentials:
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")
+ is_valid, message = validate_credentials("test-key", "51.5,-0.12", API_VERSION_2_5)
assert is_valid is False
assert message is not None
- def test_probes_current_weather_with_first_location(self):
+ @pytest.mark.parametrize(
+ "api_version, expected_path",
+ [
+ (API_VERSION_2_5, "/data/2.5/weather"),
+ (API_VERSION_3_0, "/data/3.0/onecall"),
+ ],
+ )
+ def test_probes_version_endpoint_with_first_location(self, api_version, expected_path):
+ # The probe must hit the version's own product so an unsubscribed key fails here, not at sync.
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")
+ validate_credentials("test-key", "51.5,-0.12,London\n40.7,-74.0", api_version)
called_url = mock_session.return_value.get.call_args[0][0]
- assert called_url.startswith(f"{OPENWEATHER_BASE_URL}/data/2.5/weather?")
+ assert called_url.startswith(f"{OPENWEATHER_BASE_URL}{expected_path}?")
assert "lat=51.5" in called_url
@@ -266,7 +304,7 @@ class TestGetRows:
_response(200, {"dt": 2, "main": {"temp": 290}}),
]
- batches = list(get_rows("test-key", "current_weather", locations, structlog.get_logger()))
+ batches = list(get_rows("test-key", "current_weather", locations, structlog.get_logger(), API_VERSION_2_5))
called_urls = [call.args[0] for call in mock_session.return_value.get.call_args_list]
@@ -280,15 +318,30 @@ class TestGetRows:
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()))
+ batches = list(
+ get_rows("test-key", "forecast", [Location(51.5, -0.12, None)], structlog.get_logger(), API_VERSION_2_5)
+ )
assert batches == []
+ def test_onecall_requests_the_3_0_path(self):
+ # A 3.0-pinned source must hit `/data/3.0/onecall`, not the 2.5 paths.
+ with mock.patch(f"{MODULE}.make_tracked_session") as mock_session:
+ mock_session.return_value.get.return_value = _response(200, {"current": {"dt": 1, "temp": 280}})
+
+ list(
+ get_rows("test-key", "current", [Location(51.5, -0.12, None)], structlog.get_logger(), API_VERSION_3_0)
+ )
+
+ called_url = mock_session.return_value.get.call_args[0][0]
+
+ assert called_url.startswith(f"{OPENWEATHER_BASE_URL}/data/3.0/onecall?")
+
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())
+ @pytest.mark.parametrize("api_version, endpoint", _ALL_VERSIONED_ENDPOINTS)
+ def test_source_response_shape(self, api_version, endpoint):
+ response = openweather_source("test-key", endpoint, "51.5,-0.12,London", structlog.get_logger(), api_version)
assert response.name == endpoint
assert response.primary_keys == ["lat", "lon", "dt"]
@@ -298,4 +351,8 @@ class TestOpenWeatherSource:
def test_invalid_locations_raise(self):
with pytest.raises(ValueError):
- openweather_source("test-key", "current_weather", "garbage", structlog.get_logger())
+ openweather_source("test-key", "current_weather", "garbage", structlog.get_logger(), API_VERSION_2_5)
+
+ def test_unsupported_version_raises(self):
+ with pytest.raises(ValueError, match="Unsupported OpenWeather API version"):
+ openweather_source("test-key", "current_weather", "51.5,-0.12", structlog.get_logger(), "9.9")
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/openweather/tests/test_openweather_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/openweather/tests/test_openweather_source.py
index 0aca4091f23a..7b73e987ece2 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/openweather/tests/test_openweather_source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/openweather/tests/test_openweather_source.py
@@ -9,12 +9,20 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common.typ
from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.openweather import (
OpenWeatherSourceConfig,
)
-from products.warehouse_sources.backend.temporal.data_imports.sources.openweather.settings import ENDPOINTS
+from products.warehouse_sources.backend.temporal.data_imports.sources.openweather.settings import (
+ API_VERSION_2_5,
+ API_VERSION_3_0,
+ endpoints_for_version,
+)
from products.warehouse_sources.backend.temporal.data_imports.sources.openweather.source import OpenWeatherSource
from products.warehouse_sources.backend.types import ExternalDataSourceType
+_ALL_VERSIONED_ENDPOINTS = [
+ (version, endpoint) for version in (API_VERSION_2_5, API_VERSION_3_0) for endpoint in endpoints_for_version(version)
+]
+
-def _make_inputs(schema_name: str = "current_weather") -> SourceInputs:
+def _make_inputs(schema_name: str = "current_weather", api_version: str | None = None) -> SourceInputs:
return SourceInputs(
schema_name=schema_name,
schema_id="schema-id",
@@ -28,6 +36,7 @@ def _make_inputs(schema_name: str = "current_weather") -> SourceInputs:
job_id="job-id",
logger=structlog.get_logger(),
reset_pipeline=False,
+ api_version=api_version,
)
@@ -66,23 +75,36 @@ class TestOpenWeatherSource:
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)
+ def test_default_version_is_3_0(self):
+ # New sources are stamped with `default_version`; the 3.0 One Call product is now the default.
+ assert self.source.default_version == API_VERSION_3_0
+ assert set(self.source.supported_versions) == {API_VERSION_2_5, API_VERSION_3_0}
- assert {schema.name for schema in schemas} == set(ENDPOINTS)
+ @pytest.mark.parametrize(
+ "api_version, expected",
+ [
+ (None, {"current", "hourly", "daily"}), # None → default_version (3.0)
+ (API_VERSION_3_0, {"current", "hourly", "daily"}),
+ (API_VERSION_2_5, {"current_weather", "forecast", "air_pollution", "air_pollution_forecast"}),
+ ],
+ )
+ def test_get_schemas_lists_the_versions_endpoints(self, api_version, expected):
+ schemas = self.source.get_schemas(self.config, self.team_id, api_version=api_version)
- @pytest.mark.parametrize("endpoint", list(ENDPOINTS))
- def test_get_schemas_supports_append_not_incremental(self, endpoint):
+ assert {schema.name for schema in schemas} == expected
+
+ @pytest.mark.parametrize("api_version, endpoint", _ALL_VERSIONED_ENDPOINTS)
+ def test_get_schemas_supports_append_not_incremental(self, api_version, 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)}
+ schemas = {s.name: s for s in self.source.get_schemas(self.config, self.team_id, api_version=api_version)}
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"])
+ schemas = self.source.get_schemas(self.config, self.team_id, names=["forecast"], api_version=API_VERSION_2_5)
assert [schema.name for schema in schemas] == ["forecast"]
@@ -97,7 +119,8 @@ class TestOpenWeatherSource:
def test_canonical_descriptions_cover_every_endpoint(self):
descriptions = self.source.get_canonical_descriptions()
- assert set(descriptions) == set(ENDPOINTS)
+ every_endpoint = {endpoint for _, endpoint in _ALL_VERSIONED_ENDPOINTS}
+ assert every_endpoint <= set(descriptions)
@pytest.mark.parametrize(
"mock_return, expected_valid, expected_message",
@@ -116,19 +139,31 @@ class TestOpenWeatherSource:
assert is_valid is expected_valid
assert error_message == expected_message
- mock_validate.assert_called_once_with(self.config.api_key, self.config.locations)
+ # No pin at validation time (pre-creation) resolves to the default version.
+ mock_validate.assert_called_once_with(self.config.api_key, self.config.locations, API_VERSION_3_0)
+ @pytest.mark.parametrize(
+ "pin, schema_name, expected_version",
+ [
+ (None, "current", API_VERSION_3_0), # unpinned → default
+ (API_VERSION_3_0, "current", API_VERSION_3_0),
+ (API_VERSION_2_5, "forecast", API_VERSION_2_5), # a 2.5-pinned source keeps its version
+ ],
+ )
@mock.patch(
"products.warehouse_sources.backend.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")
+ def test_source_for_pipeline_plumbs_resolved_version(
+ self, mock_openweather_source, pin, schema_name, expected_version
+ ):
+ inputs = _make_inputs(schema_name=schema_name, api_version=pin)
self.source.source_for_pipeline(self.config, inputs)
mock_openweather_source.assert_called_once_with(
api_key="test-key",
- endpoint="forecast",
+ endpoint=schema_name,
locations_raw="51.5,-0.12,London",
logger=inputs.logger,
+ api_version=expected_version,
)