:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(data-warehouse): implement open_exchange_rates import source (#67811)
Tom Owersb35745c1243c
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.mdindex c3b585436ae1..cf32d4e500e0 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md@@ -219,6 +219,7 @@ the row lists both.| notion | HTTP | requests | ✅ || omnisend | HTTP | requests | ✅ || onfleet | HTTP (cursor pagination) | requests | ✅ |+| open_exchange_rates | HTTP | requests | ✅ || orb | HTTP | requests + `rest_source.RESTClient` | ✅ || openweather | HTTP | requests | ✅ || ortto | HTTP | requests | ✅ |@@ -545,7 +546,6 @@ doesn't conflict with concurrent PRs.- onepagecrm- onesignal- open_data_dc-- open_exchange_rates- openaq- openfda- opinion_stagediff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.py b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.pyindex 57f63d714015..c7b7593ba544 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@@ -2248,7 +2248,9 @@ class OpenDataDcSourceConfig(config.Config):@config.configclass OpenExchangeRatesSourceConfig(config.Config):- pass+ app_id: str+ base_currency: str | None = None+ start_date: str | None = None@config.configdiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/open_exchange_rates/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/open_exchange_rates/canonical_descriptions.pynew file mode 100644index 000000000000..ddf673c8c4b6--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/open_exchange_rates/canonical_descriptions.py@@ -0,0 +1,55 @@+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (+ CanonicalDescriptions,+)++DOCS_URL = "https://docs.openexchangerates.org/reference/api-introduction"++CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {+ "currencies": {+ "description": "Reference catalog of every currency Open Exchange Rates supports, as one row per currency.",+ "docs_url": "https://docs.openexchangerates.org/reference/currencies-json",+ "columns": {+ "code": "Three-letter ISO 4217 currency code (e.g. USD, GBP, JPY).",+ "name": "Human-readable currency name (e.g. United States Dollar).",+ },+ },+ "latest": {+ "description": "The most recent available exchange rate for each currency against the base currency, as one row per currency.",+ "docs_url": "https://docs.openexchangerates.org/reference/latest-json",+ "columns": {+ "base": "Base currency the rates are quoted against (USD on the free plan).",+ "currency": "Three-letter ISO 4217 code of the quoted currency.",+ "rate": "Exchange rate: units of `currency` per one unit of `base`.",+ "date": "Date the rates apply to, derived from the response timestamp (YYYY-MM-DD, UTC).",+ "timestamp": "Unix timestamp of when the rates were last published.",+ },+ },+ "historical": {+ "description": "Daily historical exchange rates per currency, one row per (base, currency, date). Each value date is fetched from the /historical/{date}.json endpoint.",+ "docs_url": "https://docs.openexchangerates.org/reference/historical-json",+ "columns": {+ "base": "Base currency the rates are quoted against (USD on the free plan).",+ "currency": "Three-letter ISO 4217 code of the quoted currency.",+ "rate": "Exchange rate for that day: units of `currency` per one unit of `base`.",+ "date": "Value date of the rate (YYYY-MM-DD).",+ "timestamp": "Unix timestamp of when the rates for that day were published.",+ },+ },+ "usage": {+ "description": "Your Open Exchange Rates account plan and current-period request usage, as a single row.",+ "docs_url": "https://docs.openexchangerates.org/reference/usage-json",+ "columns": {+ "id": 'Constant synthetic key for this single-row snapshot (always "usage"). The account\'s App ID is deliberately not stored, as it is the API credential.',+ "status": "Account status (e.g. active).",+ "plan_name": "Name of the subscription plan (e.g. Free, Developer).",+ "plan_quota": "Human-readable monthly request quota for the plan.",+ "plan_update_frequency": "How often rates are refreshed on the plan.",+ "requests": "Number of requests made in the current billing period.",+ "requests_quota": "Total requests allowed in the current billing period.",+ "requests_remaining": "Requests remaining in the current billing period.",+ "days_elapsed": "Days elapsed in the current billing period.",+ "days_remaining": "Days remaining in the current billing period.",+ "daily_average": "Average requests per day so far this period.",+ },+ },+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/open_exchange_rates/open_exchange_rates.py b/products/warehouse_sources/backend/temporal/data_imports/sources/open_exchange_rates/open_exchange_rates.pynew file mode 100644index 000000000000..d461136fbb4b--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/open_exchange_rates/open_exchange_rates.py@@ -0,0 +1,298 @@+import dataclasses+from collections.abc import Iterator+from datetime import UTC, date, datetime, timedelta+from typing import Any, Optional+from urllib.parse import urlencode++import requests+from structlog.types import FilteringBoundLogger+from 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.common.http import make_tracked_session+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from products.warehouse_sources.backend.temporal.data_imports.sources.open_exchange_rates.settings import (+ OPEN_EXCHANGE_RATES_ENDPOINTS,+)++BASE_URL = "https://openexchangerates.org/api"+DEFAULT_BASE_CURRENCY = "USD"+REQUEST_TIMEOUT_SECONDS = 60+MAX_RETRY_ATTEMPTS = 6++# `historical` is walked one request per day, so a first-sync backfill with no configured start date+# stays deliberately small to avoid burning a free-tier monthly request quota (1000/month) in one run.+DEFAULT_LOOKBACK_DAYS = 30+++class OpenExchangeRatesRetryableError(Exception):+ """Raised for transient upstream failures (5xx) that are worth retrying."""++ pass+++class OpenExchangeRatesResumeConfig:+ # ISO date (YYYY-MM-DD) of the next `historical` day to fetch. Lets a multi-day backfill resume+ # mid-sync after a heartbeat timeout instead of restarting from the first day. Unused for the+ # single-response currencies/latest/usage endpoints.+ next_date: str | None = None+++def _build_url(path: str, params: dict[str, Any] | None = None) -> str:+ if params:+ return f"{BASE_URL}/{path}?{urlencode(params)}"+ return f"{BASE_URL}/{path}"+++def _auth_headers(app_id: str) -> dict[str, str]:+ # Send the App ID as a header rather than the `app_id` query param, so the credential never+ # appears in a request URL, log line, or raised error message.+ return {"Authorization": f"Token {app_id}"}+++def _request(session: requests.Session, path: str, params: dict[str, Any], logger: FilteringBoundLogger) -> Any:+ url = _build_url(path, params)+ response = session.get(url, timeout=REQUEST_TIMEOUT_SECONDS)++ # Open Exchange Rates uses real HTTP status codes. Only 5xx is transient — a 429 here means+ # `not_allowed` (the plan doesn't permit this feature/base), which is permanent, so it falls+ # through to the raise below and is surfaced via `get_non_retryable_errors()`.+ if response.status_code >= 500:+ raise OpenExchangeRatesRetryableError(f"Open Exchange Rates error (retryable): status={response.status_code}")++ if not response.ok:+ description = _error_description(response)+ logger.error(f"Open Exchange Rates error: status={response.status_code}, body={response.text}, url={url}")+ # The App ID rides in the Authorization header, not the URL, so the URL is safe to include —+ # it lets `get_non_retryable_errors()` match on the stable host prefix.+ raise requests.HTTPError(+ f"{response.status_code} Client Error: {response.reason} for url: {url}{description}",+ response=response,+ )++ return response.json()+++def _error_description(response: requests.Response) -> str:+ # Open Exchange Rates error bodies look like {"error": true, "status", "message", "description"}.+ # Append the human-readable description to the raised error when present, but never fail if the+ # body isn't the expected JSON.+ try:+ body = response.json()+ except ValueError:+ return ""+ if isinstance(body, dict) and body.get("description"):+ return f" — {body['description']}"+ return ""+++def validate_credentials(app_id: str) -> bool:+ """Confirm the App ID is genuine with the cheapest authenticated call (/usage.json). It requires+ a valid App ID (an invalid one returns 401) but is free and does not count toward the request+ quota. A valid App ID returns 200."""+ try:+ session = make_tracked_session(headers=_auth_headers(app_id), redact_values=(app_id,) if app_id else ())+ response = session.get(_build_url("usage.json"), timeout=10)+ return response.status_code == 200+ except Exception:+ return False+++def _iter_currencies(data: dict[str, Any]) -> list[dict[str, Any]]:+ # currencies.json is a flat {code: name} map.+ return [{"code": code, "name": name} for code, name in data.items()]+++def _iter_rates(data: dict[str, Any], value_date: str) -> list[dict[str, Any]]:+ # base is part of the composite primary key — fail fast rather than write None rows. latest.json+ # and historical/{date}.json share this {base, timestamp, rates: {currency: rate}} shape.+ base = data["base"]+ timestamp = data.get("timestamp")+ rates = data.get("rates") or {}+ return [+ {"base": base, "currency": currency, "rate": rate, "date": value_date, "timestamp": timestamp}+ for currency, rate in rates.items()+ ]+++def _iter_usage(data: dict[str, Any]) -> list[dict[str, Any]]:+ # usage.json wraps the account details under `data`; flatten the plan + usage blocks into one row.+ payload = data.get("data") or {}+ plan = payload.get("plan") or {}+ usage = payload.get("usage") or {}+ # Deliberately do NOT store the upstream `app_id`: it is the API credential (a secret field), so+ # writing it here would echo it into a queryable warehouse column. This is a single snapshot row+ # per source, so key it on a constant synthetic id instead.+ return [+ {+ "id": "usage",+ "status": payload.get("status"),+ "plan_name": plan.get("name"),+ "plan_quota": plan.get("quota"),+ "plan_update_frequency": plan.get("update_frequency"),+ "requests": usage.get("requests"),+ "requests_quota": usage.get("requests_quota"),+ "requests_remaining": usage.get("requests_remaining"),+ "days_elapsed": usage.get("days_elapsed"),+ "days_remaining": usage.get("days_remaining"),+ "daily_average": usage.get("daily_average"),+ }+ ]+++def _to_date(value: Any) -> Optional[date]:+ if value is None:+ return None+ if isinstance(value, datetime):+ return value.date()+ if isinstance(value, date):+ return value+ try:+ # Tolerate both bare dates and full ISO datetimes (the watermark may be stored either way).+ return datetime.fromisoformat(str(value).replace("Z", "+00:00")).date()+ except ValueError:+ return None+++def _date_from_timestamp(timestamp: Any) -> Optional[date]:+ if timestamp is None:+ return None+ try:+ return datetime.fromtimestamp(int(timestamp), tz=UTC).date()+ except (ValueError, OverflowError, OSError, TypeError):+ return None+++def _date_range(start: date, end: date) -> list[date]:+ if start > end:+ return []+ return [start + timedelta(days=offset) for offset in range((end - start).days + 1)]+++def _resolve_historical_start(+ should_use_incremental_field: bool,+ db_incremental_field_last_value: Any,+ configured_start_date: str | None,+ today: date,+) -> date:+ if should_use_incremental_field:+ watermark = _to_date(db_incremental_field_last_value)+ if watermark is not None:+ # Re-pull the watermark day; merge dedupes on the composite primary key.+ return watermark++ configured = _to_date(configured_start_date)+ if configured is not None:+ return configured++ return today - timedelta(days=DEFAULT_LOOKBACK_DAYS)+++def get_rows(+ app_id: str,+ endpoint: str,+ base_currency: str,+ start_date: str | None,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[OpenExchangeRatesResumeConfig],+ should_use_incremental_field: bool = False,+ db_incremental_field_last_value: Any = None,+) -> Iterator[list[dict[str, Any]]]:+ session = make_tracked_session(headers=_auth_headers(app_id), redact_values=(app_id,) if app_id else ())+ base = base_currency or DEFAULT_BASE_CURRENCY++ @retry(+ retry=retry_if_exception_type(+ (OpenExchangeRatesRetryableError, requests.ReadTimeout, requests.ConnectionError)+ ),+ stop=stop_after_attempt(MAX_RETRY_ATTEMPTS),+ wait=wait_exponential_jitter(initial=2, max=120),+ reraise=True,+ )+ def fetch(path: str, params: dict[str, Any]) -> Any:+ return _request(session, path, params, logger)++ if endpoint == "currencies":+ rows = _iter_currencies(fetch("currencies.json", {}))+ if rows:+ yield rows+ return++ if endpoint == "usage":+ rows = _iter_usage(fetch("usage.json", {}))+ if rows:+ yield rows+ return++ if endpoint == "latest":+ data = fetch("latest.json", {"base": base})+ value_date = _date_from_timestamp(data.get("timestamp")) or datetime.now(tz=UTC).date()+ rows = _iter_rates(data, value_date.isoformat())+ if rows:+ yield rows+ return++ if endpoint == "historical":+ today = datetime.now(tz=UTC).date()+ # Only walk finalized past days (up to yesterday). Today's snapshot lives in `latest`.+ end = today - timedelta(days=1)+ start = _resolve_historical_start(+ should_use_incremental_field, db_incremental_field_last_value, start_date, today+ )+ days = _date_range(start, end)++ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None+ if resume is not None and resume.next_date:+ days = [day for day in days if day.isoformat() >= resume.next_date]+ logger.debug(f"Open Exchange Rates: resuming historical from {resume.next_date}")++ for index, value_date in enumerate(days):+ data = fetch(f"historical/{value_date.isoformat()}.json", {"base": base})+ rows = _iter_rates(data, value_date.isoformat())+ if rows:+ yield rows++ # Save AFTER yielding so a crash re-yields the last day rather than skipping it (merge+ # dedupes on the composite primary key).+ if index + 1 < len(days):+ resumable_source_manager.save_state(+ OpenExchangeRatesResumeConfig(next_date=days[index + 1].isoformat())+ )+ return++ raise ValueError(f"Unknown Open Exchange Rates endpoint: {endpoint}")+++def open_exchange_rates_source(+ app_id: str,+ endpoint: str,+ base_currency: str,+ start_date: str | None,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[OpenExchangeRatesResumeConfig],+ should_use_incremental_field: bool = False,+ db_incremental_field_last_value: Optional[Any] = None,+) -> SourceResponse:+ config = OPEN_EXCHANGE_RATES_ENDPOINTS[endpoint]++ return SourceResponse(+ name=endpoint,+ items=lambda: get_rows(+ app_id=app_id,+ endpoint=endpoint,+ base_currency=base_currency,+ start_date=start_date,+ logger=logger,+ resumable_source_manager=resumable_source_manager,+ should_use_incremental_field=should_use_incremental_field,+ db_incremental_field_last_value=db_incremental_field_last_value,+ ),+ primary_keys=config.primary_keys,+ partition_count=1,+ partition_size=1,+ partition_keys=config.partition_keys,+ partition_mode=config.partition_mode,+ partition_format=config.partition_format,+ sort_mode="asc",+ )diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/open_exchange_rates/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/open_exchange_rates/settings.pynew file mode 100644index 000000000000..421d4e313be8--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/open_exchange_rates/settings.py@@ -0,0 +1,83 @@+from dataclasses import dataclass, field++from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import (+ PartitionFormat,+ PartitionMode,+)+from products.warehouse_sources.backend.types import IncrementalField, IncrementalFieldType+++@dataclass+class OpenExchangeRatesEndpointConfig:+ name: str+ # Fields the rows are merged on. The rate endpoints carry one row per (base, currency, date), so+ # the natural key is the composite — a single currency code repeats across dates and base+ # currencies.+ primary_keys: list[str]+ incremental_fields: list[IncrementalField] = field(default_factory=list)+ # Only set on `historical`, which selects a single value date server-side (via the URL path), so+ # an incremental sync only fetches days newer than the watermark rather than the whole history.+ supports_incremental: bool = False+ # `date` is the rate's value date — historical rates never change, so it's a stable partition key.+ partition_keys: list[str] | None = None+ partition_mode: PartitionMode | None = None+ partition_format: PartitionFormat | None = None+ should_sync_default: bool = True+ description: str | None = None+++_DATE_INCREMENTAL_FIELD: IncrementalField = {+ "label": "date",+ "type": IncrementalFieldType.Date,+ "field": "date",+ "field_type": IncrementalFieldType.Date,+}+++OPEN_EXCHANGE_RATES_ENDPOINTS: dict[str, OpenExchangeRatesEndpointConfig] = {+ # /currencies.json — reference catalog of every supported currency as {code, name} rows. One+ # response, free, and does not count toward the monthly request quota.+ "currencies": OpenExchangeRatesEndpointConfig(+ name="currencies",+ primary_keys=["code"],+ description="All currencies the API supports, as {code, name} rows. Full refresh only.",+ ),+ # /latest.json — the most recent rates for every currency against the base, as one row per+ # currency. A live snapshot with no server-side time filter, so full refresh only.+ "latest": OpenExchangeRatesEndpointConfig(+ name="latest",+ primary_keys=["base", "currency", "date"],+ partition_keys=["date"],+ partition_mode="datetime",+ partition_format="month",+ description="Latest exchange rate per currency against the base currency. Full refresh only.",+ ),+ # /historical/{date}.json — the daily rates for a single value date, normalized to one row per+ # (base, currency, date). Backfills walk one request per day from the start date (or the+ # incremental watermark) up to yesterday, so an incremental sync only fetches new days. The value+ # date is the natural, stable incremental cursor.+ "historical": OpenExchangeRatesEndpointConfig(+ name="historical",+ primary_keys=["base", "currency", "date"],+ incremental_fields=[_DATE_INCREMENTAL_FIELD],+ supports_incremental=True,+ partition_keys=["date"],+ partition_mode="datetime",+ partition_format="month",+ description="Daily historical rates per currency, one request per day (walked from the start date). Supports incremental sync on the value date.",+ ),+ # /usage.json — the account's plan and current-period request usage as a single flattened row.+ # Free and does not count toward the monthly request quota. Keyed on a constant synthetic id+ # (`id`) rather than the account's app_id, which is the API credential and must not be persisted.+ "usage": OpenExchangeRatesEndpointConfig(+ name="usage",+ primary_keys=["id"],+ description="Your Open Exchange Rates plan and current request usage, as a single row. Full refresh only.",+ ),+}++ENDPOINTS = tuple(OPEN_EXCHANGE_RATES_ENDPOINTS.keys())++INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {+ name: config.incremental_fields for name, config in OPEN_EXCHANGE_RATES_ENDPOINTS.items()+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/open_exchange_rates/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/open_exchange_rates/source.pyindex 921afe567988..66a79351c4d7 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/open_exchange_rates/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/open_exchange_rates/source.py@@ -1,21 +1,43 @@-from typing import cast+from typing import Optional, castfrom posthog.schema import (DataWarehouseSourceCategory,ExternalDataSourceType as SchemaExternalDataSourceType,+ ReleaseStatus,SourceConfig,+ SourceFieldInputConfig,+ SourceFieldInputConfigType,)-from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, SimpleSource+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import (+ SourceInputs,+ SourceResponse,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, ResumableSource+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (+ CanonicalDescriptions,+)from products.warehouse_sources.backend.temporal.data_imports.sources.common.registry import SourceRegistry+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from products.warehouse_sources.backend.temporal.data_imports.sources.common.schema import SourceSchemafrom products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs import (OpenExchangeRatesSourceConfig,)+from products.warehouse_sources.backend.temporal.data_imports.sources.open_exchange_rates.open_exchange_rates import (+ OpenExchangeRatesResumeConfig,+ open_exchange_rates_source,+ validate_credentials as validate_open_exchange_rates_credentials,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.open_exchange_rates.settings import (+ OPEN_EXCHANGE_RATES_ENDPOINTS,+)from products.warehouse_sources.backend.types import ExternalDataSourceType@SourceRegistry.register-class OpenExchangeRatesSource(SimpleSource[OpenExchangeRatesSourceConfig]):+class OpenExchangeRatesSource(ResumableSource[OpenExchangeRatesSourceConfig, OpenExchangeRatesResumeConfig]):+ lists_tables_without_credentials = True # static endpoint catalog — safe for public docs+@propertydef source_type(self) -> ExternalDataSourceType:return ExternalDataSourceType.OPENEXCHANGERATES@@ -26,7 +48,125 @@ class OpenExchangeRatesSource(SimpleSource[OpenExchangeRatesSourceConfig]):name=SchemaExternalDataSourceType.OPEN_EXCHANGE_RATES,category=DataWarehouseSourceCategory.FINANCE___ACCOUNTING,label="Open Exchange Rates",- iconPath="/static/services/open_exchange_rates.png",- fields=cast(list[FieldType], []),+ releaseStatus=ReleaseStatus.ALPHA,unreleasedSource=True,+ caption="""Enter your Open Exchange Rates App ID to pull foreign-exchange reference rates into the PostHog Data warehouse.++Find your App ID in your [Open Exchange Rates dashboard](https://openexchangerates.org/account/app-ids).++The free plan is restricted to the `USD` base currency — a custom base currency requires a paid plan. The `historical` table walks one request per day from the start date, so a large backfill can use a lot of your monthly request quota.""",+ iconPath="/static/services/open_exchange_rates.png",+ docsUrl="https://posthog.com/docs/cdp/sources/open-exchange-rates",+ keywords=["oxr", "forex", "currency", "fx", "exchange rates"],+ fields=cast(+ list[FieldType],+ [+ SourceFieldInputConfig(+ name="app_id",+ label="App ID",+ type=SourceFieldInputConfigType.PASSWORD,+ required=True,+ placeholder="",+ secret=True,+ ),+ SourceFieldInputConfig(+ name="base_currency",+ label="Base currency",+ type=SourceFieldInputConfigType.TEXT,+ required=False,+ placeholder="USD",+ secret=False,+ ),+ SourceFieldInputConfig(+ name="start_date",+ label="Start date (historical backfill)",+ type=SourceFieldInputConfigType.TEXT,+ required=False,+ placeholder="YYYY-MM-DD",+ secret=False,+ ),+ ],+ ),+ )++ def get_canonical_descriptions(self) -> CanonicalDescriptions:+ from products.warehouse_sources.backend.temporal.data_imports.sources.open_exchange_rates.canonical_descriptions import (+ CANONICAL_DESCRIPTIONS,+ )++ return CANONICAL_DESCRIPTIONS++ def get_non_retryable_errors(self) -> dict[str, str | None]:+ return {+ # An invalid, missing, or revoked App ID surfaces as a 401 when `_request` raises. Retrying+ # can never fix a credential problem, so stop the sync. Match the stable status text and+ # base host, not the per-request path.+ "401 Client Error: Unauthorized for url: https://openexchangerates.org/api": "Your Open Exchange Rates App ID is invalid or has been revoked. Create a new App ID in your Open Exchange Rates dashboard, then reconnect.",+ "403 Client Error: Forbidden for url: https://openexchangerates.org/api": "Your Open Exchange Rates App ID is missing or your account is restricted. Check the App ID and your account status, then reconnect.",+ # Open Exchange Rates returns 429 `not_allowed` for plan-gated features (e.g. a non-USD base+ # currency on the free plan), not a transient throttle — so it is permanent, not retryable.+ "429 Client Error: Too Many Requests for url: https://openexchangerates.org/api": "Your Open Exchange Rates plan does not allow this request (for example a non-USD base currency on the free plan). Upgrade your plan or set the base currency back to USD, then reconnect.",+ }++ def get_schemas(+ self,+ config: OpenExchangeRatesSourceConfig,+ team_id: int,+ with_counts: bool = False,+ names: list[str] | None = None,+ force_refresh: bool = False,+ ) -> list[SourceSchema]:+ schemas = [+ SourceSchema(+ name=endpoint_config.name,+ supports_incremental=endpoint_config.supports_incremental,+ supports_append=endpoint_config.supports_incremental,+ incremental_fields=endpoint_config.incremental_fields,+ should_sync_default=endpoint_config.should_sync_default,+ description=endpoint_config.description,+ )+ for endpoint_config in OPEN_EXCHANGE_RATES_ENDPOINTS.values()+ ]++ 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: OpenExchangeRatesSourceConfig, team_id: int, schema_name: Optional[str] = None+ ) -> tuple[bool, str | None]:+ if validate_open_exchange_rates_credentials(config.app_id):+ return True, None++ # The probe also returns False on transient network/timeout errors, so don't claim the App ID+ # is definitively invalid — point at both possibilities.+ return (+ False,+ "Unable to verify your Open Exchange Rates App ID. Check that the App ID is correct and that openexchangerates.org is reachable.",+ )++ def get_resumable_source_manager(+ self, inputs: SourceInputs+ ) -> ResumableSourceManager[OpenExchangeRatesResumeConfig]:+ return ResumableSourceManager[OpenExchangeRatesResumeConfig](inputs, OpenExchangeRatesResumeConfig)++ def source_for_pipeline(+ self,+ config: OpenExchangeRatesSourceConfig,+ resumable_source_manager: ResumableSourceManager[OpenExchangeRatesResumeConfig],+ inputs: SourceInputs,+ ) -> SourceResponse:+ return open_exchange_rates_source(+ app_id=config.app_id,+ endpoint=inputs.schema_name,+ base_currency=config.base_currency or "",+ start_date=config.start_date,+ logger=inputs.logger,+ resumable_source_manager=resumable_source_manager,+ should_use_incremental_field=inputs.should_use_incremental_field,+ db_incremental_field_last_value=inputs.db_incremental_field_last_value+ if inputs.should_use_incremental_field+ else None,)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/open_exchange_rates/tests/test_open_exchange_rates.py b/products/warehouse_sources/backend/temporal/data_imports/sources/open_exchange_rates/tests/test_open_exchange_rates.pynew file mode 100644index 000000000000..735e84fa3f8e--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/open_exchange_rates/tests/test_open_exchange_rates.py@@ -0,0 +1,406 @@+from datetime import UTC, date, datetime+from typing import Any++import pytest+from unittest import mock++import requests+from parameterized import parameterized++from products.warehouse_sources.backend.temporal.data_imports.sources.open_exchange_rates import open_exchange_rates+from products.warehouse_sources.backend.temporal.data_imports.sources.open_exchange_rates.open_exchange_rates import (+ BASE_URL,+ DEFAULT_BASE_CURRENCY,+ OpenExchangeRatesResumeConfig,+ OpenExchangeRatesRetryableError,+ _build_url,+ _date_from_timestamp,+ _date_range,+ _iter_currencies,+ _iter_rates,+ _iter_usage,+ _resolve_historical_start,+ _to_date,+ get_rows,+ open_exchange_rates_source,+ validate_credentials,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.open_exchange_rates.settings import (+ OPEN_EXCHANGE_RATES_ENDPOINTS,+)+++class _FakeResponse:+ def __init__(self, status_code: int = 200, json_data: Any = None, text: str = "", reason: str = ""):+ self.status_code = status_code+ self._json_data = json_data+ self.text = text+ self.reason = reason+ self.url: str = ""++ @property+ def ok(self) -> bool:+ return self.status_code < 400++ def json(self) -> Any:+ if isinstance(self._json_data, Exception):+ raise self._json_data+ return self._json_data+++class _FakeSession:+ """Returns queued responses in order; records the URLs requested."""++ def __init__(self, responses: list[_FakeResponse]):+ self._responses = list(responses)+ self.requested_urls: list[str] = []++ def get(self, url: str, **kwargs: Any) -> _FakeResponse:+ self.requested_urls.append(url)+ response = self._responses.pop(0)+ response.url = url+ return response+++def _manager(can_resume: bool = False, state: OpenExchangeRatesResumeConfig | None = None) -> mock.MagicMock:+ manager = mock.MagicMock()+ manager.can_resume.return_value = can_resume+ manager.load_state.return_value = state+ return manager+++class TestBuildUrl:+ def test_encodes_params_under_base_url(self) -> None:+ assert _build_url("latest.json", {"base": "EUR"}) == f"{BASE_URL}/latest.json?base=EUR"++ def test_omits_query_when_no_params(self) -> None:+ assert _build_url("currencies.json") == f"{BASE_URL}/currencies.json"+++class TestRequest:+ @parameterized.expand([(500,), (502,), (503,)])+ def test_5xx_statuses_raise_retryable_error(self, status: int) -> None:+ session = _FakeSession([_FakeResponse(status_code=status, json_data=None)])+ with pytest.raises(OpenExchangeRatesRetryableError):+ open_exchange_rates._request(session, "latest.json", {}, mock.MagicMock()) # type: ignore[arg-type]++ @parameterized.expand([(401,), (403,), (429,)])+ def test_client_errors_raise_http_error(self, status: int) -> None:+ # 429 is `not_allowed` (plan-gated), not a transient throttle — it must NOT be retryable.+ session = _FakeSession([_FakeResponse(status_code=status, json_data=None, text="nope")])+ with pytest.raises(requests.HTTPError):+ open_exchange_rates._request(session, "latest.json", {}, mock.MagicMock()) # type: ignore[arg-type]++ def test_error_description_appended(self) -> None:+ body = {"error": True, "status": 401, "message": "invalid_app_id", "description": "Invalid App ID provided."}+ session = _FakeSession([_FakeResponse(status_code=401, json_data=body, reason="Unauthorized")])+ with pytest.raises(requests.HTTPError) as exc:+ open_exchange_rates._request(session, "latest.json", {}, mock.MagicMock()) # type: ignore[arg-type]+ assert "Invalid App ID provided." in str(exc.value)++ def test_success_returns_parsed_body(self) -> None:+ body = {"base": "USD", "rates": {"GBP": 0.8}}+ session = _FakeSession([_FakeResponse(status_code=200, json_data=body)])+ assert open_exchange_rates._request(session, "latest.json", {"base": "USD"}, mock.MagicMock()) == body # type: ignore[arg-type]+++class TestValidateCredentials:+ @parameterized.expand([("valid", 200, True), ("unauthorized", 401, False)])+ @mock.patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.open_exchange_rates.open_exchange_rates.make_tracked_session"+ )+ def test_status_mapping(self, _name: str, status: int, expected: bool, mock_session: mock.MagicMock) -> None:+ mock_session.return_value.get.return_value = _FakeResponse(status_code=status)+ assert validate_credentials("key") is expected++ @mock.patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.open_exchange_rates.open_exchange_rates.make_tracked_session"+ )+ def test_exception_returns_false(self, mock_session: mock.MagicMock) -> None:+ mock_session.return_value.get.side_effect = requests.ConnectionError("boom")+ assert validate_credentials("key") is False++ @mock.patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.open_exchange_rates.open_exchange_rates.make_tracked_session"+ )+ def test_probes_usage_with_header_auth_and_redacts_key(self, mock_session: mock.MagicMock) -> None:+ get = mock_session.return_value.get+ get.return_value = _FakeResponse(status_code=200)+ validate_credentials("secret")++ url = get.call_args.args[0]+ # usage.json validates the App ID but is free and does not count toward the request quota.+ assert url == f"{BASE_URL}/usage.json"+ # App ID rides in the Authorization header, and is redacted by value as defense in depth.+ assert mock_session.call_args.kwargs["headers"] == {"Authorization": "Token secret"}+ assert mock_session.call_args.kwargs["redact_values"] == ("secret",)+++class TestNormalization:+ def test_iter_currencies(self) -> None:+ data = {"USD": "US Dollar", "GBP": "Pound Sterling"}+ assert _iter_currencies(data) == [+ {"code": "USD", "name": "US Dollar"},+ {"code": "GBP", "name": "Pound Sterling"},+ ]++ def test_iter_rates(self) -> None:+ data = {"base": "USD", "timestamp": 1704153600, "rates": {"EUR": 0.9, "GBP": 0.8}}+ assert _iter_rates(data, "2024-01-02") == [+ {"base": "USD", "currency": "EUR", "rate": 0.9, "date": "2024-01-02", "timestamp": 1704153600},+ {"base": "USD", "currency": "GBP", "rate": 0.8, "date": "2024-01-02", "timestamp": 1704153600},+ ]++ def test_iter_usage_flattens_plan_and_usage(self) -> None:+ data = {+ "status": 200,+ "data": {+ "app_id": "abc123",+ "status": "active",+ "plan": {"name": "Free", "quota": "1000 requests / month", "update_frequency": "3600s"},+ "usage": {+ "requests": 34,+ "requests_quota": 1000,+ "requests_remaining": 966,+ "days_elapsed": 2,+ "days_remaining": 28,+ "daily_average": 17,+ },+ },+ }+ rows = _iter_usage(data)+ assert rows == [+ {+ "id": "usage",+ "status": "active",+ "plan_name": "Free",+ "plan_quota": "1000 requests / month",+ "plan_update_frequency": "3600s",+ "requests": 34,+ "requests_quota": 1000,+ "requests_remaining": 966,+ "days_elapsed": 2,+ "days_remaining": 28,+ "daily_average": 17,+ }+ ]++ def test_iter_usage_never_stores_the_credential(self) -> None:+ # app_id is the API credential (a secret) — it must never be written into the synced row.+ rows = _iter_usage({"data": {"app_id": "SECRET_APP_ID", "plan": {}, "usage": {}}})+ assert rows == [+ {+ "id": "usage",+ "status": None,+ "plan_name": None,+ "plan_quota": None,+ "plan_update_frequency": None,+ "requests": None,+ "requests_quota": None,+ "requests_remaining": None,+ "days_elapsed": None,+ "days_remaining": None,+ "daily_average": None,+ }+ ]+ assert "SECRET_APP_ID" not in str(rows)+++class TestToDate:+ @parameterized.expand(+ [+ ("iso_date", "2024-03-04", date(2024, 3, 4)),+ ("iso_datetime", "2024-03-04T12:00:00", date(2024, 3, 4)),+ ("zulu", "2024-03-04T12:00:00Z", date(2024, 3, 4)),+ ("garbage", "not-a-date", None),+ ("none", None, None),+ ]+ )+ def test_parses(self, _name: str, value: Any, expected: date | None) -> None:+ assert _to_date(value) == expected+++class TestDateFromTimestamp:+ def test_converts_unix_timestamp_to_utc_date(self) -> None:+ # 1704153600 == 2024-01-02T00:00:00Z+ assert _date_from_timestamp(1704153600) == date(2024, 1, 2)++ @parameterized.expand([("none", None), ("garbage", "abc")])+ def test_bad_values_return_none(self, _name: str, value: Any) -> None:+ assert _date_from_timestamp(value) is None+++class TestDateRange:+ @parameterized.expand(+ [+ (+ "inclusive_range",+ date(2024, 1, 1),+ date(2024, 1, 3),+ [date(2024, 1, 1), date(2024, 1, 2), date(2024, 1, 3)],+ ),+ ("single_day", date(2024, 1, 1), date(2024, 1, 1), [date(2024, 1, 1)]),+ ("empty_when_start_after_end", date(2024, 2, 1), date(2024, 1, 1), []),+ ]+ )+ def test_date_range(self, _name: str, start: date, end: date, expected: list[date]) -> None:+ assert _date_range(start, end) == expected+++class TestResolveHistoricalStart:+ @parameterized.expand(+ [+ # incremental with a watermark → re-pull from the watermark day+ ("watermark_when_incremental", True, "2024-05-05", "2020-01-01", date(2024, 5, 5)),+ # incremental but no watermark yet → fall back to the configured start+ ("configured_start_when_no_watermark", True, None, "2020-01-01", date(2020, 1, 1)),+ # not incremental → ignore the watermark, use the configured start+ ("configured_start_when_not_incremental", False, "2024-05-05", "2020-01-01", date(2020, 1, 1)),+ # nothing configured → 30-day default lookback keeps a first backfill small on a quota-limited plan+ ("defaults_to_lookback", False, None, None, date(2024, 5, 2)),+ ]+ )+ def test_resolve_start(+ self, _name: str, incremental: bool, watermark: Any, configured: str | None, expected: date+ ) -> None:+ assert _resolve_historical_start(incremental, watermark, configured, date(2024, 6, 1)) == expected+++class TestGetRows:+ def _run(+ self, endpoint: str, responses: list[_FakeResponse], manager: mock.MagicMock, **kwargs: Any+ ) -> tuple[list[Any], _FakeSession]:+ session = _FakeSession(responses)+ with mock.patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.open_exchange_rates.open_exchange_rates.make_tracked_session",+ return_value=session,+ ):+ return list(get_rows("key", endpoint, "USD", None, mock.MagicMock(), manager, **kwargs)), session++ def test_currencies_yields_once(self) -> None:+ batches, _ = self._run("currencies", [_FakeResponse(json_data={"USD": "US Dollar"})], _manager())+ assert batches == [[{"code": "USD", "name": "US Dollar"}]]++ def test_currencies_empty_yields_nothing(self) -> None:+ batches, _ = self._run("currencies", [_FakeResponse(json_data={})], _manager())+ assert batches == []++ def test_usage_yields_once(self) -> None:+ body = {"data": {"app_id": "abc", "plan": {}, "usage": {"requests": 1}}}+ batches, session = self._run("usage", [_FakeResponse(json_data=body)], _manager())+ assert batches[0][0]["id"] == "usage"+ assert batches[0][0]["requests"] == 1+ # The credential must not be echoed into the synced row.+ assert "app_id" not in batches[0][0]+ assert session.requested_urls == [f"{BASE_URL}/usage.json"]++ def test_latest_sends_base_and_derives_date_from_timestamp(self) -> None:+ body = {"base": "USD", "timestamp": 1704153600, "rates": {"EUR": 0.9}}+ batches, session = self._run("latest", [_FakeResponse(json_data=body)], _manager())+ assert batches == [+ [{"base": "USD", "currency": "EUR", "rate": 0.9, "date": "2024-01-02", "timestamp": 1704153600}]+ ]+ assert "base=USD" in session.requested_urls[0]++ def test_historical_walks_each_day_and_saves_state_between(self) -> None:+ manager = _manager()+ days = [date(2024, 1, 1), date(2024, 1, 2)]+ body1 = {"base": "USD", "timestamp": 1, "rates": {"EUR": 0.9}}+ body2 = {"base": "USD", "timestamp": 2, "rates": {"EUR": 0.95}}+ session = _FakeSession([_FakeResponse(json_data=body1), _FakeResponse(json_data=body2)])+ with (+ mock.patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.open_exchange_rates.open_exchange_rates.make_tracked_session",+ return_value=session,+ ),+ mock.patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.open_exchange_rates.open_exchange_rates._date_range",+ return_value=days,+ ),+ ):+ batches = list(+ get_rows(+ "key",+ "historical",+ "USD",+ "2024-01-01",+ mock.MagicMock(),+ manager,+ should_use_incremental_field=True,+ db_incremental_field_last_value="2024-01-01",+ )+ )+ assert [b[0]["date"] for b in batches] == ["2024-01-01", "2024-01-02"]+ assert session.requested_urls == [+ f"{BASE_URL}/historical/2024-01-01.json?base=USD",+ f"{BASE_URL}/historical/2024-01-02.json?base=USD",+ ]+ # State saved AFTER the first day (pointing at the next day), never after the last.+ manager.save_state.assert_called_once_with(OpenExchangeRatesResumeConfig(next_date="2024-01-02"))++ def test_historical_resumes_from_saved_day(self) -> None:+ manager = _manager(can_resume=True, state=OpenExchangeRatesResumeConfig(next_date="2024-01-02"))+ days = [date(2024, 1, 1), date(2024, 1, 2)]+ body2 = {"base": "USD", "timestamp": 2, "rates": {"EUR": 0.95}}+ session = _FakeSession([_FakeResponse(json_data=body2)])+ with (+ mock.patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.open_exchange_rates.open_exchange_rates.make_tracked_session",+ return_value=session,+ ),+ mock.patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.open_exchange_rates.open_exchange_rates._date_range",+ return_value=days,+ ),+ ):+ batches = list(get_rows("key", "historical", "USD", "2024-01-01", mock.MagicMock(), manager))+ # Only the day at/after the resume point is fetched.+ assert session.requested_urls == [f"{BASE_URL}/historical/2024-01-02.json?base=USD"]+ assert [b[0]["date"] for b in batches] == ["2024-01-02"]++ def test_unknown_endpoint_raises(self) -> None:+ with pytest.raises(ValueError):+ self._run("nope", [], _manager())+++class TestOpenExchangeRatesSourceResponse:+ @parameterized.expand(+ [+ ("currencies", ["code"]),+ ("latest", ["base", "currency", "date"]),+ ("historical", ["base", "currency", "date"]),+ ("usage", ["id"]),+ ]+ )+ def test_primary_keys_per_endpoint(self, endpoint: str, expected_keys: list[str]) -> None:+ response = open_exchange_rates_source("key", endpoint, "USD", None, mock.MagicMock(), mock.MagicMock())+ assert response.name == endpoint+ assert response.primary_keys == expected_keys+ assert response.sort_mode == "asc"++ @parameterized.expand([("latest",), ("historical",)])+ def test_rate_endpoints_partition_on_stable_date(self, endpoint: str) -> None:+ response = open_exchange_rates_source("key", endpoint, "USD", None, mock.MagicMock(), mock.MagicMock())+ assert response.partition_keys == ["date"]+ assert response.partition_mode == "datetime"+ assert response.partition_format == "month"++ @parameterized.expand([("currencies",), ("usage",)])+ def test_catalog_endpoints_are_not_partitioned(self, endpoint: str) -> None:+ response = open_exchange_rates_source("key", endpoint, "USD", None, mock.MagicMock(), mock.MagicMock())+ assert response.partition_keys is None++ def test_every_settings_endpoint_builds_a_source_response(self) -> None:+ for endpoint in OPEN_EXCHANGE_RATES_ENDPOINTS:+ response = open_exchange_rates_source("key", endpoint, "USD", None, mock.MagicMock(), mock.MagicMock())+ assert response.name == endpoint+ assert response.primary_keys == OPEN_EXCHANGE_RATES_ENDPOINTS[endpoint].primary_keys++ def test_default_base_currency_is_usd(self) -> None:+ assert DEFAULT_BASE_CURRENCY == "USD"+++class TestUtcTodayUsage:+ def test_datetime_now_is_timezone_aware(self) -> None:+ # Guard the UTC handling that derives the `latest` value date and the historical window.+ assert datetime.now(tz=UTC).tzinfo is not Nonediff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/open_exchange_rates/tests/test_open_exchange_rates_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/open_exchange_rates/tests/test_open_exchange_rates_source.pynew file mode 100644index 000000000000..ea99469890c2--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/open_exchange_rates/tests/test_open_exchange_rates_source.py@@ -0,0 +1,178 @@+import pytest+from unittest import mock++from posthog.schema import (+ DataWarehouseSourceCategory,+ ReleaseStatus,+ SourceFieldInputConfig,+ SourceFieldInputConfigType,+)++from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs import (+ OpenExchangeRatesSourceConfig,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.open_exchange_rates.open_exchange_rates import (+ OpenExchangeRatesResumeConfig,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.open_exchange_rates.settings import ENDPOINTS+from products.warehouse_sources.backend.temporal.data_imports.sources.open_exchange_rates.source import (+ OpenExchangeRatesSource,+)+from products.warehouse_sources.backend.types import ExternalDataSourceType+++class TestOpenExchangeRatesSource:+ def setup_method(self) -> None:+ self.source = OpenExchangeRatesSource()+ self.team_id = 123+ self.config = OpenExchangeRatesSourceConfig(app_id="oxr-test", base_currency="USD", start_date=None)++ def test_source_type(self) -> None:+ assert self.source.source_type == ExternalDataSourceType.OPENEXCHANGERATES++ def test_get_source_config(self) -> None:+ config = self.source.get_source_config++ assert config.name.value == "OpenExchangeRates"+ assert config.label == "Open Exchange Rates"+ assert config.category == DataWarehouseSourceCategory.FINANCE___ACCOUNTING+ assert config.releaseStatus == ReleaseStatus.ALPHA+ # Kept behind the unreleased flag until the source has been exercised end to end.+ assert config.unreleasedSource is True+ assert config.docsUrl == "https://posthog.com/docs/cdp/sources/open-exchange-rates"+ assert [f.name for f in config.fields] == ["app_id", "base_currency", "start_date"]++ def test_app_id_field_is_secret_password(self) -> None:+ field = next(f for f in self.source.get_source_config.fields if f.name == "app_id")+ assert isinstance(field, SourceFieldInputConfig)+ assert field.type == SourceFieldInputConfigType.PASSWORD+ assert field.secret is True+ assert field.required is True++ @pytest.mark.parametrize("field_name", ["base_currency", "start_date"])+ def test_optional_fields_are_not_required(self, field_name: str) -> None:+ field = next(f for f in self.source.get_source_config.fields if f.name == field_name)+ assert isinstance(field, SourceFieldInputConfig)+ assert field.required is False+ assert field.secret is False++ def test_lists_tables_without_credentials(self) -> None:+ # Static endpoint catalog with no I/O — safe to surface in public docs.+ assert self.source.lists_tables_without_credentials is True++ @pytest.mark.parametrize(+ "observed_error",+ [+ "401 Client Error: Unauthorized for url: https://openexchangerates.org/api/latest.json",+ "403 Client Error: Forbidden for url: https://openexchangerates.org/api/usage.json",+ "429 Client Error: Too Many Requests for url: https://openexchangerates.org/api/latest.json?base=EUR",+ ],+ )+ def test_non_retryable_errors_match_auth_and_plan_failures(self, observed_error: str) -> None:+ assert any(key in observed_error for key in self.source.get_non_retryable_errors())++ @pytest.mark.parametrize(+ "other_error",+ [+ "500 Server Error for url: https://openexchangerates.org/api/historical/2024-01-01.json",+ "503 Server Error for url: https://openexchangerates.org/api/latest.json",+ ],+ )+ def test_non_retryable_errors_does_not_match_transient(self, other_error: str) -> None:+ assert not any(key in other_error for key in self.source.get_non_retryable_errors())++ def test_get_schemas_covers_all_endpoints(self) -> None:+ schemas = self.source.get_schemas(self.config, self.team_id)+ assert {schema.name for schema in schemas} == set(ENDPOINTS)++ def test_only_historical_supports_incremental(self) -> None:+ by_name = {schema.name: schema for schema in self.source.get_schemas(self.config, self.team_id)}+ # Only /historical selects a single value date server-side, so only new days are fetched.+ assert by_name["historical"].supports_incremental is True+ assert [f["field"] for f in by_name["historical"].incremental_fields] == ["date"]+ assert by_name["currencies"].supports_incremental is False+ assert by_name["latest"].supports_incremental is False+ assert by_name["usage"].supports_incremental is False++ def test_all_endpoints_sync_by_default(self) -> None:+ by_name = {schema.name: schema for schema in self.source.get_schemas(self.config, self.team_id)}+ assert all(schema.should_sync_default for schema in by_name.values())++ def test_get_schemas_filtered_by_names(self) -> None:+ schemas = self.source.get_schemas(self.config, self.team_id, names=["latest"])+ assert len(schemas) == 1+ assert schemas[0].name == "latest"++ def test_get_schemas_filtered_unknown_name_returns_empty(self) -> None:+ assert self.source.get_schemas(self.config, self.team_id, names=["nope"]) == []++ @pytest.mark.parametrize(+ "mock_return, expected_valid, expected_message",+ [+ (True, True, None),+ (+ False,+ False,+ "Unable to verify your Open Exchange Rates App ID. Check that the App ID is correct and that openexchangerates.org is reachable.",+ ),+ ],+ )+ @mock.patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.open_exchange_rates.source.validate_open_exchange_rates_credentials"+ )+ def test_validate_credentials(+ self, mock_validate: mock.MagicMock, mock_return: bool, expected_valid: bool, expected_message: str | None+ ) -> None:+ mock_validate.return_value = mock_return++ is_valid, error_message = self.source.validate_credentials(self.config, self.team_id)++ assert is_valid is expected_valid+ assert error_message == expected_message+ mock_validate.assert_called_once_with("oxr-test")++ def test_get_resumable_source_manager_binds_resume_config(self) -> None:+ manager = self.source.get_resumable_source_manager(mock.MagicMock())+ assert isinstance(manager, ResumableSourceManager)+ assert manager._data_class is OpenExchangeRatesResumeConfig++ @mock.patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.open_exchange_rates.source.open_exchange_rates_source"+ )+ def test_source_for_pipeline_plumbs_arguments(self, mock_source: mock.MagicMock) -> None:+ inputs = mock.MagicMock()+ inputs.schema_name = "historical"+ inputs.should_use_incremental_field = True+ inputs.db_incremental_field_last_value = "2024-01-01"+ manager = mock.MagicMock()++ self.source.source_for_pipeline(self.config, manager, inputs)++ mock_source.assert_called_once()+ kwargs = mock_source.call_args.kwargs+ assert kwargs["app_id"] == "oxr-test"+ assert kwargs["endpoint"] == "historical"+ assert kwargs["base_currency"] == "USD"+ assert kwargs["resumable_source_manager"] is manager+ assert kwargs["should_use_incremental_field"] is True+ assert kwargs["db_incremental_field_last_value"] == "2024-01-01"++ @mock.patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.open_exchange_rates.source.open_exchange_rates_source"+ )+ def test_source_for_pipeline_drops_watermark_when_not_incremental(self, mock_source: mock.MagicMock) -> None:+ inputs = mock.MagicMock()+ inputs.schema_name = "latest"+ inputs.should_use_incremental_field = False+ inputs.db_incremental_field_last_value = "2024-01-01"++ self.source.source_for_pipeline(self.config, mock.MagicMock(), inputs)++ # A non-incremental sync must not pass a stale watermark down to the transport.+ assert mock_source.call_args.kwargs["db_incremental_field_last_value"] is None++ def test_canonical_descriptions_cover_all_endpoints(self) -> None:+ descriptions = self.source.get_canonical_descriptions()+ assert set(descriptions) == set(ENDPOINTS)+ assert "rate" in descriptions["historical"]["columns"]