: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 coin_api import source (#66748)
Tom Owers6a7e34093ee0
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.mdindex 4a1d53160b95..1597cdc3c292 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md@@ -76,6 +76,7 @@ the row lists both.| chargedesk | HTTP | requests | ✅ || checkout_com | HTTP | requests | ✅ || coda | HTTP | requests | ✅ |+| coin_api | HTTP | requests | ✅ || coingecko | HTTP | requests | ✅ || coinmarketcap | HTTP | requests + `rest_source.RESTClient` | ✅ || commercetools | HTTP | requests | ✅ |@@ -351,7 +352,6 @@ doesn't conflict with concurrent PRs.- coassemble- cockroachdb- codefresh-- coin_api- concord- configcat- constant_contactdiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/coin_api/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/coin_api/canonical_descriptions.pynew file mode 100644index 000000000000..7a59ed80a287--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/coin_api/canonical_descriptions.py@@ -0,0 +1,102 @@+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (+ CanonicalDescriptions,+)++# Descriptions sourced from the public CoinAPI v1 REST docs (https://docs.coinapi.io/market-data/rest-api).+# Partial coverage is fine — anything not described here falls back to LLM enrichment.+CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {+ "assets": {+ "description": "Every asset CoinAPI tracks (cryptocurrencies and fiat), with volume and price metadata.",+ "docs_url": "https://docs.coinapi.io/market-data/rest-api/metadata#list-all-assets-get",+ "columns": {+ "asset_id": "CoinAPI identifier of the asset (e.g. BTC, USD).",+ "name": "Display name of the asset.",+ "type_is_crypto": "1 if the asset is a cryptocurrency, 0 if it is fiat.",+ "data_quote_start": "First date CoinAPI has quote data for this asset.",+ "data_quote_end": "Last date CoinAPI has quote data for this asset.",+ "data_trade_start": "First date CoinAPI has trade data for this asset.",+ "data_trade_end": "Last date CoinAPI has trade data for this asset.",+ "data_symbols_count": "Number of symbols referencing this asset.",+ "volume_1hrs_usd": "Trading volume over the last hour, in USD.",+ "volume_1day_usd": "Trading volume over the last day, in USD.",+ "volume_1mth_usd": "Trading volume over the last month, in USD.",+ "price_usd": "Latest price of the asset in USD.",+ },+ },+ "exchanges": {+ "description": "Every exchange CoinAPI tracks, with coverage dates and volume metadata.",+ "docs_url": "https://docs.coinapi.io/market-data/rest-api/metadata#list-all-exchanges-get",+ "columns": {+ "exchange_id": "CoinAPI identifier of the exchange.",+ "website": "Exchange website URL.",+ "name": "Display name of the exchange.",+ "data_start": "First date CoinAPI has any data for this exchange.",+ "data_end": "Last date CoinAPI has any data for this exchange.",+ "data_quote_start": "First date CoinAPI has quote data for this exchange.",+ "data_quote_end": "Last date CoinAPI has quote data for this exchange.",+ "data_trade_start": "First date CoinAPI has trade data for this exchange.",+ "data_trade_end": "Last date CoinAPI has trade data for this exchange.",+ "data_symbols_count": "Number of symbols on this exchange.",+ "volume_1hrs_usd": "Trading volume over the last hour, in USD.",+ "volume_1day_usd": "Trading volume over the last day, in USD.",+ "volume_1mth_usd": "Trading volume over the last month, in USD.",+ },+ },+ "symbols": {+ "description": "Every symbol (market) CoinAPI tracks across all exchanges, with its component assets.",+ "docs_url": "https://docs.coinapi.io/market-data/rest-api/metadata#list-all-symbols-get",+ "columns": {+ "symbol_id": "CoinAPI identifier of the symbol (e.g. BITSTAMP_SPOT_BTC_USD).",+ "exchange_id": "Exchange this symbol trades on.",+ "symbol_type": "Type of the symbol: SPOT, FUTURES, OPTION, PERPETUAL, or INDEX.",+ "asset_id_base": "Base asset of the market.",+ "asset_id_quote": "Quote asset of the market.",+ "data_start": "First date CoinAPI has data for this symbol.",+ "data_end": "Last date CoinAPI has data for this symbol.",+ "volume_1hrs_usd": "Trading volume over the last hour, in USD.",+ "volume_1day_usd": "Trading volume over the last day, in USD.",+ "volume_1mth_usd": "Trading volume over the last month, in USD.",+ },+ },+ "exchange_rates": {+ "description": "Current exchange rate from the configured base asset to every other asset, one row per quote asset.",+ "docs_url": "https://docs.coinapi.io/market-data/rest-api/exchange-rates",+ "columns": {+ "asset_id_base": "Base asset of the rate (the source's configured base asset).",+ "asset_id_quote": "Quote asset of the rate.",+ "rate": "Exchange rate from the base asset to the quote asset.",+ "time": "Timestamp the rate was calculated.",+ },+ },+ "ohlcv_history": {+ "description": "Historical OHLCV (open/high/low/close/volume) candles for the configured symbol and period.",+ "docs_url": "https://docs.coinapi.io/market-data/rest-api/ohlcv#historical-data-get",+ "columns": {+ "symbol_id": "Symbol the candle belongs to (injected from the source configuration).",+ "period_id": "Aggregation period of the candle (injected from the source configuration), e.g. 1DAY.",+ "time_period_start": "Start time of the candle period (inclusive).",+ "time_period_end": "End time of the candle period (exclusive).",+ "time_open": "Timestamp of the first trade in the period.",+ "time_close": "Timestamp of the last trade in the period.",+ "price_open": "Price of the first trade in the period.",+ "price_high": "Highest trade price in the period.",+ "price_low": "Lowest trade price in the period.",+ "price_close": "Price of the last trade in the period.",+ "volume_traded": "Cumulative base-asset volume traded in the period.",+ "trades_count": "Number of trades in the period.",+ },+ },+ "trades_history": {+ "description": "Historical individual trades (executions) for the configured symbol.",+ "docs_url": "https://docs.coinapi.io/market-data/rest-api/trades#historical-data-get",+ "columns": {+ "symbol_id": "Symbol the trade belongs to (injected from the source configuration).",+ "uuid": "Globally-unique CoinAPI identifier of the trade.",+ "time_exchange": "Timestamp the exchange reported for the trade.",+ "time_coinapi": "Timestamp CoinAPI received the trade.",+ "price": "Execution price of the trade.",+ "size": "Base-asset quantity traded.",+ "taker_side": "Aggressor side of the trade: BUY, SELL, or UNKNOWN.",+ },+ },+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/coin_api/coin_api.py b/products/warehouse_sources/backend/temporal/data_imports/sources/coin_api/coin_api.pynew file mode 100644index 000000000000..687719ff1a11--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/coin_api/coin_api.py@@ -0,0 +1,269 @@+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.coin_api.settings import (+ COIN_API_ENDPOINTS,+ CoinApiEndpointConfig,+)+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++# CoinAPI serves all REST market data from a single host. The key rides in the `X-CoinAPI-Key` header.+#+# NOTE: response shapes, the ascending time ordering of the history endpoints, and that `time_start`+# filters server-side are taken from the public CoinAPI v1 docs and Airbyte's CoinAPI connector. CoinAPI+# no longer offers a free tier, so these could not be re-verified with a live curl smoke test — the+# pagination/merge logic is kept conservative (boundary re-fetch deduped on the primary key) to stay+# safe if the ordering ever differs from documented.+BASE_URL = "https://rest.coinapi.io"++# CoinAPI's time-series endpoints accept up to 100000 rows per request. We request a large page to+# keep the request (and billing — each 100 output items is one request) count down while staying+# comfortably under the limit.+PAGE_LIMIT = 10000+REQUEST_TIMEOUT_SECONDS = 60+MAX_RETRY_ATTEMPTS = 6+# How far back the first sync of a time-series table reaches when the user leaves `start_date` blank.+DEFAULT_LOOKBACK_DAYS = 365+++class CoinApiRetryableError(Exception):+ pass+++class CoinApiResumeConfig:+ # Next `time_start` (ISO 8601) to request for time-series endpoints. None for the+ # single-response reference/snapshot endpoints, which aren't resumable mid-table.+ time_start: str | None = None+++def _headers(api_key: str) -> dict[str, str]:+ headers = {"Accept": "application/json"}+ if api_key:+ headers["X-CoinAPI-Key"] = api_key+ return headers+++def _build_url(path: str, params: dict[str, Any]) -> str:+ if not params:+ return f"{BASE_URL}{path}"+ return f"{BASE_URL}{path}?{urlencode(params)}"+++def _format_time(value: Any) -> str:+ """Format an incremental cursor value as an ISO 8601 string CoinAPI accepts for `time_start`."""+ if isinstance(value, datetime):+ aware = value if value.tzinfo is not None else value.replace(tzinfo=UTC)+ return aware.astimezone(UTC).isoformat().replace("+00:00", "Z")+ if isinstance(value, date):+ return datetime.combine(value, datetime.min.time(), tzinfo=UTC).isoformat().replace("+00:00", "Z")+ return str(value)+++def _fetch(session: requests.Session, url: str, headers: dict[str, str], logger: FilteringBoundLogger) -> Any:+ response = session.get(url, headers=headers, timeout=REQUEST_TIMEOUT_SECONDS)++ # CoinAPI returns 429 when the daily credit or concurrency limit is hit, and may include a+ # Retry-After header. Both 429 and transient 5xx are safe to retry.+ if response.status_code == 429 or response.status_code >= 500:+ raise CoinApiRetryableError(f"CoinAPI error (retryable): status={response.status_code}, url={url}")++ if not response.ok:+ logger.error(f"CoinAPI error: status={response.status_code}, body={response.text}, url={url}")+ response.raise_for_status()++ return response.json()+++def validate_credentials(api_key: str) -> bool:+ """Confirm the key is genuine with one cheap request. A valid key returns 200; an invalid or+ malformed key returns 401."""+ url = _build_url("/v1/exchangerate/BTC/USD", {})+ try:+ session = make_tracked_session(redact_values=(api_key,) if api_key else ())+ response = session.get(url, headers=_headers(api_key), timeout=10)+ # A valid key with a plan that gates this endpoint returns 403 — the key itself is genuine,+ # so accept it at source-create and let per-table sync surface any real access problem.+ return response.status_code in (200, 403)+ except Exception:+ return False+++def _initial_time_start(+ should_use_incremental_field: bool,+ db_incremental_field_last_value: Any,+ start_date: str,+) -> str:+ if should_use_incremental_field and db_incremental_field_last_value:+ return _format_time(db_incremental_field_last_value)+ if start_date:+ return start_date+ return _format_time(datetime.now(UTC) - timedelta(days=DEFAULT_LOOKBACK_DAYS))+++def _get_timeseries_rows(+ config: CoinApiEndpointConfig,+ logger: FilteringBoundLogger,+ fetch: Any,+ symbol_id: str,+ period_id: str,+ incremental_field: str,+ initial_time_start: str,+ resumable_source_manager: ResumableSourceManager[CoinApiResumeConfig],+) -> Iterator[list[dict[str, Any]]]:+ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None+ time_start = resume.time_start if resume is not None and resume.time_start else initial_time_start+ if resume is not None and resume.time_start:+ logger.debug(f"CoinAPI: resuming {config.name} from time_start={time_start}")++ path = config.path.replace("{symbol_id}", symbol_id)++ while True:+ params: dict[str, Any] = {"time_start": time_start, "limit": PAGE_LIMIT}+ if config.needs_period:+ params["period_id"] = period_id++ data = fetch(_build_url(path, params))+ if not isinstance(data, list) or not data:+ break++ # OHLCV rows omit the symbol/period they belong to; injecting them keeps the primary key+ # columns present and the table self-describing.+ for row in data:+ row["symbol_id"] = symbol_id+ if config.needs_period:+ row["period_id"] = period_id++ yield data++ # A short page is the last page.+ if len(data) < PAGE_LIMIT:+ break++ next_time_start = _format_time(data[-1][incremental_field])+ # `time_start` is inclusive, so the boundary row is re-fetched and deduped on merge. If a full+ # page shares one timestamp (e.g. a microsecond burst of trades), advancing wouldn't progress —+ # stop rather than loop forever. ISO 8601 strings in CoinAPI's fixed format compare chronologically.+ if next_time_start <= time_start:+ logger.warning(+ f"CoinAPI: {config.name} page boundary did not advance past time_start={time_start}; stopping"+ )+ break++ time_start = next_time_start+ # Save AFTER yielding so a crash re-yields the last page (deduped on the primary key) rather+ # than skipping it.+ resumable_source_manager.save_state(CoinApiResumeConfig(time_start=time_start))+++def get_rows(+ api_key: str,+ endpoint: str,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[CoinApiResumeConfig],+ symbol_id: str = "",+ period_id: str = "1DAY",+ exchange_rate_base_asset: str = "USD",+ start_date: str = "",+ should_use_incremental_field: bool = False,+ db_incremental_field_last_value: Any = None,+ incremental_field: str | None = None,+) -> Iterator[list[dict[str, Any]]]:+ config = COIN_API_ENDPOINTS[endpoint]+ session = make_tracked_session(redact_values=(api_key,) if api_key else ())+ headers = _headers(api_key)++ @retry(+ retry=retry_if_exception_type((CoinApiRetryableError, requests.ReadTimeout, requests.ConnectionError)),+ stop=stop_after_attempt(MAX_RETRY_ATTEMPTS),+ wait=wait_exponential_jitter(initial=2, max=120),+ reraise=True,+ )+ def fetch(url: str) -> Any:+ return _fetch(session, url, headers, logger)++ if config.kind == "reference":+ data = fetch(_build_url(config.path, {}))+ if isinstance(data, list) and data:+ yield data+ return++ if config.kind == "exchange_rate":+ base = exchange_rate_base_asset or "USD"+ data = fetch(_build_url(config.path.replace("{base}", base), {}))+ rates = data.get("rates", []) if isinstance(data, dict) else []+ base_asset = data.get("asset_id_base", base) if isinstance(data, dict) else base+ rows = [{**rate, "asset_id_base": base_asset} for rate in rates]+ if rows:+ yield rows+ return++ # Time-series endpoint.+ if not symbol_id:+ raise ValueError(+ f"CoinAPI endpoint '{endpoint}' requires a symbol_id. Set the Symbol ID field on the source "+ f"(e.g. BITSTAMP_SPOT_BTC_USD) to sync this table."+ )++ cursor = incremental_field or config.incremental_fields[0]["field"]+ initial_time_start = _initial_time_start(should_use_incremental_field, db_incremental_field_last_value, start_date)++ yield from _get_timeseries_rows(+ config=config,+ logger=logger,+ fetch=fetch,+ symbol_id=symbol_id,+ period_id=period_id or "1DAY",+ incremental_field=cursor,+ initial_time_start=initial_time_start,+ resumable_source_manager=resumable_source_manager,+ )+++def coin_api_source(+ api_key: str,+ endpoint: str,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[CoinApiResumeConfig],+ symbol_id: str = "",+ period_id: str = "1DAY",+ exchange_rate_base_asset: str = "USD",+ start_date: str = "",+ should_use_incremental_field: bool = False,+ db_incremental_field_last_value: Optional[Any] = None,+ incremental_field: str | None = None,+) -> SourceResponse:+ config = COIN_API_ENDPOINTS[endpoint]++ return SourceResponse(+ name=endpoint,+ items=lambda: get_rows(+ api_key=api_key,+ endpoint=endpoint,+ logger=logger,+ resumable_source_manager=resumable_source_manager,+ symbol_id=symbol_id,+ period_id=period_id,+ exchange_rate_base_asset=exchange_rate_base_asset,+ start_date=start_date,+ should_use_incremental_field=should_use_incremental_field,+ db_incremental_field_last_value=db_incremental_field_last_value,+ incremental_field=incremental_field,+ ),+ primary_keys=config.primary_keys,+ partition_count=1 if config.partition_key else None,+ partition_size=1 if config.partition_key else None,+ partition_mode="datetime" if config.partition_key else None,+ partition_format="week" if config.partition_key else None,+ partition_keys=[config.partition_key] if config.partition_key else None,+ sort_mode="asc",+ )diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/coin_api/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/coin_api/settings.pynew file mode 100644index 000000000000..2747c64508e2--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/coin_api/settings.py@@ -0,0 +1,100 @@+from dataclasses import dataclass, field+from typing import Literal, Optional++from products.warehouse_sources.backend.types import IncrementalField, IncrementalFieldType++# How a CoinAPI endpoint is shaped on the wire, which drives how the transport reads it:+# - "reference": a single bare JSON array of metadata rows (assets / exchanges / symbols).+# - "exchange_rate": an object `{asset_id_base, rates: [...]}` we flatten into one row per quote.+# - "timeseries": a time-windowed, paginated history walked forward via `time_start`.+EndpointKind = Literal["reference", "exchange_rate", "timeseries"]+++@dataclass+class CoinApiEndpointConfig:+ name: str+ path: str # may contain `{symbol_id}` / `{base}` placeholders, resolved from config+ kind: EndpointKind+ primary_keys: list[str] = field(default_factory=lambda: ["id"])+ incremental_fields: list[IncrementalField] = field(default_factory=list)+ # Stable time field rows are partitioned by (timeseries only). Never an updated_at-style field.+ partition_key: Optional[str] = None+ # Time-series endpoints are scoped to a single symbol passed in the path, so they only sync when+ # the user has configured a `symbol_id`. They're off by default to avoid surprising credit spend.+ requires_symbol: bool = False+ # OHLCV history additionally needs a `period_id` aggregation param (e.g. 1DAY).+ needs_period: bool = False+ should_sync_default: bool = True+++def _datetime_field(name: str) -> IncrementalField:+ return {+ "label": name,+ "type": IncrementalFieldType.DateTime,+ "field": name,+ "field_type": IncrementalFieldType.DateTime,+ }+++COIN_API_ENDPOINTS: dict[str, CoinApiEndpointConfig] = {+ # Reference metadata. Full collections returned in a single response; full refresh only — CoinAPI+ # exposes no server-side "modified since" filter on these.+ "assets": CoinApiEndpointConfig(+ name="assets",+ path="/v1/assets",+ kind="reference",+ primary_keys=["asset_id"],+ ),+ "exchanges": CoinApiEndpointConfig(+ name="exchanges",+ path="/v1/exchanges",+ kind="reference",+ primary_keys=["exchange_id"],+ ),+ "symbols": CoinApiEndpointConfig(+ name="symbols",+ path="/v1/symbols",+ kind="reference",+ primary_keys=["symbol_id"],+ ),+ # Current exchange rates from the configured base asset to every other asset. A point-in-time+ # snapshot — full refresh only. `asset_id_base` is injected per row from the configured base.+ "exchange_rates": CoinApiEndpointConfig(+ name="exchange_rates",+ path="/v1/exchangerate/{base}",+ kind="exchange_rate",+ primary_keys=["asset_id_base", "asset_id_quote"],+ ),+ # OHLCV candles for the configured symbol/period. Incremental on `time_period_start`; periods are+ # immutable once closed, so the [symbol_id, period_id, time_period_start] key is stable and unique.+ "ohlcv_history": CoinApiEndpointConfig(+ name="ohlcv_history",+ path="/v1/ohlcv/{symbol_id}/history",+ kind="timeseries",+ primary_keys=["symbol_id", "period_id", "time_period_start"],+ incremental_fields=[_datetime_field("time_period_start")],+ partition_key="time_period_start",+ requires_symbol=True,+ needs_period=True,+ should_sync_default=False,+ ),+ # Individual trades for the configured symbol. Each trade carries a globally-unique `uuid`, so+ # re-fetching the `time_start` boundary on resume dedupes cleanly on merge. Incremental on+ # `time_exchange` (the trade's exchange timestamp, which never changes).+ "trades_history": CoinApiEndpointConfig(+ name="trades_history",+ path="/v1/trades/{symbol_id}/history",+ kind="timeseries",+ primary_keys=["uuid"],+ incremental_fields=[_datetime_field("time_exchange"), _datetime_field("time_coinapi")],+ partition_key="time_exchange",+ requires_symbol=True,+ should_sync_default=False,+ ),+}++ENDPOINTS = tuple(COIN_API_ENDPOINTS.keys())++INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {+ name: config.incremental_fields for name, config in COIN_API_ENDPOINTS.items()+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/coin_api/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/coin_api/source.pyindex cde7a3f8e789..19a2b13724d4 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/coin_api/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/coin_api/source.py@@ -1,19 +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.coin_api.coin_api import (+ CoinApiResumeConfig,+ coin_api_source,+ validate_credentials as validate_coin_api_credentials,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.coin_api.settings import (+ COIN_API_ENDPOINTS,+ ENDPOINTS,+ INCREMENTAL_FIELDS,+)+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 CoinApiSourceConfigfrom products.warehouse_sources.backend.types import ExternalDataSourceType@SourceRegistry.register-class CoinApiSource(SimpleSource[CoinApiSourceConfig]):+class CoinApiSource(ResumableSource[CoinApiSourceConfig, CoinApiResumeConfig]):+ lists_tables_without_credentials = True # static endpoint catalog — safe for public docs+@propertydef source_type(self) -> ExternalDataSourceType:return ExternalDataSourceType.COINAPI@@ -23,8 +47,144 @@ class CoinApiSource(SimpleSource[CoinApiSourceConfig]):return SourceConfig(name=SchemaExternalDataSourceType.COIN_API,category=DataWarehouseSourceCategory.FINANCE___ACCOUNTING,- label="Coin API",- iconPath="/static/services/coin_api.png",- fields=cast(list[FieldType], []),+ label="CoinAPI",+ releaseStatus=ReleaseStatus.ALPHA,unreleasedSource=True,+ caption="""Enter your CoinAPI key to pull cryptocurrency market data into the PostHog Data warehouse.++Create a key in the [CoinAPI customer portal](https://customer.coinapi.io/). CoinAPI uses a credit/quota-based (pay-as-you-go) model with a daily credit limit, so large time-series tables can consume significant credits.++The **reference** tables (assets, exchanges, symbols) and **exchange rates** sync with just an API key. The **OHLCV** and **trades** history tables are scoped to a single market, so set the **Symbol ID** field (and, for OHLCV, the **Period ID**) to enable them.""",+ iconPath="/static/services/coin_api.png",+ docsUrl="https://posthog.com/docs/cdp/sources/coin-api",+ fields=cast(+ list[FieldType],+ [+ SourceFieldInputConfig(+ name="api_key",+ label="API key",+ type=SourceFieldInputConfigType.PASSWORD,+ required=True,+ placeholder="00000000-0000-0000-0000-000000000000",+ secret=True,+ ),+ SourceFieldInputConfig(+ name="exchange_rate_base_asset",+ label="Exchange rate base asset",+ type=SourceFieldInputConfigType.TEXT,+ required=False,+ placeholder="USD",+ secret=False,+ ),+ SourceFieldInputConfig(+ name="symbol_id",+ label="Symbol ID",+ type=SourceFieldInputConfigType.TEXT,+ required=False,+ placeholder="BITSTAMP_SPOT_BTC_USD",+ secret=False,+ ),+ SourceFieldInputConfig(+ name="period_id",+ label="Period ID",+ type=SourceFieldInputConfigType.TEXT,+ required=False,+ placeholder="1DAY",+ secret=False,+ ),+ SourceFieldInputConfig(+ name="start_date",+ label="Start date",+ type=SourceFieldInputConfigType.TEXT,+ required=False,+ placeholder="2024-01-01T00:00:00",+ secret=False,+ ),+ ],+ ),+ )++ def get_canonical_descriptions(self) -> CanonicalDescriptions:+ from products.warehouse_sources.backend.temporal.data_imports.sources.coin_api.canonical_descriptions import (+ CANONICAL_DESCRIPTIONS,+ )++ return CANONICAL_DESCRIPTIONS++ def get_non_retryable_errors(self) -> dict[str, str | None]:+ return {+ # An invalid or malformed key surfaces as a 401 when `_fetch` calls `raise_for_status()`.+ # Retrying can never fix a credential problem. Match the stable status text and base host.+ "401 Client Error: Unauthorized for url: https://rest.coinapi.io": "Your CoinAPI key is invalid or incorrectly formatted. Create a new key in the CoinAPI customer portal, then reconnect.",+ # 403 means the key is genuine but its plan doesn't grant access to this data.+ "403 Client Error: Forbidden for url: https://rest.coinapi.io": "Your CoinAPI key does not have access to this data. Check that your CoinAPI subscription covers this endpoint, then reconnect.",+ }++ def get_schemas(+ self,+ config: CoinApiSourceConfig,+ team_id: int,+ with_counts: bool = False,+ names: list[str] | None = None,+ force_refresh: bool = False,+ ) -> list[SourceSchema]:+ def _build_schema(endpoint: str) -> SourceSchema:+ endpoint_config = COIN_API_ENDPOINTS[endpoint]+ is_timeseries = endpoint_config.kind == "timeseries"+ description = None+ if endpoint_config.requires_symbol:+ description = "Requires a Symbol ID on the source. Only syncs the configured symbol."+ # CoinAPI's time-series endpoints filter server-side on `time_start`, so they're genuinely+ # incremental. Reference/snapshot endpoints expose no such filter — full refresh only.+ return SourceSchema(+ name=endpoint,+ supports_incremental=is_timeseries,+ supports_append=is_timeseries,+ incremental_fields=INCREMENTAL_FIELDS.get(endpoint, []),+ should_sync_default=endpoint_config.should_sync_default,+ description=description,+ )++ schemas = [_build_schema(endpoint) for endpoint in ENDPOINTS]+ if names is not None:+ names_set = set(names)+ schemas = [s for s in schemas if s.name in names_set]+ return schemas++ def validate_credentials(+ self, config: CoinApiSourceConfig, team_id: int, schema_name: Optional[str] = None+ ) -> tuple[bool, str | None]:+ if validate_coin_api_credentials(config.api_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 CoinAPI key. Check that the key is correct and that CoinAPI is reachable.",+ )++ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[CoinApiResumeConfig]:+ return ResumableSourceManager[CoinApiResumeConfig](inputs, CoinApiResumeConfig)++ def source_for_pipeline(+ self,+ config: CoinApiSourceConfig,+ resumable_source_manager: ResumableSourceManager[CoinApiResumeConfig],+ inputs: SourceInputs,+ ) -> SourceResponse:+ return coin_api_source(+ api_key=config.api_key,+ endpoint=inputs.schema_name,+ logger=inputs.logger,+ resumable_source_manager=resumable_source_manager,+ symbol_id=config.symbol_id or "",+ period_id=config.period_id or "1DAY",+ exchange_rate_base_asset=config.exchange_rate_base_asset or "USD",+ start_date=config.start_date or "",+ 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,+ incremental_field=inputs.incremental_field,)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/coin_api/tests/test_coin_api.py b/products/warehouse_sources/backend/temporal/data_imports/sources/coin_api/tests/test_coin_api.pynew file mode 100644index 000000000000..4d71e17b5c78--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/coin_api/tests/test_coin_api.py@@ -0,0 +1,311 @@+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.coin_api import coin_api+from products.warehouse_sources.backend.temporal.data_imports.sources.coin_api.coin_api import (+ BASE_URL,+ CoinApiResumeConfig,+ CoinApiRetryableError,+ _build_url,+ _format_time,+ _headers,+ _initial_time_start,+ coin_api_source,+ get_rows,+ validate_credentials,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.coin_api.settings import COIN_API_ENDPOINTS+++class _FakeResponse:+ def __init__(self, status_code: int = 200, json_data: Any = None, text: str = ""):+ self.status_code = status_code+ self._json_data = json_data+ self.text = text++ @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)+ return self._responses.pop(0)+++def _manager(can_resume: bool = False, state: CoinApiResumeConfig | None = None) -> mock.MagicMock:+ manager = mock.MagicMock()+ manager.can_resume.return_value = can_resume+ manager.load_state.return_value = state+ return manager+++def _run(+ endpoint: str, responses: list[_FakeResponse], manager: mock.MagicMock, **kwargs: Any+) -> tuple[list[list[dict]], _FakeSession]:+ session = _FakeSession(responses)+ with mock.patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.coin_api.coin_api.make_tracked_session",+ return_value=session,+ ):+ return list(get_rows("key", endpoint, mock.MagicMock(), manager, **kwargs)), session+++class TestHeadersAndUrl:+ def test_headers_include_key(self) -> None:+ headers = _headers("secret-key")+ assert headers["X-CoinAPI-Key"] == "secret-key"+ assert headers["Accept"] == "application/json"++ def test_headers_omit_key_when_blank(self) -> None:+ assert "X-CoinAPI-Key" not in _headers("")++ def test_build_url_without_params(self) -> None:+ assert _build_url("/v1/assets", {}) == f"{BASE_URL}/v1/assets"++ def test_build_url_encodes_params(self) -> None:+ url = _build_url("/v1/ohlcv/SYM/history", {"period_id": "1DAY", "limit": 100})+ assert url == f"{BASE_URL}/v1/ohlcv/SYM/history?period_id=1DAY&limit=100"+++class TestFormatTime:+ def test_naive_datetime_gets_z_suffix(self) -> None:+ assert _format_time(datetime(2024, 1, 2, 3, 4, 5)) == "2024-01-02T03:04:05Z"++ def test_aware_datetime_converted_to_utc(self) -> None:+ assert _format_time(datetime(2024, 1, 2, 3, 4, 5, tzinfo=UTC)) == "2024-01-02T03:04:05Z"++ def test_date_becomes_midnight_utc(self) -> None:+ assert _format_time(date(2024, 1, 2)) == "2024-01-02T00:00:00Z"++ def test_string_passthrough(self) -> None:+ assert _format_time("2024-01-02T00:00:00") == "2024-01-02T00:00:00"+++class TestFetch:+ @parameterized.expand([(429,), (500,), (503,)])+ def test_retryable_statuses_raise_retryable_error(self, status: int) -> None:+ session = _FakeSession([_FakeResponse(status_code=status)])+ with pytest.raises(CoinApiRetryableError):+ coin_api._fetch(session, "http://x", {}, mock.MagicMock()) # type: ignore[arg-type]++ @parameterized.expand([(401,), (403,), (404,)])+ def test_client_errors_raise_http_error(self, status: int) -> None:+ session = _FakeSession([_FakeResponse(status_code=status, text="nope")])+ with pytest.raises(requests.HTTPError):+ coin_api._fetch(session, "http://x", {}, mock.MagicMock()) # type: ignore[arg-type]++ def test_ok_returns_json(self) -> None:+ session = _FakeSession([_FakeResponse(json_data=[{"a": 1}])])+ assert coin_api._fetch(session, "http://x", {}, mock.MagicMock()) == [{"a": 1}] # type: ignore[arg-type]+++class TestValidateCredentials:+ @parameterized.expand(+ [+ ("valid", 200, True),+ ("forbidden_but_genuine_key", 403, True),+ ("unauthorized", 401, False),+ ("server_error", 500, False),+ ]+ )+ @mock.patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.coin_api.coin_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.coin_api.coin_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.coin_api.coin_api.make_tracked_session"+ )+ def test_probes_exchangerate_with_key_header_and_redacts(self, mock_session: mock.MagicMock) -> None:+ get = mock_session.return_value.get+ get.return_value = _FakeResponse(status_code=200)+ validate_credentials("secret")+ assert get.call_args.args[0] == f"{BASE_URL}/v1/exchangerate/BTC/USD"+ assert get.call_args.kwargs["headers"]["X-CoinAPI-Key"] == "secret"+ # The key rides in a custom header the sampler can't predict, so it must be redacted by value.+ assert mock_session.call_args.kwargs["redact_values"] == ("secret",)+++class TestInitialTimeStart:+ def test_uses_incremental_value_when_present(self) -> None:+ assert _initial_time_start(True, datetime(2024, 5, 1, tzinfo=UTC), "2020-01-01") == "2024-05-01T00:00:00Z"++ def test_falls_back_to_start_date_when_no_incremental_value(self) -> None:+ assert _initial_time_start(False, None, "2020-01-01") == "2020-01-01"++ def test_defaults_to_lookback_when_nothing_provided(self) -> None:+ # Just assert it produces a Z-suffixed ISO string rather than pinning to a wall-clock value.+ result = _initial_time_start(False, None, "")+ assert result.endswith("Z")+++class TestReferenceEndpoint:+ def test_yields_list_once_and_does_not_save_state(self) -> None:+ manager = _manager()+ rows = [{"asset_id": "BTC"}, {"asset_id": "ETH"}]+ batches, _ = _run("assets", [_FakeResponse(json_data=rows)], manager)+ assert batches == [rows]+ manager.save_state.assert_not_called()++ def test_empty_yields_nothing(self) -> None:+ batches, _ = _run("assets", [_FakeResponse(json_data=[])], _manager())+ assert batches == []+++class TestExchangeRateEndpoint:+ def test_flattens_rates_and_injects_base(self) -> None:+ body = {+ "asset_id_base": "USD",+ "rates": [+ {"time": "2024-01-01T00:00:00Z", "asset_id_quote": "BTC", "rate": 0.00002},+ {"time": "2024-01-01T00:00:00Z", "asset_id_quote": "ETH", "rate": 0.0003},+ ],+ }+ batches, session = _run("exchange_rates", [_FakeResponse(json_data=body)], _manager())+ assert len(batches) == 1+ assert all(row["asset_id_base"] == "USD" for row in batches[0])+ assert {row["asset_id_quote"] for row in batches[0]} == {"BTC", "ETH"}++ def test_uses_configured_base_in_path(self) -> None:+ body = {"asset_id_base": "EUR", "rates": []}+ _, session = _run("exchange_rates", [_FakeResponse(json_data=body)], _manager(), exchange_rate_base_asset="EUR")+ assert session.requested_urls[0] == f"{BASE_URL}/v1/exchangerate/EUR"+++class TestTimeseriesEndpoint:+ def test_requires_symbol_id(self) -> None:+ with pytest.raises(ValueError, match="requires a symbol_id"):+ _run("ohlcv_history", [], _manager(), symbol_id="")++ def test_injects_symbol_and_period_for_ohlcv(self) -> None:+ with mock.patch.object(coin_api, "PAGE_LIMIT", 5):+ rows = [{"time_period_start": "2024-01-01T00:00:00.0000000Z", "price_close": 1}]+ batches, _ = _run("ohlcv_history", [_FakeResponse(json_data=rows)], _manager(), symbol_id="SYM")+ assert batches[0][0]["symbol_id"] == "SYM"+ assert batches[0][0]["period_id"] == "1DAY"++ def test_paginates_advancing_time_start_and_saves_state(self) -> None:+ with mock.patch.object(coin_api, "PAGE_LIMIT", 2):+ page1 = [+ {"time_period_start": "2024-01-01T00:00:00.0000000Z"},+ {"time_period_start": "2024-01-02T00:00:00.0000000Z"},+ ]+ page2 = [{"time_period_start": "2024-01-03T00:00:00.0000000Z"}]+ manager = _manager()+ batches, session = _run(+ "ohlcv_history",+ [_FakeResponse(json_data=page1), _FakeResponse(json_data=page2)],+ manager,+ symbol_id="SYM",+ start_date="2023-01-01T00:00:00",+ )+ assert len(batches) == 2+ # Second request advances time_start to the last row of page 1.+ assert "time_start=2024-01-02T00%3A00%3A00.0000000Z" in session.requested_urls[1]+ # State saved once after the first full page so a crash resumes at the next window.+ manager.save_state.assert_called_once_with(CoinApiResumeConfig(time_start="2024-01-02T00:00:00.0000000Z"))++ def test_short_first_page_stops_without_second_request(self) -> None:+ with mock.patch.object(coin_api, "PAGE_LIMIT", 5):+ rows = [{"time_period_start": "2024-01-01T00:00:00.0000000Z"}]+ manager = _manager()+ batches, session = _run("ohlcv_history", [_FakeResponse(json_data=rows)], manager, symbol_id="SYM")+ assert len(batches) == 1+ assert len(session.requested_urls) == 1+ manager.save_state.assert_not_called()++ def test_resumes_from_saved_time_start(self) -> None:+ with mock.patch.object(coin_api, "PAGE_LIMIT", 5):+ manager = _manager(can_resume=True, state=CoinApiResumeConfig(time_start="2024-06-01T00:00:00Z"))+ rows = [{"time_period_start": "2024-06-02T00:00:00.0000000Z"}]+ _, session = _run("ohlcv_history", [_FakeResponse(json_data=rows)], manager, symbol_id="SYM")+ assert "time_start=2024-06-01T00%3A00%3A00Z" in session.requested_urls[0]++ def test_uses_incremental_value_as_initial_time_start(self) -> None:+ with mock.patch.object(coin_api, "PAGE_LIMIT", 5):+ rows = [{"time_exchange": "2024-05-02T00:00:00.0000000Z", "uuid": "u1"}]+ _, session = _run(+ "trades_history",+ [_FakeResponse(json_data=rows)],+ _manager(),+ symbol_id="SYM",+ should_use_incremental_field=True,+ db_incremental_field_last_value=datetime(2024, 5, 1, tzinfo=UTC),+ )+ assert "time_start=2024-05-01T00%3A00%3A00Z" in session.requested_urls[0]++ def test_stall_guard_breaks_when_boundary_does_not_advance(self) -> None:+ # A full page whose rows all share one timestamp would otherwise loop forever.+ with mock.patch.object(coin_api, "PAGE_LIMIT", 2):+ same = "2024-01-01T00:00:00.0000000Z"+ page = [{"time_exchange": same, "uuid": "a"}, {"time_exchange": same, "uuid": "b"}]+ manager = _manager()+ # Window start equals the page's single timestamp, so advancing wouldn't progress.+ batches, session = _run(+ "trades_history", [_FakeResponse(json_data=page)], manager, symbol_id="SYM", start_date=same+ )+ assert len(batches) == 1+ assert len(session.requested_urls) == 1+ manager.save_state.assert_not_called()+++class TestCoinApiSourceResponse:+ @parameterized.expand(+ [+ ("assets", ["asset_id"], False),+ ("exchanges", ["exchange_id"], False),+ ("symbols", ["symbol_id"], False),+ ("exchange_rates", ["asset_id_base", "asset_id_quote"], False),+ ("ohlcv_history", ["symbol_id", "period_id", "time_period_start"], True),+ ("trades_history", ["uuid"], True),+ ]+ )+ def test_primary_keys_and_partitioning(self, endpoint: str, expected_keys: list[str], partitioned: bool) -> None:+ response = coin_api_source("key", endpoint, mock.MagicMock(), mock.MagicMock())+ assert response.name == endpoint+ assert response.primary_keys == expected_keys+ assert response.sort_mode == "asc"+ if partitioned:+ assert response.partition_mode == "datetime"+ assert response.partition_keys == [COIN_API_ENDPOINTS[endpoint].partition_key]+ else:+ assert response.partition_mode is None+ assert response.partition_keys is None++ def test_every_settings_endpoint_builds_a_source_response(self) -> None:+ for endpoint in COIN_API_ENDPOINTS:+ response = coin_api_source("key", endpoint, mock.MagicMock(), mock.MagicMock())+ assert response.name == endpoint+ assert response.primary_keys == COIN_API_ENDPOINTS[endpoint].primary_keysdiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/coin_api/tests/test_coin_api_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/coin_api/tests/test_coin_api_source.pynew file mode 100644index 000000000000..7c6e6232f337--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/coin_api/tests/test_coin_api_source.py@@ -0,0 +1,164 @@+import pytest+from unittest import mock++from posthog.schema import ReleaseStatus, SourceFieldInputConfig, SourceFieldInputConfigType++from products.warehouse_sources.backend.temporal.data_imports.sources.coin_api.coin_api import CoinApiResumeConfig+from products.warehouse_sources.backend.temporal.data_imports.sources.coin_api.settings import ENDPOINTS+from products.warehouse_sources.backend.temporal.data_imports.sources.coin_api.source import CoinApiSource+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 CoinApiSourceConfig+from products.warehouse_sources.backend.types import ExternalDataSourceType+++class TestCoinApiSource:+ def setup_method(self) -> None:+ self.source = CoinApiSource()+ self.team_id = 123+ self.config = CoinApiSourceConfig(api_key="key", symbol_id="BITSTAMP_SPOT_BTC_USD", period_id="1DAY")++ def test_source_type(self) -> None:+ assert self.source.source_type == ExternalDataSourceType.COINAPI++ def test_get_source_config(self) -> None:+ config = self.source.get_source_config+ assert config.name.value == "CoinApi"+ assert config.label == "CoinAPI"+ assert config.releaseStatus == ReleaseStatus.ALPHA+ # Shipped behind the unreleased flag until the alpha has been exercised end to end.+ assert config.unreleasedSource is True+ assert config.docsUrl == "https://posthog.com/docs/cdp/sources/coin-api"+ assert [f.name for f in config.fields] == [+ "api_key",+ "exchange_rate_base_asset",+ "symbol_id",+ "period_id",+ "start_date",+ ]++ def test_api_key_field_is_secret_password(self) -> None:+ key_field = next(+ f+ for f in self.source.get_source_config.fields+ if isinstance(f, SourceFieldInputConfig) and f.name == "api_key"+ )+ assert key_field.type == SourceFieldInputConfigType.PASSWORD+ assert key_field.secret is True+ assert key_field.required is True++ def test_lists_tables_without_credentials(self) -> None:+ # Static endpoint catalog with no I/O, so public docs can render the table list.+ assert self.source.lists_tables_without_credentials is True++ @pytest.mark.parametrize(+ "observed_error",+ [+ "401 Client Error: Unauthorized for url: https://rest.coinapi.io/v1/assets",+ "403 Client Error: Forbidden for url: https://rest.coinapi.io/v1/ohlcv/SYM/history",+ ],+ )+ def test_non_retryable_errors_match_auth_failures(self, observed_error: str) -> None:+ non_retryable = self.source.get_non_retryable_errors()+ assert any(key in observed_error for key in non_retryable)++ @pytest.mark.parametrize(+ "other_error",+ [+ "429 Client Error: Too Many Requests for url: https://rest.coinapi.io/v1/trades/SYM/history",+ "500 Server Error for url: https://rest.coinapi.io/v1/exchanges",+ ],+ )+ def test_non_retryable_errors_does_not_match_transient(self, other_error: str) -> None:+ non_retryable = self.source.get_non_retryable_errors()+ assert not any(key in other_error for key in non_retryable)++ def test_get_schemas_marks_only_timeseries_incremental(self) -> None:+ schemas = {s.name: s for s in self.source.get_schemas(self.config, self.team_id)}+ assert set(schemas) == set(ENDPOINTS)+ for name in ("assets", "exchanges", "symbols", "exchange_rates"):+ assert schemas[name].supports_incremental is False+ assert schemas[name].supports_append is False+ for name in ("ohlcv_history", "trades_history"):+ assert schemas[name].supports_incremental is True+ assert schemas[name].supports_append is True++ def test_timeseries_endpoints_off_by_default(self) -> None:+ schemas = {s.name: s for s in self.source.get_schemas(self.config, self.team_id)}+ assert schemas["assets"].should_sync_default is True+ assert schemas["ohlcv_history"].should_sync_default is False+ assert schemas["trades_history"].should_sync_default is False++ def test_get_schemas_filtered_by_names(self) -> None:+ schemas = self.source.get_schemas(self.config, self.team_id, names=["ohlcv_history"])+ assert [s.name for s in schemas] == ["ohlcv_history"]++ 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 CoinAPI key. Check that the key is correct and that CoinAPI is reachable.",+ ),+ ],+ )+ @mock.patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.coin_api.source.validate_coin_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("key")++ 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 CoinApiResumeConfig++ @mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.coin_api.source.coin_api_source")+ def test_source_for_pipeline_plumbs_arguments(self, mock_source: mock.MagicMock) -> None:+ inputs = mock.MagicMock()+ inputs.schema_name = "ohlcv_history"+ inputs.should_use_incremental_field = True+ manager = mock.MagicMock()++ self.source.source_for_pipeline(self.config, manager, inputs)++ kwargs = mock_source.call_args.kwargs+ assert kwargs["api_key"] == "key"+ assert kwargs["endpoint"] == "ohlcv_history"+ assert kwargs["symbol_id"] == "BITSTAMP_SPOT_BTC_USD"+ assert kwargs["period_id"] == "1DAY"+ assert kwargs["resumable_source_manager"] is manager++ @mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.coin_api.source.coin_api_source")+ def test_source_for_pipeline_coerces_blank_optionals_to_defaults(self, mock_source: mock.MagicMock) -> None:+ config = CoinApiSourceConfig(api_key="key")+ inputs = mock.MagicMock()+ inputs.schema_name = "exchange_rates"+ inputs.should_use_incremental_field = False++ self.source.source_for_pipeline(config, mock.MagicMock(), inputs)++ kwargs = mock_source.call_args.kwargs+ assert kwargs["symbol_id"] == ""+ assert kwargs["period_id"] == "1DAY"+ assert kwargs["exchange_rate_base_asset"] == "USD"+ assert kwargs["start_date"] == ""++ def test_canonical_descriptions_cover_key_endpoints(self) -> None:+ descriptions = self.source.get_canonical_descriptions()+ assert "ohlcv_history" in descriptions+ assert "price_close" in descriptions["ohlcv_history"]["columns"]++ def test_documented_tables_render_for_public_docs(self) -> None:+ tables = self.source.get_documented_tables()+ assert {t["name"] for t in tables} == set(ENDPOINTS)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.pyindex 65e256030b3a..7bd67e61fea8 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@@ -747,7 +747,11 @@ class CodefreshSourceConfig(config.Config):@config.configclass CoinApiSourceConfig(config.Config):- pass+ api_key: str+ exchange_rate_base_asset: str | None = None+ symbol_id: str | None = None+ period_id: str | None = None+ start_date: str | None = None@config.config