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 exchange_rates_api import source (#66740)

Tom Owersadd3261225b7
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 e3fa23acdddb..099bc5587e55 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
@@ -135,6 +135,7 @@ the row lists both.
| eventbrite | HTTP | requests | ✅ |
| eventee | HTTP | requests | ✅ |
| everhour | HTTP | requests | ✅ |
+| exchange_rates_api | HTTP | requests | ✅ |
| factorial | HTTP | requests + `rest_source.RESTClient` | ✅ |
| fillout | HTTP | requests + `rest_source.RESTClient` | ✅ |
| financial_modelling | HTTP | requests | ✅ |
@@ -387,7 +388,6 @@ doesn't conflict with concurrent PRs.
- employment_hero
- encharge
- eventzilla
-- exchange_rates_api
- expensify
- ezofficeinventory
- facebook_pages
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/exchange_rates_api/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/exchange_rates_api/canonical_descriptions.py
new file mode 100644
index 000000000000..7188cfbd5e00
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/exchange_rates_api/canonical_descriptions.py
@@ -0,0 +1,37 @@
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (
+ CanonicalDescriptions,
+)
+
+DOCS_URL = "https://exchangeratesapi.io/documentation/"
+
+CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
+ "symbols": {
+ "description": "Reference catalog of every currency the Exchange Rates API supports, as one row per currency.",
+ "docs_url": DOCS_URL,
+ "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": DOCS_URL,
+ "columns": {
+ "base": "Base currency the rates are quoted against (EUR 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 (YYYY-MM-DD).",
+ "timestamp": "Unix timestamp of when the rates were last updated.",
+ },
+ },
+ "timeseries": {
+ "description": "Daily historical exchange rates per currency over a requested date range, normalized to one row per (base, currency, date). Requests are chunked into 365-day windows.",
+ "docs_url": DOCS_URL,
+ "columns": {
+ "base": "Base currency the rates are quoted against (EUR 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).",
+ },
+ },
+}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/exchange_rates_api/exchange_rates_api.py b/products/warehouse_sources/backend/temporal/data_imports/sources/exchange_rates_api/exchange_rates_api.py
new file mode 100644
index 000000000000..641436f89162
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/exchange_rates_api/exchange_rates_api.py
@@ -0,0 +1,283 @@
+import dataclasses
+from collections.abc import Iterator
+from datetime import date, datetime, timedelta
+from typing import Any, Optional
+from urllib.parse import urlencode, urlsplit, urlunsplit
+
+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.exchange_rates_api.settings import (
+ EXCHANGE_RATES_API_ENDPOINTS,
+)
+
+BASE_URL = "https://api.exchangeratesapi.io/v1"
+DEFAULT_BASE_CURRENCY = "EUR"
+REQUEST_TIMEOUT_SECONDS = 60
+MAX_RETRY_ATTEMPTS = 6
+
+# The /timeseries endpoint rejects ranges longer than 365 days, so multi-year backfills are chunked
+# into windows of at most this many distinct days (inclusive).
+MAX_RANGE_DAYS = 365
+# On the first sync of an incremental timeseries (no watermark) and when no start date is configured,
+# pull this far back — one full window.
+DEFAULT_LOOKBACK_DAYS = 365
+
+
+class ExchangeRatesApiError(Exception):
+ """Raised when the API returns a functional error (HTTP 200 with success=false)."""
+
+ pass
+
+
+class ExchangeRatesApiRetryableError(Exception):
+ pass
+
+
+class ExchangeRatesApiResumeConfig:
+ # ISO date (YYYY-MM-DD) of the next timeseries window's start. Lets a chunked multi-year backfill
+ # resume mid-sync after a heartbeat timeout instead of restarting from the first window. Unused
+ # for the single-response symbols/latest endpoints.
+ next_start_date: str | None = None
+
+
+def _build_url(path: str, params: dict[str, Any]) -> str:
+ return f"{BASE_URL}/{path}?{urlencode(params)}"
+
+
+def _scrub_url(url: str | None) -> str:
+ # The access_key rides in the query string, so strip the query before the URL reaches any error
+ # message or log line — otherwise a non-2xx response would leak the credential into job errors.
+ # The base host stays intact so `get_non_retryable_errors()` can still match on it.
+ if not url:
+ return BASE_URL
+ parts = urlsplit(url)
+ return urlunsplit((parts.scheme, parts.netloc, parts.path, "", ""))
+
+
+def _raise_on_functional_error(data: Any, url: str) -> None:
+ """apilayer returns HTTP 200 with ``{"success": false, "error": {...}}`` for functional errors
+ (e.g. an invalid date, or a base currency the plan doesn't allow). Surface those as failures
+ instead of silently yielding nothing."""
+ if isinstance(data, dict) and data.get("success") is False:
+ error = data.get("error") or {}
+ code = error.get("code") or error.get("type") or "unknown_error"
+ message = error.get("message") or error.get("info") or "Unknown error"
+ raise ExchangeRatesApiError(f"Exchange Rates API error ({code}): {message} url={_scrub_url(url)}")
+
+
+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)
+
+ if response.status_code == 429 or response.status_code >= 500:
+ raise ExchangeRatesApiRetryableError(
+ f"Exchange Rates API error (retryable): status={response.status_code}, url={_scrub_url(url)}"
+ )
+
+ if not response.ok:
+ logger.error(
+ f"Exchange Rates API error: status={response.status_code}, body={response.text}, url={_scrub_url(url)}"
+ )
+ # Raise with the access_key scrubbed from the URL rather than calling raise_for_status(), whose
+ # message embeds the full credential-bearing URL.
+ raise requests.HTTPError(
+ f"{response.status_code} Client Error: {response.reason} for url: {_scrub_url(response.url)}",
+ response=response,
+ )
+
+ data = response.json()
+ _raise_on_functional_error(data, url)
+ return data
+
+
+def validate_credentials(access_key: str) -> bool:
+ """Confirm the key is genuine with the cheapest call (/symbols). A valid key returns 200; an
+ invalid or missing one returns 401."""
+ try:
+ session = make_tracked_session(redact_values=(access_key,) if access_key else ())
+ response = session.get(_build_url("symbols", {"access_key": access_key}), timeout=10)
+ return response.status_code == 200
+ except Exception:
+ return False
+
+
+def _iter_symbols(data: dict[str, Any]) -> list[dict[str, Any]]:
+ symbols = data.get("symbols") or {}
+ return [{"code": code, "name": name} for code, name in symbols.items()]
+
+
+def _iter_latest(data: dict[str, Any]) -> list[dict[str, Any]]:
+ # base and date are part of the composite primary key — fail fast rather than write None rows.
+ base = data["base"]
+ value_date = data["date"]
+ 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_timeseries(data: dict[str, Any]) -> list[dict[str, Any]]:
+ # base is part of the composite primary key — fail fast rather than write None rows.
+ base = data["base"]
+ rates_by_date = data.get("rates") or {}
+ rows: list[dict[str, Any]] = []
+ # Sort by date so rows arrive in ascending order, matching sort_mode="asc" and keeping the
+ # incremental watermark monotonic.
+ for value_date in sorted(rates_by_date):
+ for currency, rate in rates_by_date[value_date].items():
+ rows.append({"base": base, "currency": currency, "rate": rate, "date": value_date})
+ return rows
+
+
+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_windows(start: date, end: date, max_days: int) -> list[tuple[date, date]]:
+ windows: list[tuple[date, date]] = []
+ current = start
+ while current <= end:
+ window_end = min(current + timedelta(days=max_days - 1), end)
+ windows.append((current, window_end))
+ current = window_end + timedelta(days=1)
+ return windows
+
+
+def _resolve_timeseries_start(
+ should_use_incremental_field: bool,
+ db_incremental_field_last_value: Any,
+ configured_start_date: str | None,
+) -> 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 datetime.now().date() - timedelta(days=DEFAULT_LOOKBACK_DAYS)
+
+
+def get_rows(
+ access_key: str,
+ endpoint: str,
+ base_currency: str,
+ start_date: str | None,
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[ExchangeRatesApiResumeConfig],
+ should_use_incremental_field: bool = False,
+ db_incremental_field_last_value: Any = None,
+) -> Iterator[list[dict[str, Any]]]:
+ session = make_tracked_session(redact_values=(access_key,) if access_key else ())
+ base = base_currency or DEFAULT_BASE_CURRENCY
+ common_params: dict[str, Any] = {"access_key": access_key}
+
+ @retry(
+ retry=retry_if_exception_type((ExchangeRatesApiRetryableError, 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 == "symbols":
+ rows = _iter_symbols(fetch("symbols", common_params))
+ if rows:
+ yield rows
+ return
+
+ if endpoint == "latest":
+ rows = _iter_latest(fetch("latest", {**common_params, "base": base}))
+ if rows:
+ yield rows
+ return
+
+ if endpoint == "timeseries":
+ end = datetime.now().date()
+ start = _resolve_timeseries_start(should_use_incremental_field, db_incremental_field_last_value, start_date)
+ windows = _date_windows(start, end, MAX_RANGE_DAYS)
+
+ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None
+ if resume is not None and resume.next_start_date:
+ windows = [w for w in windows if w[0].isoformat() >= resume.next_start_date]
+ logger.debug(f"Exchange Rates API: resuming timeseries from {resume.next_start_date}")
+
+ for index, (window_start, window_end) in enumerate(windows):
+ data = fetch(
+ "timeseries",
+ {
+ **common_params,
+ "base": base,
+ "start_date": window_start.isoformat(),
+ "end_date": window_end.isoformat(),
+ },
+ )
+ rows = _iter_timeseries(data)
+ if rows:
+ yield rows
+
+ # Save AFTER yielding so a crash re-yields the last window rather than skipping it (merge
+ # dedupes on the composite primary key).
+ if index + 1 < len(windows):
+ resumable_source_manager.save_state(
+ ExchangeRatesApiResumeConfig(next_start_date=windows[index + 1][0].isoformat())
+ )
+ return
+
+ raise ValueError(f"Unknown Exchange Rates API endpoint: {endpoint}")
+
+
+def exchange_rates_api_source(
+ access_key: str,
+ endpoint: str,
+ base_currency: str,
+ start_date: str | None,
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[ExchangeRatesApiResumeConfig],
+ should_use_incremental_field: bool = False,
+ db_incremental_field_last_value: Optional[Any] = None,
+) -> SourceResponse:
+ config = EXCHANGE_RATES_API_ENDPOINTS[endpoint]
+
+ return SourceResponse(
+ name=endpoint,
+ items=lambda: get_rows(
+ access_key=access_key,
+ 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/exchange_rates_api/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/exchange_rates_api/settings.py
new file mode 100644
index 000000000000..f4deb8f7d2e3
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/exchange_rates_api/settings.py
@@ -0,0 +1,73 @@
+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 ExchangeRatesApiEndpointConfig:
+ 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 the `timeseries` endpoint, which exposes a genuine server-side `start_date` filter.
+ 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,
+}
+
+
+EXCHANGE_RATES_API_ENDPOINTS: dict[str, ExchangeRatesApiEndpointConfig] = {
+ # /symbols — reference catalog of every supported currency as {code, name} rows. One response.
+ "symbols": ExchangeRatesApiEndpointConfig(
+ name="symbols",
+ primary_keys=["code"],
+ description="All currencies the API supports, as {code, name} rows. Full refresh only.",
+ ),
+ # /latest — 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": ExchangeRatesApiEndpointConfig(
+ name="latest",
+ primary_keys=["base", "currency", "date"],
+ description="Latest exchange rate per currency against the base currency. Full refresh only.",
+ ),
+ # /timeseries — daily historical rates over a date range, normalized to one row per
+ # (base, currency, date). The endpoint requires start_date/end_date and caps the range at 365
+ # days, so backfills are chunked into ≤365-day windows. start_date is a real server-side filter,
+ # so this endpoint supports incremental sync keyed on the value date.
+ "timeseries": ExchangeRatesApiEndpointConfig(
+ name="timeseries",
+ primary_keys=["base", "currency", "date"],
+ incremental_fields=[_DATE_INCREMENTAL_FIELD],
+ supports_incremental=True,
+ partition_keys=["date"],
+ partition_mode="datetime",
+ partition_format="month",
+ # Opt-in: timeseries can be a large multi-year backfill and is not available on every plan,
+ # so leave it off by default to avoid surprising free-tier request usage.
+ should_sync_default=False,
+ description="Daily historical rates per currency over a date range (max 365 days per request, chunked). Supports incremental sync on the value date.",
+ ),
+}
+
+ENDPOINTS = tuple(EXCHANGE_RATES_API_ENDPOINTS.keys())
+
+INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {
+ name: config.incremental_fields for name, config in EXCHANGE_RATES_API_ENDPOINTS.items()
+}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/exchange_rates_api/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/exchange_rates_api/source.py
index 8b3e00f6eba9..b3b636c74877 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/exchange_rates_api/source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/exchange_rates_api/source.py
@@ -1,13 +1,33 @@
-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.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 SourceSchema
+from products.warehouse_sources.backend.temporal.data_imports.sources.exchange_rates_api.exchange_rates_api import (
+ ExchangeRatesApiResumeConfig,
+ exchange_rates_api_source,
+ validate_credentials as validate_exchange_rates_api_credentials,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.exchange_rates_api.settings import (
+ EXCHANGE_RATES_API_ENDPOINTS,
+)
from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs import (
ExchangeRatesApiSourceConfig,
)
@@ -15,7 +35,9 @@ from products.warehouse_sources.backend.types import ExternalDataSourceType
@SourceRegistry.register
-class ExchangeRatesApiSource(SimpleSource[ExchangeRatesApiSourceConfig]):
+class ExchangeRatesApiSource(ResumableSource[ExchangeRatesApiSourceConfig, ExchangeRatesApiResumeConfig]):
+ lists_tables_without_credentials = True # static endpoint catalog — safe for public docs
+
@property
def source_type(self) -> ExternalDataSourceType:
return ExternalDataSourceType.EXCHANGERATESAPI
@@ -26,7 +48,122 @@ class ExchangeRatesApiSource(SimpleSource[ExchangeRatesApiSourceConfig]):
name=SchemaExternalDataSourceType.EXCHANGE_RATES_API,
category=DataWarehouseSourceCategory.FINANCE___ACCOUNTING,
label="Exchange Rates API",
- iconPath="/static/services/exchange_rates_api.png",
- fields=cast(list[FieldType], []),
+ releaseStatus=ReleaseStatus.ALPHA,
unreleasedSource=True,
+ caption="""Enter your Exchange Rates API access key to pull foreign-exchange reference rates into the PostHog Data warehouse.
+
+Create a key in your [exchangeratesapi.io dashboard](https://exchangeratesapi.io/dashboard).
+
+The free plan is restricted to the `EUR` base currency — a custom base currency requires a paid plan. The `timeseries` table is capped at a 365-day range per request (backfills are chunked automatically) and may not be available on every plan.""",
+ iconPath="/static/services/exchange_rates_api.png",
+ docsUrl="https://posthog.com/docs/cdp/sources/exchange-rates-api",
+ keywords=["exchangeratesapi", "forex", "currency", "fx"],
+ fields=cast(
+ list[FieldType],
+ [
+ SourceFieldInputConfig(
+ name="access_key",
+ label="Access key",
+ type=SourceFieldInputConfigType.PASSWORD,
+ required=True,
+ placeholder="",
+ secret=True,
+ ),
+ SourceFieldInputConfig(
+ name="base_currency",
+ label="Base currency",
+ type=SourceFieldInputConfigType.TEXT,
+ required=False,
+ placeholder="EUR",
+ secret=False,
+ ),
+ SourceFieldInputConfig(
+ name="start_date",
+ label="Start date (timeseries 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.exchange_rates_api.canonical_descriptions import (
+ CANONICAL_DESCRIPTIONS,
+ )
+
+ return CANONICAL_DESCRIPTIONS
+
+ def get_non_retryable_errors(self) -> dict[str, str | None]:
+ return {
+ # An invalid, missing, or revoked access key surfaces as a 401 when `_request` calls
+ # `raise_for_status()`. Retrying can never fix a credential problem, so stop the sync.
+ # Match the stable status text and base host, not the per-request path/query.
+ "401 Client Error: Unauthorized for url: https://api.exchangeratesapi.io": "Your Exchange Rates API access key is invalid or has been revoked. Create a new key in your exchangeratesapi.io dashboard, then reconnect.",
+ "403 Client Error: Forbidden for url: https://api.exchangeratesapi.io": "Your Exchange Rates API plan does not allow this request (for example a non-EUR base currency or the timeseries endpoint on the free plan). Upgrade your plan or adjust the source settings, then reconnect.",
+ }
+
+ def get_schemas(
+ self,
+ config: ExchangeRatesApiSourceConfig,
+ 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 EXCHANGE_RATES_API_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: ExchangeRatesApiSourceConfig, team_id: int, schema_name: Optional[str] = None
+ ) -> tuple[bool, str | None]:
+ if validate_exchange_rates_api_credentials(config.access_key):
+ return True, None
+
+ # The probe also returns False on transient network/timeout errors, so don't claim the key is
+ # definitively invalid — point at both possibilities.
+ return (
+ False,
+ "Unable to verify your Exchange Rates API access key. Check that the key is correct and that exchangeratesapi.io is reachable.",
+ )
+
+ def get_resumable_source_manager(
+ self, inputs: SourceInputs
+ ) -> ResumableSourceManager[ExchangeRatesApiResumeConfig]:
+ return ResumableSourceManager[ExchangeRatesApiResumeConfig](inputs, ExchangeRatesApiResumeConfig)
+
+ def source_for_pipeline(
+ self,
+ config: ExchangeRatesApiSourceConfig,
+ resumable_source_manager: ResumableSourceManager[ExchangeRatesApiResumeConfig],
+ inputs: SourceInputs,
+ ) -> SourceResponse:
+ return exchange_rates_api_source(
+ access_key=config.access_key,
+ 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/exchange_rates_api/tests/test_exchange_rates_api.py b/products/warehouse_sources/backend/temporal/data_imports/sources/exchange_rates_api/tests/test_exchange_rates_api.py
new file mode 100644
index 000000000000..521be5da68a0
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/exchange_rates_api/tests/test_exchange_rates_api.py
@@ -0,0 +1,352 @@
+from datetime import date
+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.exchange_rates_api import exchange_rates_api
+from products.warehouse_sources.backend.temporal.data_imports.sources.exchange_rates_api.exchange_rates_api import (
+ BASE_URL,
+ DEFAULT_BASE_CURRENCY,
+ MAX_RANGE_DAYS,
+ ExchangeRatesApiError,
+ ExchangeRatesApiResumeConfig,
+ ExchangeRatesApiRetryableError,
+ _build_url,
+ _date_windows,
+ _iter_latest,
+ _iter_symbols,
+ _iter_timeseries,
+ _raise_on_functional_error,
+ _resolve_timeseries_start,
+ _to_date,
+ exchange_rates_api_source,
+ get_rows,
+ validate_credentials,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.exchange_rates_api.settings import (
+ EXCHANGE_RATES_API_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
+ # Mirrors requests.Response.url; the session sets it to the requested URL.
+ 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
+
+ def raise_for_status(self) -> None:
+ if not self.ok:
+ raise requests.HTTPError(f"{self.status_code} Client Error", response=self) # type: ignore[arg-type]
+
+
+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: ExchangeRatesApiResumeConfig | 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:
+ url = _build_url("timeseries", {"access_key": "k", "start_date": "2024-01-01", "end_date": "2024-01-02"})
+ assert url == f"{BASE_URL}/timeseries?access_key=k&start_date=2024-01-01&end_date=2024-01-02"
+
+
+class TestRaiseOnFunctionalError:
+ def test_raises_on_success_false(self) -> None:
+ body = {"success": False, "error": {"code": "invalid_base_currency", "message": "bad base"}}
+ with pytest.raises(ExchangeRatesApiError) as exc:
+ _raise_on_functional_error(body, "http://x")
+ assert "invalid_base_currency" in str(exc.value)
+
+ @parameterized.expand(
+ [
+ ("success_true", {"success": True, "rates": {}}),
+ ("no_success_key", {"symbols": {}}),
+ ("not_a_dict", ["a", "b"]),
+ ]
+ )
+ def test_does_not_raise_on_valid_bodies(self, _name: str, body: Any) -> None:
+ _raise_on_functional_error(body, "http://x")
+
+
+class TestRequest:
+ @parameterized.expand([(429,), (500,), (503,)])
+ def test_retryable_statuses_raise_retryable_error(self, status: int) -> None:
+ session = _FakeSession([_FakeResponse(status_code=status, json_data=None)])
+ with pytest.raises(ExchangeRatesApiRetryableError):
+ exchange_rates_api._request(session, "symbols", {}, mock.MagicMock()) # type: ignore[arg-type]
+
+ def test_client_error_raises_http_error(self) -> None:
+ session = _FakeSession([_FakeResponse(status_code=401, json_data=None, text="unauthorized")])
+ with pytest.raises(requests.HTTPError):
+ exchange_rates_api._request(session, "symbols", {}, mock.MagicMock()) # type: ignore[arg-type]
+
+ def test_client_error_does_not_leak_access_key(self) -> None:
+ # The access_key rides in the query string; a 4xx must never surface it in the raised error.
+ session = _FakeSession([_FakeResponse(status_code=401, reason="Unauthorized")])
+ logger = mock.MagicMock()
+ with pytest.raises(requests.HTTPError) as exc:
+ exchange_rates_api._request(session, "symbols", {"access_key": "SECRET_KEY"}, logger) # type: ignore[arg-type]
+ assert "SECRET_KEY" not in str(exc.value)
+ assert "SECRET_KEY" not in str(logger.error.call_args)
+
+ def test_functional_error_raises_after_200(self) -> None:
+ body = {"success": False, "error": {"code": "base_currency_access_restricted", "message": "upgrade"}}
+ session = _FakeSession([_FakeResponse(status_code=200, json_data=body)])
+ with pytest.raises(ExchangeRatesApiError):
+ exchange_rates_api._request(session, "latest", {}, mock.MagicMock()) # type: ignore[arg-type]
+
+ def test_success_returns_parsed_body(self) -> None:
+ body = {"success": True, "symbols": {"USD": "US Dollar"}}
+ session = _FakeSession([_FakeResponse(status_code=200, json_data=body)])
+ assert exchange_rates_api._request(session, "symbols", {}, 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.exchange_rates_api.exchange_rates_api.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.exchange_rates_api.exchange_rates_api.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.exchange_rates_api.exchange_rates_api.make_tracked_session"
+ )
+ def test_probes_symbols_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]
+ assert url.startswith(f"{BASE_URL}/symbols")
+ # The key rides in a query param the sampler can't predict, so it must be redacted by value.
+ assert mock_session.call_args.kwargs["redact_values"] == ("secret",)
+
+
+class TestNormalization:
+ def test_iter_symbols(self) -> None:
+ data = {"symbols": {"USD": "US Dollar", "GBP": "Pound Sterling"}}
+ assert _iter_symbols(data) == [
+ {"code": "USD", "name": "US Dollar"},
+ {"code": "GBP", "name": "Pound Sterling"},
+ ]
+
+ def test_iter_latest(self) -> None:
+ data = {"base": "EUR", "date": "2024-01-02", "timestamp": 1704153600, "rates": {"USD": 1.1, "GBP": 0.86}}
+ assert _iter_latest(data) == [
+ {"base": "EUR", "currency": "USD", "rate": 1.1, "date": "2024-01-02", "timestamp": 1704153600},
+ {"base": "EUR", "currency": "GBP", "rate": 0.86, "date": "2024-01-02", "timestamp": 1704153600},
+ ]
+
+ def test_iter_timeseries_sorts_by_date(self) -> None:
+ data = {
+ "base": "EUR",
+ "rates": {"2024-01-02": {"USD": 1.2}, "2024-01-01": {"USD": 1.1}},
+ }
+ rows = _iter_timeseries(data)
+ # Rows must arrive ascending by date to keep the incremental watermark monotonic.
+ assert [r["date"] for r in rows] == ["2024-01-01", "2024-01-02"]
+ assert rows[0] == {"base": "EUR", "currency": "USD", "rate": 1.1, "date": "2024-01-01"}
+
+
+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 TestDateWindows:
+ def test_single_window_when_within_max_range(self) -> None:
+ windows = _date_windows(date(2024, 1, 1), date(2024, 1, 10), MAX_RANGE_DAYS)
+ assert windows == [(date(2024, 1, 1), date(2024, 1, 10))]
+
+ def test_chunks_multi_year_backfill(self) -> None:
+ windows = _date_windows(date(2020, 1, 1), date(2022, 1, 1), MAX_RANGE_DAYS)
+ # Each window spans at most 365 distinct days and they tile the range without gaps/overlap.
+ assert len(windows) == 3
+ assert windows[0][0] == date(2020, 1, 1)
+ assert windows[-1][1] == date(2022, 1, 1)
+ for start, end in windows:
+ assert (end - start).days <= MAX_RANGE_DAYS - 1
+ for (_, prev_end), (next_start, _) in zip(windows, windows[1:]):
+ assert (next_start - prev_end).days == 1
+
+ def test_empty_when_start_after_end(self) -> None:
+ assert _date_windows(date(2024, 2, 1), date(2024, 1, 1), MAX_RANGE_DAYS) == []
+
+
+class TestResolveTimeseriesStart:
+ def test_uses_watermark_when_incremental(self) -> None:
+ assert _resolve_timeseries_start(True, "2024-05-05", "2020-01-01") == date(2024, 5, 5)
+
+ def test_uses_configured_start_when_no_watermark(self) -> None:
+ assert _resolve_timeseries_start(True, None, "2020-01-01") == date(2020, 1, 1)
+
+ def test_uses_configured_start_when_not_incremental(self) -> None:
+ assert _resolve_timeseries_start(False, "2024-05-05", "2020-01-01") == date(2020, 1, 1)
+
+
+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.exchange_rates_api.exchange_rates_api.make_tracked_session",
+ return_value=session,
+ ):
+ return list(get_rows("key", endpoint, "EUR", None, mock.MagicMock(), manager, **kwargs)), session
+
+ def test_symbols_yields_once(self) -> None:
+ body = {"success": True, "symbols": {"USD": "US Dollar"}}
+ batches, _ = self._run("symbols", [_FakeResponse(json_data=body)], _manager())
+ assert batches == [[{"code": "USD", "name": "US Dollar"}]]
+
+ def test_symbols_empty_yields_nothing(self) -> None:
+ batches, _ = self._run("symbols", [_FakeResponse(json_data={"success": True, "symbols": {}})], _manager())
+ assert batches == []
+
+ def test_latest_yields_once_and_sends_base(self) -> None:
+ body = {"success": True, "base": "EUR", "date": "2024-01-02", "timestamp": 1, "rates": {"USD": 1.1}}
+ batches, session = self._run("latest", [_FakeResponse(json_data=body)], _manager())
+ assert batches == [[{"base": "EUR", "currency": "USD", "rate": 1.1, "date": "2024-01-02", "timestamp": 1}]]
+ assert "base=EUR" in session.requested_urls[0]
+
+ def test_timeseries_fetches_each_window_and_saves_state_between(self) -> None:
+ manager = _manager()
+ windows = [(date(2020, 1, 1), date(2020, 12, 30)), (date(2020, 12, 31), date(2021, 1, 5))]
+ body1 = {"success": True, "base": "EUR", "rates": {"2020-01-01": {"USD": 1.1}}}
+ body2 = {"success": True, "base": "EUR", "rates": {"2020-12-31": {"USD": 1.2}}}
+ session = _FakeSession([_FakeResponse(json_data=body1), _FakeResponse(json_data=body2)])
+ with (
+ mock.patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.exchange_rates_api.exchange_rates_api.make_tracked_session",
+ return_value=session,
+ ),
+ mock.patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.exchange_rates_api.exchange_rates_api._date_windows",
+ return_value=windows,
+ ),
+ ):
+ batches = list(
+ get_rows(
+ "key",
+ "timeseries",
+ "EUR",
+ "2020-01-01",
+ mock.MagicMock(),
+ manager,
+ should_use_incremental_field=True,
+ db_incremental_field_last_value="2020-01-01",
+ )
+ )
+ assert [b[0]["date"] for b in batches] == ["2020-01-01", "2020-12-31"]
+ # State is saved AFTER the first window yields (pointing at the next window), never after the last.
+ manager.save_state.assert_called_once_with(ExchangeRatesApiResumeConfig(next_start_date="2020-12-31"))
+
+ def test_timeseries_resumes_from_saved_window(self) -> None:
+ manager = _manager(can_resume=True, state=ExchangeRatesApiResumeConfig(next_start_date="2020-12-31"))
+ windows = [(date(2020, 1, 1), date(2020, 12, 30)), (date(2020, 12, 31), date(2021, 1, 5))]
+ body2 = {"success": True, "base": "EUR", "rates": {"2020-12-31": {"USD": 1.2}}}
+ session = _FakeSession([_FakeResponse(json_data=body2)])
+ with (
+ mock.patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.exchange_rates_api.exchange_rates_api.make_tracked_session",
+ return_value=session,
+ ),
+ mock.patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.exchange_rates_api.exchange_rates_api._date_windows",
+ return_value=windows,
+ ),
+ ):
+ batches = list(get_rows("key", "timeseries", "EUR", "2020-01-01", mock.MagicMock(), manager))
+ # Only the window at/after the resume point is fetched.
+ assert len(session.requested_urls) == 1
+ assert "start_date=2020-12-31" in session.requested_urls[0]
+ assert [b[0]["date"] for b in batches] == ["2020-12-31"]
+
+ def test_unknown_endpoint_raises(self) -> None:
+ with pytest.raises(ValueError):
+ self._run("nope", [], _manager())
+
+
+class TestExchangeRatesApiSource:
+ @parameterized.expand(
+ [
+ ("symbols", ["code"]),
+ ("latest", ["base", "currency", "date"]),
+ ("timeseries", ["base", "currency", "date"]),
+ ]
+ )
+ def test_primary_keys_per_endpoint(self, endpoint: str, expected_keys: list[str]) -> None:
+ response = exchange_rates_api_source("key", endpoint, "EUR", None, mock.MagicMock(), mock.MagicMock())
+ assert response.name == endpoint
+ assert response.primary_keys == expected_keys
+ assert response.sort_mode == "asc"
+
+ def test_timeseries_partitions_on_stable_date(self) -> None:
+ response = exchange_rates_api_source("key", "timeseries", "EUR", None, mock.MagicMock(), mock.MagicMock())
+ assert response.partition_keys == ["date"]
+ assert response.partition_mode == "datetime"
+ assert response.partition_format == "month"
+
+ def test_snapshot_endpoints_are_not_partitioned(self) -> None:
+ for endpoint in ("symbols", "latest"):
+ response = exchange_rates_api_source("key", endpoint, "EUR", 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 EXCHANGE_RATES_API_ENDPOINTS:
+ response = exchange_rates_api_source("key", endpoint, "EUR", None, mock.MagicMock(), mock.MagicMock())
+ assert response.name == endpoint
+ assert response.primary_keys == EXCHANGE_RATES_API_ENDPOINTS[endpoint].primary_keys
+
+ def test_default_base_currency_is_eur(self) -> None:
+ assert DEFAULT_BASE_CURRENCY == "EUR"
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/exchange_rates_api/tests/test_exchange_rates_api_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/exchange_rates_api/tests/test_exchange_rates_api_source.py
new file mode 100644
index 000000000000..667b8d13fb35
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/exchange_rates_api/tests/test_exchange_rates_api_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.exchange_rates_api.exchange_rates_api import (
+ ExchangeRatesApiResumeConfig,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.exchange_rates_api.settings import ENDPOINTS
+from products.warehouse_sources.backend.temporal.data_imports.sources.exchange_rates_api.source import (
+ ExchangeRatesApiSource,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs import (
+ ExchangeRatesApiSourceConfig,
+)
+from products.warehouse_sources.backend.types import ExternalDataSourceType
+
+
+class TestExchangeRatesApiSource:
+ def setup_method(self) -> None:
+ self.source = ExchangeRatesApiSource()
+ self.team_id = 123
+ self.config = ExchangeRatesApiSourceConfig(access_key="era-test", base_currency="EUR", start_date=None)
+
+ def test_source_type(self) -> None:
+ assert self.source.source_type == ExternalDataSourceType.EXCHANGERATESAPI
+
+ def test_get_source_config(self) -> None:
+ config = self.source.get_source_config
+
+ assert config.name.value == "ExchangeRatesApi"
+ assert config.label == "Exchange Rates API"
+ 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/exchange-rates-api"
+ assert [f.name for f in config.fields] == ["access_key", "base_currency", "start_date"]
+
+ def test_access_key_field_is_secret_password(self) -> None:
+ field = next(f for f in self.source.get_source_config.fields if f.name == "access_key")
+ 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://api.exchangeratesapi.io/v1/symbols?access_key=x",
+ "403 Client Error: Forbidden for url: https://api.exchangeratesapi.io/v1/timeseries?access_key=x",
+ ],
+ )
+ 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",
+ [
+ "429 Client Error: Too Many Requests for url: https://api.exchangeratesapi.io/v1/latest",
+ "500 Server Error for url: https://api.exchangeratesapi.io/v1/timeseries",
+ ],
+ )
+ 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_timeseries_supports_incremental(self) -> None:
+ by_name = {schema.name: schema for schema in self.source.get_schemas(self.config, self.team_id)}
+ # Only /timeseries exposes a server-side start_date filter.
+ assert by_name["timeseries"].supports_incremental is True
+ assert [f["field"] for f in by_name["timeseries"].incremental_fields] == ["date"]
+ assert by_name["symbols"].supports_incremental is False
+ assert by_name["latest"].supports_incremental is False
+
+ def test_timeseries_off_by_default(self) -> None:
+ by_name = {schema.name: schema for schema in self.source.get_schemas(self.config, self.team_id)}
+ # Opt-in to avoid surprising free-tier request usage on a multi-year backfill.
+ assert by_name["timeseries"].should_sync_default is False
+ assert by_name["symbols"].should_sync_default is True
+
+ 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 Exchange Rates API access key. Check that the key is correct and that exchangeratesapi.io is reachable.",
+ ),
+ ],
+ )
+ @mock.patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.exchange_rates_api.source.validate_exchange_rates_api_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("era-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 ExchangeRatesApiResumeConfig
+
+ @mock.patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.exchange_rates_api.source.exchange_rates_api_source"
+ )
+ def test_source_for_pipeline_plumbs_arguments(self, mock_source: mock.MagicMock) -> None:
+ inputs = mock.MagicMock()
+ inputs.schema_name = "timeseries"
+ 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["access_key"] == "era-test"
+ assert kwargs["endpoint"] == "timeseries"
+ assert kwargs["base_currency"] == "EUR"
+ 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.exchange_rates_api.source.exchange_rates_api_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["timeseries"]["columns"]
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 be2d0ea25775..b45b55463b57 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
@@ -1096,7 +1096,9 @@ class EverhourSourceConfig(config.Config):
@config.config
class ExchangeRatesApiSourceConfig(config.Config):
- pass
+ access_key: str
+ base_currency: str | None = None
+ start_date: str | None = None
@config.config