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 breezometer import source (#66723)

Tom Owers1979fceeb5c3
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
index 0fc2de2bce70..3dcadab75eb4 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
@@ -67,6 +67,7 @@ the row lists both.
| blogger | HTTP | requests | ✅ |
| braintree | HTTP (GraphQL) | requests | ✅ |
| braze | HTTP | requests | ✅ |
+| breezometer | HTTP | requests | ✅ |
| brevo | HTTP | requests | ✅ |
| brex | HTTP | requests | ✅ |
| bugsnag | HTTP | requests | ✅ |
@@ -327,7 +328,6 @@ doesn't conflict with concurrent PRs.
- box
- braintrust
- branch
-- breezometer
- breezy_hr
- bunny
- buzzsprout
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/breezometer/breezometer.py b/products/warehouse_sources/backend/temporal/data_imports/sources/breezometer/breezometer.py
new file mode 100644
index 000000000000..4cc345187643
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/breezometer/breezometer.py
@@ -0,0 +1,343 @@
+import re
+import dataclasses
+from collections.abc import Iterator
+from datetime import UTC, datetime, timedelta
+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 products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import SourceResponse
+from products.warehouse_sources.backend.temporal.data_imports.sources.breezometer.settings import (
+ BREEZOMETER_ENDPOINTS,
+ BreezometerEndpointConfig,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.http import make_tracked_session
+
+# BreezoMeter's standalone API (api.breezometer.com) was sunset after Google acquired BreezoMeter and
+# folded the product into Google Maps Platform. This connector targets the living successor APIs:
+# the Air Quality API and the Pollen API. Both are REST/JSON, authenticated with an API key passed as
+# the `key` query parameter. The per-endpoint base URLs live in `settings.py` (`config.base_url`).
+
+REQUEST_TIMEOUT_SECONDS = 30
+MAX_RETRY_ATTEMPTS = 5
+
+# Each location costs at least one request per enabled endpoint on every sync (more when a response
+# paginates), 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
+
+# Defensive cap on pages followed per location so a misbehaving cursor can't loop unbounded. The
+# documented windows are small (≤96 forecast hours, ≤30 history days, ≤5 pollen days), so a handful
+# of pages is plenty.
+MAX_PAGES_PER_LOCATION = 50
+
+# Forecast horizon (hours). The Air Quality forecast API caps the window at 96 hours.
+FORECAST_HOURS = 96
+# History lookback (hours). The Air Quality history API allows up to 720 hours (30 days); 24h keeps
+# each sync cheap while still building a rolling window when paired with append sync.
+HISTORY_HOURS = 24
+# Pollen forecast horizon (days). The Pollen API allows up to 5 days.
+POLLEN_DAYS = 5
+
+
+class BreezometerRetryableError(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(base_url: str, path: str, params: dict[str, Any]) -> str:
+ return f"{base_url}{path}?{urlencode(params)}"
+
+
+# The API key is passed as the `key` 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. Match only the `key=` query param, not any field that happens to contain "key".
+_KEY_RE = re.compile(r"([?&]key=)[^&\s]+", re.IGNORECASE)
+
+
+def _redact_key(text: str) -> str:
+ return _KEY_RE.sub(r"\1REDACTED", text)
+
+
+def _rfc3339(dt: datetime) -> str:
+ """Format a datetime as RFC 3339 with a `Z` suffix, which the Google APIs expect."""
+ return dt.astimezone(UTC).strftime("%Y-%m-%dT%H:%M:%SZ")
+
+
+def _build_request(
+ config: BreezometerEndpointConfig,
+ api_key: str,
+ location: Location,
+ page_token: str | None,
+) -> tuple[str, dict[str, Any] | None]:
+ """Build the ``(url, json_body)`` for a single page of a single location.
+
+ Air Quality endpoints are POST with a JSON body (``json_body`` is a dict); the Pollen endpoint is
+ GET with query params (``json_body`` is ``None``). The API key always rides the ``key`` query param.
+ """
+ if config.request_kind == "pollen":
+ params: dict[str, Any] = {
+ "key": api_key,
+ "location.latitude": location.lat,
+ "location.longitude": location.lon,
+ "days": POLLEN_DAYS,
+ }
+ if page_token:
+ params["pageToken"] = page_token
+ return _build_url(config.base_url, config.path, params), None
+
+ # Air Quality (POST). The key stays in the query string; the location and request shape go in the body.
+ body: dict[str, Any] = {
+ "location": {"latitude": location.lat, "longitude": location.lon},
+ "languageCode": "en",
+ }
+ if config.extra_computations:
+ body["extraComputations"] = config.extra_computations
+ if config.name == "air_quality_forecast":
+ now = datetime.now(UTC).replace(minute=0, second=0, microsecond=0)
+ body["period"] = {"startTime": _rfc3339(now), "endTime": _rfc3339(now + timedelta(hours=FORECAST_HOURS))}
+ elif config.name == "air_quality_history":
+ body["hours"] = HISTORY_HOURS
+ if page_token:
+ body["pageToken"] = page_token
+
+ return _build_url(config.base_url, config.path, {"key": api_key}), body
+
+
+@retry(
+ retry=retry_if_exception_type((BreezometerRetryableError, 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,
+ config: BreezometerEndpointConfig,
+ api_key: str,
+ location: Location,
+ page_token: str | None,
+ logger: FilteringBoundLogger,
+) -> dict[str, Any]:
+ url, body = _build_request(config, api_key, location, page_token)
+
+ if body is None:
+ response = session.get(url, timeout=REQUEST_TIMEOUT_SECONDS)
+ else:
+ response = session.post(url, json=body, timeout=REQUEST_TIMEOUT_SECONDS)
+
+ # 429 (rate limit) and transient 5xx are retryable; back off and try again.
+ if response.status_code == 429 or response.status_code >= 500:
+ raise BreezometerRetryableError(f"Breezometer API error (retryable): status={response.status_code}")
+
+ if not response.ok:
+ logger.error(f"Breezometer API error: status={response.status_code}, body={_redact_key(response.text)}")
+ try:
+ response.raise_for_status()
+ except requests.HTTPError as exc:
+ # Re-raise with the `key` redacted so the API key never reaches stored errors / logs, keeping
+ # the `... for url: https://airquality.googleapis.com` prefix intact for non-retryable matching.
+ raise requests.HTTPError(_redact_key(str(exc)), response=exc.response) from None
+
+ return response.json()
+
+
+def _date_obj_to_iso(value: Any) -> str | None:
+ """Convert a Pollen ``date`` object (``{year, month, day}``) into an ISO 8601 UTC string."""
+ if not isinstance(value, dict):
+ return None
+ try:
+ return datetime(int(value["year"]), int(value["month"]), int(value["day"]), tzinfo=UTC).isoformat()
+ except (KeyError, TypeError, ValueError):
+ return None
+
+
+def _datetime_str_to_iso(value: Any) -> str | None:
+ """Normalize a Google ``dateTime`` string (RFC 3339, e.g. ``2023-08-11T08:00:00Z``) to ISO 8601 UTC."""
+ if not isinstance(value, str) or not value:
+ return None
+ try:
+ parsed = datetime.fromisoformat(value.replace("Z", "+00:00"))
+ except ValueError:
+ return None
+ if parsed.tzinfo is None:
+ parsed = parsed.replace(tzinfo=UTC)
+ return parsed.astimezone(UTC).isoformat()
+
+
+def _extract_dt_iso(config: BreezometerEndpointConfig, item: dict[str, Any]) -> str | None:
+ # `dt_iso` derives from this field and is part of the primary key, so index directly: a missing
+ # field is a structural API change (e.g. a renamed `dateTime`/`date`) that should fail loudly with
+ # a `KeyError` rather than silently dropping every row. A present-but-malformed value still parses
+ # to `None` and is skipped per-row by the caller.
+ if config.timestamp_kind == "date_obj":
+ return _date_obj_to_iso(item[config.timestamp_field])
+ return _datetime_str_to_iso(item[config.timestamp_field])
+
+
+def _normalize_rows(
+ config: BreezometerEndpointConfig, 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 any echoed coordinate, which can snap to a nearby grid cell
+ and drift between syncs) so the ``[latitude, longitude, dt_iso]`` primary key stays stable. The raw
+ timestamp field (``dateTime`` or ``date``) is preserved; ``dt_iso`` is the derived, parseable copy
+ used for partitioning and as the append cursor.
+ """
+ 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)]
+
+ rows: list[dict[str, Any]] = []
+ for item in items:
+ item["latitude"] = location.lat
+ item["longitude"] = location.lon
+ item["location_label"] = location.label
+ dt_iso = _extract_dt_iso(config, item)
+ if dt_iso is None:
+ # `dt_iso` is part of the primary key and the partition key; a row whose timestamp is
+ # present but unparseable is degenerate, so skip it rather than flow a null key into the
+ # merge. (A *missing* timestamp field raises in `_extract_dt_iso` — see its note.)
+ continue
+ item["dt_iso"] = dt_iso
+ rows.append(item)
+
+ return rows
+
+
+def validate_credentials(api_key: str, locations_raw: str | None) -> tuple[bool, str | None]:
+ """Probe the current air-quality endpoint with the first configured location.
+
+ Google returns 400 (``API key not valid``) for a missing/invalid key and 403 (``PERMISSION_DENIED``)
+ when the Air Quality API is not enabled for the project the key belongs to.
+ """
+ try:
+ locations = parse_locations(locations_raw)
+ except ValueError as exc:
+ return False, str(exc)
+
+ location = locations[0]
+ config = BREEZOMETER_ENDPOINTS["air_quality_current"]
+ url = _build_url(config.base_url, config.path, {"key": api_key})
+ body = {"location": {"latitude": location.lat, "longitude": location.lon}}
+
+ try:
+ response = make_tracked_session().post(url, json=body, timeout=REQUEST_TIMEOUT_SECONDS)
+ except Exception:
+ return False, "Could not reach the Google Maps Platform Air Quality API. Please try again."
+
+ if response.status_code == 200:
+ return True, None
+ if response.status_code in (400, 403):
+ return False, (
+ "Invalid API key, or the Air Quality API is not enabled for your Google Cloud project. "
+ "Check the key and enable the Air Quality and Pollen APIs, then reconnect."
+ )
+
+ return False, f"The Air Quality 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 = BREEZOMETER_ENDPOINTS[endpoint]
+ # One session reused across every location and page so urllib3 keeps the connection alive.
+ session = make_tracked_session()
+
+ for location in locations:
+ page_token: str | None = None
+ for page in range(MAX_PAGES_PER_LOCATION):
+ response = _fetch(session, config, api_key, location, page_token, logger)
+ rows = _normalize_rows(config, response, location)
+ if rows:
+ yield rows
+
+ page_token = response.get("nextPageToken")
+ if not page_token:
+ break
+ if page == MAX_PAGES_PER_LOCATION - 1:
+ logger.warning(
+ f"Breezometer: hit the {MAX_PAGES_PER_LOCATION}-page cap for endpoint={endpoint} "
+ f"at location=({location.lat},{location.lon}); stopping pagination."
+ )
+
+
+def breezometer_source(
+ api_key: str,
+ endpoint: str,
+ locations_raw: str | None,
+ logger: FilteringBoundLogger,
+) -> SourceResponse:
+ config = BREEZOMETER_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/history rows arrive in ascending time order; single-snapshot endpoints have one row.
+ sort_mode="asc",
+ )
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/breezometer/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/breezometer/canonical_descriptions.py
new file mode 100644
index 000000000000..9b40a7bd3a42
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/breezometer/canonical_descriptions.py
@@ -0,0 +1,57 @@
+from products.warehouse_sources.backend.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 = {
+ "latitude": "Requested latitude of the location (as configured, not a snapped grid cell).",
+ "longitude": "Requested longitude of the location (as configured, not a snapped grid cell).",
+ "location_label": "Optional user-supplied label for the configured location.",
+ "dt_iso": "ISO 8601 UTC timestamp derived from the response timestamp; used as the partition key and append cursor.",
+}
+
+_AIR_QUALITY_COLUMNS = {
+ "dateTime": "Rounded timestamp the data refers to, RFC 3339 UTC.",
+ "regionCode": "ISO 3166-1 alpha-2 country/region code the location falls in.",
+ "indexes": "List of air-quality indexes (e.g. Universal AQI and the local index) with code, value, category, and dominant pollutant.",
+ "pollutants": "List of pollutant objects (code, display name, concentration, and additional info) where requested.",
+ "healthRecommendations": "Health advice per population group (general, elderly, athletes, etc.) where requested.",
+}
+
+CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
+ "air_quality_current": {
+ "description": "Current air-quality conditions for a configured location, from the Google Maps Platform Air Quality API (currentConditions).",
+ "docs_url": "https://developers.google.com/maps/documentation/air-quality/reference/rest/v1/currentConditions/lookup",
+ "columns": {
+ **_INJECTED_COLUMNS,
+ **_AIR_QUALITY_COLUMNS,
+ },
+ },
+ "air_quality_forecast": {
+ "description": "Hourly air-quality forecast (up to 96 hours ahead) for a configured location; one row per forecast hour.",
+ "docs_url": "https://developers.google.com/maps/documentation/air-quality/reference/rest/v1/forecast/lookup",
+ "columns": {
+ **_INJECTED_COLUMNS,
+ **_AIR_QUALITY_COLUMNS,
+ },
+ },
+ "air_quality_history": {
+ "description": "Historical hourly air quality (the last 24 hours) for a configured location; one row per hour.",
+ "docs_url": "https://developers.google.com/maps/documentation/air-quality/reference/rest/v1/history/lookup",
+ "columns": {
+ **_INJECTED_COLUMNS,
+ **_AIR_QUALITY_COLUMNS,
+ },
+ },
+ "pollen_forecast": {
+ "description": "Daily pollen forecast (up to 5 days ahead) for a configured location, from the Google Maps Platform Pollen API; one row per day.",
+ "docs_url": "https://developers.google.com/maps/documentation/pollen/reference/rest/v1/forecast/lookup",
+ "columns": {
+ **_INJECTED_COLUMNS,
+ "date": "Calendar date the forecast day refers to, as a `{year, month, day}` object.",
+ "regionCode": "ISO 3166-1 alpha-2 country/region code the location falls in.",
+ "pollenTypeInfo": "Per pollen type (grass, tree, weed) index, category, and health recommendations for the day.",
+ "plantInfo": "Per plant index, category, and plant description (in-season flag, cross-reactions) for the day.",
+ },
+ },
+}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/breezometer/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/breezometer/settings.py
new file mode 100644
index 000000000000..427e0358881b
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/breezometer/settings.py
@@ -0,0 +1,109 @@
+from dataclasses import dataclass, field
+from typing import Literal, Optional
+
+from products.warehouse_sources.backend.types import IncrementalField, IncrementalFieldType
+
+# Every row carries `dt_iso`, a derived ISO 8601 UTC timestamp describing the point in time the
+# observation/forecast slot refers to (parsed from the API's `dateTime` string or `date` object). It
+# never changes for a given row, so it doubles as the append cursor and a stable partition key.
+_DT_INCREMENTAL_FIELDS: list[IncrementalField] = [
+ {
+ "label": "dt_iso",
+ "type": IncrementalFieldType.DateTime,
+ "field": "dt_iso",
+ "field_type": IncrementalFieldType.DateTime,
+ },
+]
+
+
+@dataclass
+class BreezometerEndpointConfig:
+ name: str
+ # "air_quality" -> POST with a JSON body; "pollen" -> GET with query params.
+ request_kind: Literal["air_quality", "pollen"]
+ base_url: str
+ path: str
+ # Where rows live in the JSON response. ``None`` means the response *is* the row (current
+ # conditions), otherwise rows are the elements of the array under this key.
+ data_key: Optional[str]
+ # Raw field on each row carrying the timestamp, and how to parse it into `dt_iso`.
+ timestamp_field: str
+ timestamp_kind: Literal["datetime_str", "date_obj"]
+ # Extra computations requested from the Air Quality API to enrich the response (ignored for pollen).
+ extra_computations: list[str] = field(default_factory=list)
+ incremental_fields: list[IncrementalField] = field(default_factory=lambda: list(_DT_INCREMENTAL_FIELDS))
+ # `dt_iso` 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: ["latitude", "longitude", "dt_iso"])
+ # Stable datetime column used for partitioning (derived from the raw timestamp).
+ partition_key: str = "dt_iso"
+ should_sync_default: bool = True
+ description: Optional[str] = None
+
+
+# Common Air Quality extra computations. Kept to widely-supported values; the API enriches the
+# response with these where available. Based on the public Air Quality API docs — see the PR notes:
+# the exact accepted enum could not be curl-verified without a key.
+_AIR_QUALITY_EXTRA_COMPUTATIONS = [
+ "HEALTH_RECOMMENDATIONS",
+ "DOMINANT_POLLUTANT_CONCENTRATION",
+ "POLLUTANT_CONCENTRATION",
+ "LOCAL_AQI",
+ "POLLUTANT_ADDITIONAL_INFO",
+]
+
+
+BREEZOMETER_ENDPOINTS: dict[str, BreezometerEndpointConfig] = {
+ "air_quality_current": BreezometerEndpointConfig(
+ name="air_quality_current",
+ request_kind="air_quality",
+ base_url="https://airquality.googleapis.com",
+ path="/v1/currentConditions:lookup",
+ data_key=None,
+ timestamp_field="dateTime",
+ timestamp_kind="datetime_str",
+ extra_computations=_AIR_QUALITY_EXTRA_COMPUTATIONS,
+ description="Current air-quality conditions (AQI indexes and pollutant concentrations) for each "
+ "configured location. One row per location per sync; use append sync to accumulate a time series.",
+ ),
+ "air_quality_forecast": BreezometerEndpointConfig(
+ name="air_quality_forecast",
+ request_kind="air_quality",
+ base_url="https://airquality.googleapis.com",
+ path="/v1/forecast:lookup",
+ data_key="hourlyForecasts",
+ timestamp_field="dateTime",
+ timestamp_kind="datetime_str",
+ extra_computations=_AIR_QUALITY_EXTRA_COMPUTATIONS,
+ description="Hourly air-quality forecast (up to 96 hours ahead) for each configured location. "
+ "One row per forecast hour.",
+ ),
+ "air_quality_history": BreezometerEndpointConfig(
+ name="air_quality_history",
+ request_kind="air_quality",
+ base_url="https://airquality.googleapis.com",
+ path="/v1/history:lookup",
+ data_key="hoursInfo",
+ timestamp_field="dateTime",
+ timestamp_kind="datetime_str",
+ extra_computations=_AIR_QUALITY_EXTRA_COMPUTATIONS,
+ description="Historical hourly air quality (the last 24 hours) for each configured location. One row per hour.",
+ ),
+ "pollen_forecast": BreezometerEndpointConfig(
+ name="pollen_forecast",
+ request_kind="pollen",
+ base_url="https://pollen.googleapis.com",
+ path="/v1/forecast:lookup",
+ data_key="dailyInfo",
+ timestamp_field="date",
+ timestamp_kind="date_obj",
+ description="Daily pollen forecast (up to 5 days ahead) for each configured location, covering "
+ "pollen types and plant-level indexes. One row per day.",
+ ),
+}
+
+ENDPOINTS = tuple(BREEZOMETER_ENDPOINTS.keys())
+
+INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {
+ name: config.incremental_fields for name, config in BREEZOMETER_ENDPOINTS.items()
+}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/breezometer/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/breezometer/source.py
index b361d85bbe4a..114c0027a7a6 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/breezometer/source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/breezometer/source.py
@@ -1,19 +1,43 @@
-from typing import cast
+from typing import Optional, cast
from posthog.schema import (
DataWarehouseSourceCategory,
ExternalDataSourceType as SchemaExternalDataSourceType,
+ ReleaseStatus,
SourceConfig,
+ SourceFieldInputConfig,
+ SourceFieldInputConfigType,
)
+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import (
+ SourceInputs,
+ SourceResponse,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.breezometer.breezometer import (
+ breezometer_source,
+ validate_credentials as validate_breezometer_credentials,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.breezometer.settings import (
+ BREEZOMETER_ENDPOINTS,
+ ENDPOINTS,
+ INCREMENTAL_FIELDS,
+)
from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, SimpleSource
+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.schema import SourceSchema
from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs import BreezometerSourceConfig
from products.warehouse_sources.backend.types import ExternalDataSourceType
@SourceRegistry.register
class BreezometerSource(SimpleSource[BreezometerSourceConfig]):
+ # `get_schemas` iterates a static endpoint catalog with no I/O, so the table list is safe to render
+ # in public docs without credentials.
+ lists_tables_without_credentials = True
+
@property
def source_type(self) -> ExternalDataSourceType:
return ExternalDataSourceType.BREEZOMETER
@@ -23,8 +47,102 @@ class BreezometerSource(SimpleSource[BreezometerSourceConfig]):
return SourceConfig(
name=SchemaExternalDataSourceType.BREEZOMETER,
category=DataWarehouseSourceCategory.ANALYTICS,
- label="Breezometer",
- iconPath="/static/services/breezometer.png",
- fields=cast(list[FieldType], []),
+ label="BreezoMeter",
+ releaseStatus=ReleaseStatus.ALPHA,
unreleasedSource=True,
+ caption="""Enter your API key and the locations you want to track to pull air-quality and pollen data into the PostHog Data warehouse.
+
+BreezoMeter is now part of **Google Maps Platform** — this source uses the [Air Quality API](https://developers.google.com/maps/documentation/air-quality) and the [Pollen API](https://developers.google.com/maps/documentation/pollen). Create an API key in the [Google Cloud console](https://console.cloud.google.com/apis/credentials) and enable both APIs for your project.
+
+There is 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 per table. To accumulate a history of point-in-time snapshots, pick the **append** sync method on the table.
+""",
+ iconPath="/static/services/breezometer.png",
+ docsUrl="https://posthog.com/docs/cdp/sources/breezometer",
+ fields=cast(
+ list[FieldType],
+ [
+ SourceFieldInputConfig(
+ name="api_key",
+ label="API key",
+ type=SourceFieldInputConfigType.PASSWORD,
+ required=True,
+ placeholder="Your Google Maps Platform 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 products.warehouse_sources.backend.temporal.data_imports.sources.breezometer.canonical_descriptions import ( # noqa: PLC0415
+ CANONICAL_DESCRIPTIONS,
+ )
+
+ return CANONICAL_DESCRIPTIONS
+
+ def get_non_retryable_errors(self) -> dict[str, str | None]:
+ return {
+ # An invalid key surfaces as a 400 (`API key not valid`) and a project without the API
+ # enabled as a 403 (`PERMISSION_DENIED`), both via `raise_for_status()`. Retrying can never
+ # satisfy a credential/enablement problem. Match the stable status text and base host (the
+ # `key` query param is redacted before the message reaches here).
+ "400 Client Error: Bad Request for url: https://airquality.googleapis.com": "Your API key is invalid, or the Air Quality API is not enabled for your Google Cloud project. Check the key and enable the API, then reconnect.",
+ "403 Client Error: Forbidden for url: https://airquality.googleapis.com": "Your API key does not have access to the Air Quality API. Enable the API for your Google Cloud project and check any key restrictions, then reconnect.",
+ "400 Client Error: Bad Request for url: https://pollen.googleapis.com": "Your API key is invalid, or the Pollen API is not enabled for your Google Cloud project. Check the key and enable the API, then reconnect.",
+ "403 Client Error: Forbidden for url: https://pollen.googleapis.com": "Your API key does not have access to the Pollen API. Enable the API for your Google Cloud project and check any key restrictions, then reconnect.",
+ }
+
+ def get_schemas(
+ self,
+ config: BreezometerSourceConfig,
+ team_id: int,
+ with_counts: bool = False,
+ names: list[str] | None = None,
+ force_refresh: bool = False,
+ ) -> list[SourceSchema]:
+ schemas = [
+ SourceSchema(
+ name=endpoint,
+ # No endpoint exposes a server-side change cursor, so none is truly incremental.
+ # Append is supported: each sync re-polls the snapshot and merge dedupes on
+ # `[latitude, longitude, dt_iso]`, accumulating a time series across runs.
+ supports_incremental=False,
+ supports_append=True,
+ incremental_fields=INCREMENTAL_FIELDS.get(endpoint, []),
+ should_sync_default=BREEZOMETER_ENDPOINTS[endpoint].should_sync_default,
+ description=BREEZOMETER_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: BreezometerSourceConfig, team_id: int, schema_name: Optional[str] = None
+ ) -> tuple[bool, str | None]:
+ return validate_breezometer_credentials(config.api_key, config.locations)
+
+ def source_for_pipeline(self, config: BreezometerSourceConfig, inputs: SourceInputs) -> SourceResponse:
+ return breezometer_source(
+ api_key=config.api_key,
+ endpoint=inputs.schema_name,
+ locations_raw=config.locations,
+ logger=inputs.logger,
)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/breezometer/tests/test_breezometer.py b/products/warehouse_sources/backend/temporal/data_imports/sources/breezometer/tests/test_breezometer.py
new file mode 100644
index 000000000000..11ba86fb4c64
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/breezometer/tests/test_breezometer.py
@@ -0,0 +1,440 @@
+import json
+from typing import Any, Optional
+
+import pytest
+from unittest import mock
+
+import requests
+import structlog
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.breezometer.breezometer import (
+ MAX_LOCATIONS,
+ MAX_PAGES_PER_LOCATION,
+ BreezometerRetryableError,
+ Location,
+ _build_request,
+ _date_obj_to_iso,
+ _datetime_str_to_iso,
+ _fetch,
+ _normalize_rows,
+ _redact_key,
+ breezometer_source,
+ get_rows,
+ parse_locations,
+ validate_credentials,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.breezometer.settings import BREEZOMETER_ENDPOINTS
+
+MODULE = "products.warehouse_sources.backend.temporal.data_imports.sources.breezometer.breezometer"
+
+# Source the base URLs from the endpoint configs (the single source of truth) rather than duplicating
+# the literals here, so a base-URL change in settings can't leave these assertions checking a stale value.
+AIR_QUALITY_BASE_URL = BREEZOMETER_ENDPOINTS["air_quality_current"].base_url
+POLLEN_BASE_URL = BREEZOMETER_ENDPOINTS["pollen_forecast"].base_url
+
+
+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: {AIR_QUALITY_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)]),
+ ("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", "abc,def", "91,0", "0,181"],
+ )
+ 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 TestTimestampParsing:
+ @pytest.mark.parametrize(
+ "value, expected",
+ [
+ ({"year": 2024, "month": 6, "day": 23}, "2024-06-23T00:00:00+00:00"),
+ ({"year": 2024, "month": 1, "day": 1}, "2024-01-01T00:00:00+00:00"),
+ (None, None),
+ ({"year": 2024}, None),
+ ("not-a-dict", None),
+ ({"year": "x", "month": 1, "day": 1}, None),
+ ],
+ )
+ def test_date_obj_to_iso(self, value, expected):
+ assert _date_obj_to_iso(value) == expected
+
+ @pytest.mark.parametrize(
+ "value, expected",
+ [
+ ("2023-08-11T08:00:00Z", "2023-08-11T08:00:00+00:00"),
+ ("2023-08-11T08:00:00+00:00", "2023-08-11T08:00:00+00:00"),
+ # A non-UTC offset is normalized back to UTC.
+ ("2023-08-11T10:00:00+02:00", "2023-08-11T08:00:00+00:00"),
+ (None, None),
+ ("", None),
+ ("garbage", None),
+ (12345, None),
+ ],
+ )
+ def test_datetime_str_to_iso(self, value, expected):
+ assert _datetime_str_to_iso(value) == expected
+
+
+class TestRedactKey:
+ @pytest.mark.parametrize(
+ "text, expected",
+ [
+ ("https://x/v1/a:lookup?key=secret", "https://x/v1/a:lookup?key=REDACTED"),
+ ("https://x/v1/a:lookup?key=secret&days=5", "https://x/v1/a:lookup?key=REDACTED&days=5"),
+ ("https://x/v1/a:lookup?days=5&key=secret", "https://x/v1/a:lookup?days=5&key=REDACTED"),
+ # A field that merely contains "key" must not be redacted — only the `key` query param.
+ ("https://x/v1/a:lookup?pageToken=abc", "https://x/v1/a:lookup?pageToken=abc"),
+ ("no key here", "no key here"),
+ ],
+ )
+ def test_redact(self, text, expected):
+ assert _redact_key(text) == expected
+
+
+class TestBuildRequest:
+ def test_air_quality_current_is_post_with_body(self):
+ url, body = _build_request(
+ BREEZOMETER_ENDPOINTS["air_quality_current"], "secret-key", Location(51.5, -0.12), None
+ )
+
+ assert url == f"{AIR_QUALITY_BASE_URL}/v1/currentConditions:lookup?key=secret-key"
+ assert body is not None
+ assert body["location"] == {"latitude": 51.5, "longitude": -0.12}
+ assert "extraComputations" in body
+ # Current conditions take neither a forecast period nor a history window.
+ assert "period" not in body and "hours" not in body
+
+ def test_air_quality_forecast_includes_period(self):
+ _, body = _build_request(
+ BREEZOMETER_ENDPOINTS["air_quality_forecast"], "secret-key", Location(51.5, -0.12), None
+ )
+
+ assert body is not None
+ assert set(body["period"]) == {"startTime", "endTime"}
+ assert body["period"]["startTime"].endswith("Z")
+
+ def test_air_quality_history_includes_hours(self):
+ _, body = _build_request(
+ BREEZOMETER_ENDPOINTS["air_quality_history"], "secret-key", Location(51.5, -0.12), None
+ )
+
+ assert body is not None
+ assert body["hours"] == 24
+
+ def test_air_quality_page_token_goes_in_body(self):
+ _, body = _build_request(
+ BREEZOMETER_ENDPOINTS["air_quality_forecast"], "secret-key", Location(51.5, -0.12), "next-page"
+ )
+
+ assert body is not None
+ assert body["pageToken"] == "next-page"
+
+ def test_pollen_is_get_with_query_params(self):
+ url, body = _build_request(BREEZOMETER_ENDPOINTS["pollen_forecast"], "secret-key", Location(51.5, -0.12), None)
+
+ assert body is None
+ assert url.startswith(f"{POLLEN_BASE_URL}/v1/forecast:lookup?")
+ assert "key=secret-key" in url
+ assert "location.latitude=51.5" in url
+ assert "location.longitude=-0.12" in url
+ assert "days=5" in url
+
+ def test_pollen_page_token_goes_in_query(self):
+ url, _ = _build_request(
+ BREEZOMETER_ENDPOINTS["pollen_forecast"], "secret-key", Location(51.5, -0.12), "next-page"
+ )
+
+ assert "pageToken=next-page" in url
+
+
+class TestNormalizeRows:
+ def test_current_conditions_single_row_with_injected_coords(self):
+ response = {"dateTime": "2023-08-11T08:00:00Z", "regionCode": "uk", "indexes": [{"aqi": 42}]}
+ rows = _normalize_rows(BREEZOMETER_ENDPOINTS["air_quality_current"], response, Location(51.5, -0.12, "London"))
+
+ assert len(rows) == 1
+ row = rows[0]
+ assert row["latitude"] == 51.5
+ assert row["longitude"] == -0.12
+ assert row["location_label"] == "London"
+ assert row["dt_iso"] == "2023-08-11T08:00:00+00:00"
+ assert row["indexes"] == [{"aqi": 42}]
+
+ def test_forecast_yields_one_row_per_hour(self):
+ response = {
+ "hourlyForecasts": [
+ {"dateTime": "2023-08-11T08:00:00Z", "indexes": [{"aqi": 1}]},
+ {"dateTime": "2023-08-11T09:00:00Z", "indexes": [{"aqi": 2}]},
+ ]
+ }
+ rows = _normalize_rows(BREEZOMETER_ENDPOINTS["air_quality_forecast"], response, Location(51.5, -0.12))
+
+ assert [row["dt_iso"] for row in rows] == ["2023-08-11T08:00:00+00:00", "2023-08-11T09:00:00+00:00"]
+ assert all(row["latitude"] == 51.5 and row["longitude"] == -0.12 for row in rows)
+
+ def test_pollen_builds_dt_iso_from_date_object(self):
+ response = {"dailyInfo": [{"date": {"year": 2024, "month": 6, "day": 23}, "pollenTypeInfo": []}]}
+ rows = _normalize_rows(BREEZOMETER_ENDPOINTS["pollen_forecast"], response, Location(51.5, -0.12))
+
+ assert len(rows) == 1
+ assert rows[0]["dt_iso"] == "2024-06-23T00:00:00+00:00"
+
+ def test_rows_with_unparseable_timestamp_are_skipped(self):
+ # dt_iso is part of the primary/partition key; a row whose timestamp is present but unparseable
+ # must not flow a null key into the merge.
+ response = {
+ "hourlyForecasts": [{"dateTime": "", "indexes": [{"aqi": 1}]}, {"dateTime": "2023-08-11T08:00:00Z"}]
+ }
+ rows = _normalize_rows(BREEZOMETER_ENDPOINTS["air_quality_forecast"], response, Location(51.5, -0.12))
+
+ assert len(rows) == 1
+ assert rows[0]["dt_iso"] == "2023-08-11T08:00:00+00:00"
+
+ def test_missing_timestamp_field_raises(self):
+ # A missing timestamp field signals a structural API change (e.g. a renamed field) and must fail
+ # loudly rather than silently dropping every row and reporting a successful zero-row sync.
+ response = {"hourlyForecasts": [{"indexes": [{"aqi": 1}]}]}
+ with pytest.raises(KeyError):
+ _normalize_rows(BREEZOMETER_ENDPOINTS["air_quality_forecast"], response, Location(51.5, -0.12))
+
+
+# tenacity exposes the undecorated function via `__wrapped__`, so status classification can be
+# asserted without waiting through retry backoff.
+_fetch_once = _fetch.__wrapped__ # type: ignore[attr-defined]
+
+
+class TestFetch:
+ def test_air_quality_uses_post(self):
+ session = mock.MagicMock()
+ session.post.return_value = _response(200, {"dateTime": "2023-08-11T08:00:00Z"})
+
+ body = _fetch_once(
+ session,
+ BREEZOMETER_ENDPOINTS["air_quality_current"],
+ "k",
+ Location(51.5, -0.12),
+ None,
+ structlog.get_logger(),
+ )
+
+ assert body == {"dateTime": "2023-08-11T08:00:00Z"}
+ session.post.assert_called_once()
+ session.get.assert_not_called()
+
+ def test_pollen_uses_get(self):
+ session = mock.MagicMock()
+ session.get.return_value = _response(200, {"dailyInfo": []})
+
+ _fetch_once(
+ session, BREEZOMETER_ENDPOINTS["pollen_forecast"], "k", Location(51.5, -0.12), None, structlog.get_logger()
+ )
+
+ session.get.assert_called_once()
+ session.post.assert_not_called()
+
+ @pytest.mark.parametrize("status", [429, 500, 503])
+ def test_retryable_statuses_raise_retryable(self, status):
+ session = mock.MagicMock()
+ session.post.return_value = _response(status)
+
+ with pytest.raises(BreezometerRetryableError):
+ _fetch_once(
+ session,
+ BREEZOMETER_ENDPOINTS["air_quality_current"],
+ "k",
+ Location(51.5, -0.12),
+ None,
+ structlog.get_logger(),
+ )
+
+ def test_client_error_raises_for_status(self):
+ session = mock.MagicMock()
+ session.post.return_value = _response(400)
+
+ with pytest.raises(requests.HTTPError):
+ _fetch_once(
+ session,
+ BREEZOMETER_ENDPOINTS["air_quality_current"],
+ "k",
+ Location(51.5, -0.12),
+ None,
+ structlog.get_logger(),
+ )
+
+ def test_error_message_redacts_key(self):
+ resp = mock.MagicMock()
+ resp.status_code = 400
+ resp.ok = False
+ resp.text = '{"error":{"message":"API key not valid."}}'
+ resp.raise_for_status.side_effect = requests.HTTPError(
+ "400 Client Error: Bad Request for url: "
+ "https://airquality.googleapis.com/v1/currentConditions:lookup?key=SUPERSECRETKEY",
+ response=requests.Response(),
+ )
+ session = mock.MagicMock()
+ session.post.return_value = resp
+
+ with pytest.raises(requests.HTTPError) as exc_info:
+ _fetch_once(
+ session,
+ BREEZOMETER_ENDPOINTS["air_quality_current"],
+ "k",
+ Location(51.5, -0.12),
+ None,
+ structlog.get_logger(),
+ )
+
+ message = str(exc_info.value)
+ assert "SUPERSECRETKEY" not in message
+ assert "key=REDACTED" in message
+ # The host prefix is preserved so non-retryable-error matching still works.
+ assert "for url: https://airquality.googleapis.com" in message
+
+
+class TestValidateCredentials:
+ @pytest.mark.parametrize(
+ "status, expected_valid",
+ [(200, True), (400, False), (403, 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.post.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.post.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.post.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_conditions_with_first_location(self):
+ with mock.patch(f"{MODULE}.make_tracked_session") as mock_session:
+ mock_session.return_value.post.return_value = _response(200)
+
+ validate_credentials("test-key", "51.5,-0.12,London\n40.7,-74.0")
+
+ called_url = mock_session.return_value.post.call_args[0][0]
+ called_body = mock_session.return_value.post.call_args.kwargs["json"]
+
+ assert called_url.startswith(f"{AIR_QUALITY_BASE_URL}/v1/currentConditions:lookup?")
+ assert called_body["location"] == {"latitude": 51.5, "longitude": -0.12}
+
+
+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.post.side_effect = [
+ _response(200, {"dateTime": "2023-08-11T08:00:00Z", "indexes": []}),
+ _response(200, {"dateTime": "2023-08-11T09:00:00Z", "indexes": []}),
+ ]
+
+ batches = list(get_rows("test-key", "air_quality_current", locations, structlog.get_logger()))
+
+ assert len(batches) == 2
+ assert batches[0][0]["latitude"] == 51.5
+ assert batches[1][0]["latitude"] == 40.7
+
+ def test_follows_next_page_token(self):
+ with mock.patch(f"{MODULE}.make_tracked_session") as mock_session:
+ mock_session.return_value.post.side_effect = [
+ _response(200, {"hourlyForecasts": [{"dateTime": "2023-08-11T08:00:00Z"}], "nextPageToken": "p2"}),
+ _response(200, {"hourlyForecasts": [{"dateTime": "2023-08-11T09:00:00Z"}]}),
+ ]
+
+ batches = list(
+ get_rows("test-key", "air_quality_forecast", [Location(51.5, -0.12)], structlog.get_logger())
+ )
+
+ # The second request must carry the page token from the first response.
+ second_body = mock_session.return_value.post.call_args_list[1].kwargs["json"]
+
+ assert len(batches) == 2
+ assert second_body["pageToken"] == "p2"
+
+ def test_page_cap_stops_unbounded_pagination(self):
+ with mock.patch(f"{MODULE}.make_tracked_session") as mock_session:
+ # Every response advertises another page; the cap must stop the loop.
+ mock_session.return_value.post.return_value = _response(
+ 200, {"hourlyForecasts": [{"dateTime": "2023-08-11T08:00:00Z"}], "nextPageToken": "loop"}
+ )
+
+ batches = list(
+ get_rows("test-key", "air_quality_forecast", [Location(51.5, -0.12)], structlog.get_logger())
+ )
+
+ assert len(batches) == MAX_PAGES_PER_LOCATION
+
+ 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, {"dailyInfo": []})
+
+ batches = list(get_rows("test-key", "pollen_forecast", [Location(51.5, -0.12)], structlog.get_logger()))
+
+ assert batches == []
+
+
+class TestBreezometerSource:
+ @pytest.mark.parametrize("endpoint", list(BREEZOMETER_ENDPOINTS))
+ def test_source_response_shape(self, endpoint):
+ response = breezometer_source("test-key", endpoint, "51.5,-0.12,London", structlog.get_logger())
+
+ assert response.name == endpoint
+ assert response.primary_keys == ["latitude", "longitude", "dt_iso"]
+ 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):
+ breezometer_source("test-key", "air_quality_current", "garbage", structlog.get_logger())
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/breezometer/tests/test_breezometer_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/breezometer/tests/test_breezometer_source.py
new file mode 100644
index 000000000000..31842e467061
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/breezometer/tests/test_breezometer_source.py
@@ -0,0 +1,144 @@
+import pytest
+from unittest import mock
+
+import structlog
+
+from posthog.schema import ReleaseStatus, SourceFieldInputConfig, SourceFieldInputConfigType
+
+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import SourceInputs
+from products.warehouse_sources.backend.temporal.data_imports.sources.breezometer.settings import ENDPOINTS
+from products.warehouse_sources.backend.temporal.data_imports.sources.breezometer.source import BreezometerSource
+from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs import BreezometerSourceConfig
+from products.warehouse_sources.backend.types import ExternalDataSourceType
+
+
+def _make_inputs(schema_name: str = "air_quality_current") -> 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 TestBreezometerSource:
+ def setup_method(self):
+ self.source = BreezometerSource()
+ self.team_id = 123
+ self.config = BreezometerSourceConfig(api_key="test-key", locations="51.5,-0.12,London")
+
+ def test_source_type(self):
+ assert self.source.source_type == ExternalDataSourceType.BREEZOMETER
+
+ def test_get_source_config(self):
+ config = self.source.get_source_config
+
+ assert config.name.value == "Breezometer"
+ assert config.label == "BreezoMeter"
+ assert config.releaseStatus == ReleaseStatus.ALPHA
+ assert config.unreleasedSource is True
+ assert config.iconPath == "/static/services/breezometer.png"
+ assert config.docsUrl == "https://posthog.com/docs/cdp/sources/breezometer"
+
+ def test_get_source_config_fields(self):
+ fields = self.source.get_source_config.fields
+
+ 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_lists_tables_without_credentials(self):
+ # Static endpoint catalog with no I/O — must opt in so public docs render the table list.
+ assert self.source.lists_tables_without_credentials is True
+
+ 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 change cursor, 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_iso"]
+
+ def test_get_schemas_filtered_by_names(self):
+ schemas = self.source.get_schemas(self.config, self.team_id, names=["pollen_forecast"])
+
+ assert [schema.name for schema in schemas] == ["pollen_forecast"]
+
+ def test_get_schemas_filtered_unknown_name_returns_empty(self):
+ assert self.source.get_schemas(self.config, self.team_id, names=["nonexistent"]) == []
+
+ @pytest.mark.parametrize("host", ["airquality.googleapis.com", "pollen.googleapis.com"])
+ @pytest.mark.parametrize("status", ["400 Client Error: Bad Request", "403 Client Error: Forbidden"])
+ def test_non_retryable_errors_cover_both_hosts(self, host, status):
+ errors = self.source.get_non_retryable_errors()
+
+ assert any(status in key and host in key for key in errors)
+
+ def test_documented_tables_render_without_credentials(self):
+ # Exercises the public-docs path: a credential-free placeholder config must list every table.
+ tables = self.source.get_documented_tables()
+
+ assert {table["name"] for table in tables} == set(ENDPOINTS)
+
+ 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 API key"), False, "Invalid API key"),
+ ],
+ )
+ @mock.patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.breezometer.source.validate_breezometer_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, "air_quality_current")
+
+ 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(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.breezometer.source.breezometer_source"
+ )
+ def test_source_for_pipeline_plumbs_args(self, mock_breezometer_source):
+ inputs = _make_inputs(schema_name="pollen_forecast")
+
+ self.source.source_for_pipeline(self.config, inputs)
+
+ mock_breezometer_source.assert_called_once_with(
+ api_key="test-key",
+ endpoint="pollen_forecast",
+ locations_raw="51.5,-0.12,London",
+ logger=inputs.logger,
+ )
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.py b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.py
index 1c6b05ed1c8c..640ebf775970 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.py
@@ -481,7 +481,8 @@ class BrazeSourceConfig(config.Config):
@config.config
class BreezometerSourceConfig(config.Config):
- pass
+ api_key: str
+ locations: str
@config.config