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 coingecko import source (#65641)

Tom Owersbb0e1b761640
diff --git a/posthog/temporal/data_imports/sources/SOURCES.md b/posthog/temporal/data_imports/sources/SOURCES.md
index 09eab97078aa..8adfc53769fb 100644
--- a/posthog/temporal/data_imports/sources/SOURCES.md
+++ b/posthog/temporal/data_imports/sources/SOURCES.md
@@ -69,6 +69,7 @@ the row lists both.
| chargebee | HTTP | requests + `rest_source.RESTClient` | ✅ |
| checkout_com | HTTP | requests | ✅ |
| coda | HTTP | requests | ✅ |
+| coingecko | HTTP | requests | ✅ |
| commercetools | HTTP | requests | ✅ |
| confluence | HTTP | requests | ✅ |
| chartmogul | HTTP | requests | ✅ |
@@ -323,7 +324,6 @@ doesn't conflict with concurrent PRs.
- cockroachdb
- codefresh
- coin_api
-- coingecko
- coinmarketcap
- concord
- configcat
diff --git a/posthog/temporal/data_imports/sources/coingecko/canonical_descriptions.py b/posthog/temporal/data_imports/sources/coingecko/canonical_descriptions.py
new file mode 100644
index 000000000000..43c1db19f928
--- /dev/null
+++ b/posthog/temporal/data_imports/sources/coingecko/canonical_descriptions.py
@@ -0,0 +1,94 @@
+from posthog.temporal.data_imports.sources.common.canonical_descriptions import CanonicalDescriptions
+
+# Descriptions sourced from the public CoinGecko API v3 docs (https://docs.coingecko.com/reference).
+# Partial coverage is fine — anything not described here falls back to LLM enrichment.
+CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
+ "coins_list": {
+ "description": "Every coin tracked by CoinGecko, as id/symbol/name reference rows.",
+ "docs_url": "https://docs.coingecko.com/reference/coins-list",
+ "columns": {
+ "id": "CoinGecko coin id (used as the path parameter on per-coin endpoints).",
+ "symbol": "Ticker symbol (not unique across coins).",
+ "name": "Display name of the coin.",
+ },
+ },
+ "coins_markets": {
+ "description": "Current market snapshot per coin in USD: price, market cap, volume, supply, and all-time high/low.",
+ "docs_url": "https://docs.coingecko.com/reference/coins-markets",
+ "columns": {
+ "id": "CoinGecko coin id.",
+ "symbol": "Ticker symbol.",
+ "name": "Display name of the coin.",
+ "current_price": "Latest price in USD.",
+ "market_cap": "Market capitalization in USD.",
+ "market_cap_rank": "Rank of the coin by market capitalization.",
+ "fully_diluted_valuation": "Market cap if the max supply were in circulation, in USD.",
+ "total_volume": "Trading volume over the last 24 hours in USD.",
+ "high_24h": "Highest price in the last 24 hours, in USD.",
+ "low_24h": "Lowest price in the last 24 hours, in USD.",
+ "price_change_24h": "Absolute price change over the last 24 hours, in USD.",
+ "price_change_percentage_24h": "Percentage price change over the last 24 hours.",
+ "circulating_supply": "Number of coins currently in circulation.",
+ "total_supply": "Total number of coins that exist (excluding burned).",
+ "max_supply": "Maximum number of coins that will ever exist (null if uncapped).",
+ "ath": "All-time-high price in USD.",
+ "ath_date": "Timestamp of the all-time-high price.",
+ "atl": "All-time-low price in USD.",
+ "atl_date": "Timestamp of the all-time-low price.",
+ "last_updated": "Timestamp CoinGecko last refreshed this row.",
+ },
+ },
+ "coins_categories": {
+ "description": "Aggregated market data per coin category (market cap, 24h volume, top coins).",
+ "docs_url": "https://docs.coingecko.com/reference/coins-categories",
+ "columns": {
+ "id": "Category id.",
+ "name": "Category display name.",
+ "market_cap": "Total market capitalization of the category in USD.",
+ "market_cap_change_24h": "24-hour percentage change in the category's market cap.",
+ "volume_24h": "Total 24-hour trading volume of the category in USD.",
+ "top_3_coins_id": "CoinGecko ids of the category's top three coins by market cap.",
+ "updated_at": "Timestamp CoinGecko last refreshed this category.",
+ },
+ },
+ "coins_categories_list": {
+ "description": "Reference list of category id/name pairs.",
+ "docs_url": "https://docs.coingecko.com/reference/coins-categories-list",
+ "columns": {
+ "category_id": "Category id (used as the category filter on /coins/markets).",
+ "name": "Category display name.",
+ },
+ },
+ "exchanges": {
+ "description": "Exchange metadata: name, country, trust score, and 24-hour BTC-denominated volume.",
+ "docs_url": "https://docs.coingecko.com/reference/exchanges",
+ "columns": {
+ "id": "CoinGecko exchange id.",
+ "name": "Exchange display name.",
+ "year_established": "Year the exchange was established.",
+ "country": "Country the exchange operates from.",
+ "trust_score": "CoinGecko trust score (0-10).",
+ "trust_score_rank": "Rank of the exchange by trust score.",
+ "trade_volume_24h_btc": "24-hour trading volume denominated in BTC.",
+ },
+ },
+ "exchanges_list": {
+ "description": "Reference list of exchange id/name pairs.",
+ "docs_url": "https://docs.coingecko.com/reference/exchanges-list",
+ "columns": {
+ "id": "CoinGecko exchange id.",
+ "name": "Exchange display name.",
+ },
+ },
+ "asset_platforms": {
+ "description": "Blockchain platforms (Ethereum, Solana, ...) that coins can be issued on.",
+ "docs_url": "https://docs.coingecko.com/reference/asset-platforms-list",
+ "columns": {
+ "id": "Asset platform id.",
+ "chain_identifier": "EVM chain id where applicable (null for non-EVM chains).",
+ "name": "Platform display name.",
+ "shortname": "Short name of the platform.",
+ "native_coin_id": "CoinGecko coin id of the platform's native token.",
+ },
+ },
+}
diff --git a/posthog/temporal/data_imports/sources/coingecko/coingecko.py b/posthog/temporal/data_imports/sources/coingecko/coingecko.py
new file mode 100644
index 000000000000..15e2ebae4df8
--- /dev/null
+++ b/posthog/temporal/data_imports/sources/coingecko/coingecko.py
@@ -0,0 +1,172 @@
+import dataclasses
+from collections.abc import Iterator
+from typing import Any
+from urllib.parse import urlencode
+
+import requests
+from structlog.types import FilteringBoundLogger
+from tenacity import retry, retry_if_exception_type, stop_after_attempt, wait_exponential_jitter
+
+from posthog.temporal.data_imports.pipelines.pipeline.typings import SourceResponse
+from posthog.temporal.data_imports.sources.coingecko.settings import COINGECKO_ENDPOINTS
+from posthog.temporal.data_imports.sources.common.http import make_tracked_session
+from posthog.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+
+# Two distinct hosts: the free Demo plan (and keyless public access) live on api.coingecko.com,
+# paid Pro plans on pro-api.coingecko.com. The plan also selects which API-key header to send.
+DEMO_BASE_URL = "https://api.coingecko.com/api/v3"
+PRO_BASE_URL = "https://pro-api.coingecko.com/api/v3"
+
+PLAN_DEMO = "demo"
+PLAN_PRO = "pro"
+
+# /coins/markets allows up to 250 per page; other paginated endpoints accept it too.
+PAGE_SIZE = 250
+REQUEST_TIMEOUT_SECONDS = 60
+MAX_RETRY_ATTEMPTS = 6
+
+
+class CoinGeckoRetryableError(Exception):
+ pass
+
+
+class CoinGeckoResumeConfig:
+ # Next page to fetch for paginated endpoints. Unused for single-response reference endpoints.
+ page: int = 1
+
+
+def _base_url(plan: str) -> str:
+ return PRO_BASE_URL if plan == PLAN_PRO else DEMO_BASE_URL
+
+
+def _headers(plan: str, api_key: str) -> dict[str, str]:
+ header_name = "x-cg-pro-api-key" if plan == PLAN_PRO else "x-cg-demo-api-key"
+ headers = {"Accept": "application/json"}
+ if api_key:
+ headers[header_name] = api_key
+ return headers
+
+
+def _build_url(base_url: str, path: str, params: dict[str, Any]) -> str:
+ if not params:
+ return f"{base_url}{path}"
+ return f"{base_url}{path}?{urlencode(params)}"
+
+
+def _is_rate_limited(response: requests.Response) -> bool:
+ """CoinGecko signals rate limiting both via a 429 status and, on the keyless/demo tier, via a
+ 200/4xx body carrying ``{"status": {"error_code": 429}}``. Treat both as retryable."""
+ if response.status_code == 429:
+ return True
+ try:
+ body = response.json()
+ except ValueError:
+ return False
+ if isinstance(body, dict):
+ status = body.get("status")
+ if isinstance(status, dict) and status.get("error_code") == 429:
+ return True
+ return False
+
+
+def _fetch(session: requests.Session, url: str, headers: dict[str, str], logger: FilteringBoundLogger) -> Any:
+ response = session.get(url, headers=headers, timeout=REQUEST_TIMEOUT_SECONDS)
+
+ if _is_rate_limited(response) or response.status_code >= 500:
+ raise CoinGeckoRetryableError(f"CoinGecko API error (retryable): status={response.status_code}, url={url}")
+
+ if not response.ok:
+ logger.error(f"CoinGecko API error: status={response.status_code}, body={response.text}, url={url}")
+ response.raise_for_status()
+
+ return response.json()
+
+
+def validate_credentials(plan: str, api_key: str) -> bool:
+ """Confirm the key is genuine by pinging with the plan's auth header. A valid key returns 200;
+ an invalid one returns 401."""
+ url = f"{_base_url(plan)}/ping"
+ try:
+ session = make_tracked_session(redact_values=(api_key,) if api_key else ())
+ response = session.get(url, headers=_headers(plan, api_key), timeout=10)
+ return response.status_code == 200
+ except Exception:
+ return False
+
+
+def get_rows(
+ plan: str,
+ api_key: str,
+ endpoint: str,
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[CoinGeckoResumeConfig],
+) -> Iterator[list[dict[str, Any]]]:
+ config = COINGECKO_ENDPOINTS[endpoint]
+ session = make_tracked_session(redact_values=(api_key,) if api_key else ())
+ headers = _headers(plan, api_key)
+ base_url = _base_url(plan)
+
+ @retry(
+ retry=retry_if_exception_type((CoinGeckoRetryableError, 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 not config.paginated:
+ data = fetch(_build_url(base_url, config.path, dict(config.extra_params)))
+ if isinstance(data, list) and data:
+ yield data
+ return
+
+ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None
+ page = resume.page if resume is not None else 1
+ if resume is not None:
+ logger.debug(f"CoinGecko: resuming {endpoint} from page {page}")
+
+ while True:
+ params: dict[str, Any] = {**config.extra_params, "per_page": PAGE_SIZE, "page": page}
+ data = fetch(_build_url(base_url, config.path, params))
+
+ # An empty list means we've paged past the end of the collection.
+ if not isinstance(data, list) or not data:
+ break
+
+ yield data
+
+ # A short page is the last page; stop without an extra empty request.
+ if len(data) < PAGE_SIZE:
+ break
+
+ page += 1
+ # Save AFTER yielding so a crash re-yields the last page (merge dedupes on the primary key)
+ # rather than skipping it.
+ resumable_source_manager.save_state(CoinGeckoResumeConfig(page=page))
+
+
+def coingecko_source(
+ plan: str,
+ api_key: str,
+ endpoint: str,
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[CoinGeckoResumeConfig],
+) -> SourceResponse:
+ config = COINGECKO_ENDPOINTS[endpoint]
+
+ return SourceResponse(
+ name=endpoint,
+ items=lambda: get_rows(
+ plan=plan,
+ api_key=api_key,
+ endpoint=endpoint,
+ logger=logger,
+ resumable_source_manager=resumable_source_manager,
+ ),
+ primary_keys=config.primary_keys,
+ # Snapshot/reference endpoints expose no stable created_at, so there's nothing to partition on.
+ partition_count=None,
+ partition_size=None,
+ )
diff --git a/posthog/temporal/data_imports/sources/coingecko/settings.py b/posthog/temporal/data_imports/sources/coingecko/settings.py
new file mode 100644
index 000000000000..8f5f1b048a5f
--- /dev/null
+++ b/posthog/temporal/data_imports/sources/coingecko/settings.py
@@ -0,0 +1,69 @@
+from dataclasses import dataclass, field
+
+from products.data_warehouse.backend.types import IncrementalField
+
+
+@dataclass
+class CoinGeckoEndpointConfig:
+ name: str
+ path: str
+ # Per-endpoint primary keys. CoinGecko ids are globally unique within a resource type, so a
+ # single id column is enough for the catalog/snapshot endpoints we expose.
+ primary_keys: list[str] = field(default_factory=lambda: ["id"])
+ # Whether the endpoint supports page/per_page pagination. Reference endpoints (e.g. /coins/list)
+ # return the whole collection in one response and ignore pagination params.
+ paginated: bool = False
+ # Extra static query params (e.g. vs_currency for /coins/markets).
+ extra_params: dict[str, str] = field(default_factory=dict)
+ should_sync_default: bool = True
+
+
+COINGECKO_ENDPOINTS: dict[str, CoinGeckoEndpointConfig] = {
+ # Full catalog of every coin tracked by CoinGecko (id/symbol/name). Reference data, one response.
+ "coins_list": CoinGeckoEndpointConfig(
+ name="coins_list",
+ path="/coins/list",
+ ),
+ # Market snapshot (price, market cap, volume, supply, ATH/ATL, ...) for every coin, in USD.
+ # Paginated up to 250 per page. Snapshot data — full refresh only (no server-side updated filter).
+ "coins_markets": CoinGeckoEndpointConfig(
+ name="coins_markets",
+ path="/coins/markets",
+ paginated=True,
+ extra_params={"vs_currency": "usd"},
+ ),
+ # Category market data (market cap, 24h volume, top coins, ...). Single response.
+ "coins_categories": CoinGeckoEndpointConfig(
+ name="coins_categories",
+ path="/coins/categories",
+ ),
+ # Reference list of category id/name pairs. Single response.
+ "coins_categories_list": CoinGeckoEndpointConfig(
+ name="coins_categories_list",
+ path="/coins/categories/list",
+ primary_keys=["category_id"],
+ ),
+ # Exchange metadata (name, country, trust score, 24h BTC volume, ...). Paginated.
+ "exchanges": CoinGeckoEndpointConfig(
+ name="exchanges",
+ path="/exchanges",
+ paginated=True,
+ ),
+ # Reference list of exchange id/name pairs. Single response.
+ "exchanges_list": CoinGeckoEndpointConfig(
+ name="exchanges_list",
+ path="/exchanges/list",
+ ),
+ # Blockchain platforms (Ethereum, Solana, ...) coins can live on. Single response.
+ "asset_platforms": CoinGeckoEndpointConfig(
+ name="asset_platforms",
+ path="/asset_platforms",
+ ),
+}
+
+ENDPOINTS = tuple(COINGECKO_ENDPOINTS.keys())
+
+# CoinGecko's catalog/snapshot endpoints expose no server-side updated_after/since filter, so every
+# exposed endpoint is full refresh only. The map is kept (empty) to mirror the other sources' shape
+# and make adding a server-side-filterable endpoint later an additive change.
+INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {name: [] for name in COINGECKO_ENDPOINTS}
diff --git a/posthog/temporal/data_imports/sources/coingecko/source.py b/posthog/temporal/data_imports/sources/coingecko/source.py
index ebda448e9a28..b50b7a8270e1 100644
--- a/posthog/temporal/data_imports/sources/coingecko/source.py
+++ b/posthog/temporal/data_imports/sources/coingecko/source.py
@@ -1,20 +1,37 @@
-from typing import cast
+from typing import Optional, cast
from posthog.schema import (
DataWarehouseSourceCategory,
ExternalDataSourceType as SchemaExternalDataSourceType,
+ ReleaseStatus,
SourceConfig,
+ SourceFieldInputConfig,
+ SourceFieldInputConfigType,
+ SourceFieldSelectConfig,
+ SourceFieldSelectConfigOption,
)
-from posthog.temporal.data_imports.sources.common.base import FieldType, SimpleSource
+from posthog.temporal.data_imports.pipelines.pipeline.typings import SourceInputs, SourceResponse
+from posthog.temporal.data_imports.sources.coingecko.coingecko import (
+ PLAN_DEMO,
+ PLAN_PRO,
+ CoinGeckoResumeConfig,
+ coingecko_source,
+ validate_credentials as validate_coingecko_credentials,
+)
+from posthog.temporal.data_imports.sources.coingecko.settings import ENDPOINTS, INCREMENTAL_FIELDS
+from posthog.temporal.data_imports.sources.common.base import FieldType, ResumableSource
+from posthog.temporal.data_imports.sources.common.canonical_descriptions import CanonicalDescriptions
from posthog.temporal.data_imports.sources.common.registry import SourceRegistry
+from posthog.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from posthog.temporal.data_imports.sources.common.schema import SourceSchema
from posthog.temporal.data_imports.sources.generated_configs import CoinGeckoSourceConfig
from products.data_warehouse.backend.types import ExternalDataSourceType
@SourceRegistry.register
-class CoinGeckoSource(SimpleSource[CoinGeckoSourceConfig]):
+class CoinGeckoSource(ResumableSource[CoinGeckoSourceConfig, CoinGeckoResumeConfig]):
@property
def source_type(self) -> ExternalDataSourceType:
return ExternalDataSourceType.COINGECKO
@@ -25,7 +42,105 @@ class CoinGeckoSource(SimpleSource[CoinGeckoSourceConfig]):
name=SchemaExternalDataSourceType.COIN_GECKO,
category=DataWarehouseSourceCategory.FINANCE___ACCOUNTING,
label="CoinGecko",
+ releaseStatus=ReleaseStatus.ALPHA,
+ caption="""Enter your CoinGecko API key to pull cryptocurrency market data into the PostHog Data warehouse.
+
+Create a key in your [CoinGecko developer dashboard](https://www.coingecko.com/en/developers/dashboard). Free **Demo** keys (`x-cg-demo-api-key`) and paid **Pro** keys (`x-cg-pro-api-key`) use different hosts — pick the plan that matches your key.
+
+CoinGecko enforces tight per-minute rate limits and monthly credit caps, especially on the Demo plan, so large tables may take a while to sync.""",
iconPath="/static/services/coingecko.png",
- fields=cast(list[FieldType], []),
- unreleasedSource=True,
+ docsUrl="https://posthog.com/docs/cdp/sources/coingecko",
+ fields=cast(
+ list[FieldType],
+ [
+ SourceFieldSelectConfig(
+ name="plan",
+ label="Plan",
+ required=True,
+ defaultValue=PLAN_DEMO,
+ options=[
+ SourceFieldSelectConfigOption(label="Demo (free)", value=PLAN_DEMO),
+ SourceFieldSelectConfigOption(label="Pro (paid)", value=PLAN_PRO),
+ ],
+ ),
+ SourceFieldInputConfig(
+ name="api_key",
+ label="API key",
+ type=SourceFieldInputConfigType.PASSWORD,
+ required=True,
+ placeholder="CG-...",
+ secret=True,
+ ),
+ ],
+ ),
+ )
+
+ def get_canonical_descriptions(self) -> CanonicalDescriptions:
+ from posthog.temporal.data_imports.sources.coingecko.canonical_descriptions import CANONICAL_DESCRIPTIONS
+
+ return CANONICAL_DESCRIPTIONS
+
+ def get_non_retryable_errors(self) -> dict[str, str | None]:
+ return {
+ # An invalid or revoked 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,
+ # not the per-request path/query.
+ "401 Client Error: Unauthorized for url: https://api.coingecko.com": "Your CoinGecko API key is invalid or has been revoked. Create a new Demo key in your CoinGecko dashboard, then reconnect.",
+ "401 Client Error: Unauthorized for url: https://pro-api.coingecko.com": "Your CoinGecko Pro API key is invalid or has been revoked. Create a new Pro key in your CoinGecko dashboard, then reconnect.",
+ }
+
+ def get_schemas(
+ self,
+ config: CoinGeckoSourceConfig,
+ team_id: int,
+ with_counts: bool = False,
+ names: list[str] | None = None,
+ force_refresh: bool = False,
+ ) -> list[SourceSchema]:
+ # Every exposed endpoint is a catalog/snapshot with no server-side timestamp filter, so all
+ # are full refresh only (no incremental/append).
+ schemas = [
+ SourceSchema(
+ name=endpoint,
+ supports_incremental=False,
+ supports_append=False,
+ incremental_fields=INCREMENTAL_FIELDS.get(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: CoinGeckoSourceConfig, team_id: int, schema_name: Optional[str] = None
+ ) -> tuple[bool, str | None]:
+ if validate_coingecko_credentials(config.plan, 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 CoinGecko API key. Check that the key is correct and that CoinGecko is reachable.",
+ )
+
+ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[CoinGeckoResumeConfig]:
+ return ResumableSourceManager[CoinGeckoResumeConfig](inputs, CoinGeckoResumeConfig)
+
+ def source_for_pipeline(
+ self,
+ config: CoinGeckoSourceConfig,
+ resumable_source_manager: ResumableSourceManager[CoinGeckoResumeConfig],
+ inputs: SourceInputs,
+ ) -> SourceResponse:
+ return coingecko_source(
+ plan=config.plan,
+ api_key=config.api_key,
+ endpoint=inputs.schema_name,
+ logger=inputs.logger,
+ resumable_source_manager=resumable_source_manager,
)
diff --git a/posthog/temporal/data_imports/sources/coingecko/tests/test_coingecko.py b/posthog/temporal/data_imports/sources/coingecko/tests/test_coingecko.py
new file mode 100644
index 000000000000..a138713236af
--- /dev/null
+++ b/posthog/temporal/data_imports/sources/coingecko/tests/test_coingecko.py
@@ -0,0 +1,252 @@
+from typing import Any
+
+import pytest
+from unittest import mock
+
+import requests
+from parameterized import parameterized
+
+from posthog.temporal.data_imports.sources.coingecko import coingecko
+from posthog.temporal.data_imports.sources.coingecko.coingecko import (
+ DEMO_BASE_URL,
+ PAGE_SIZE,
+ PLAN_DEMO,
+ PLAN_PRO,
+ PRO_BASE_URL,
+ CoinGeckoResumeConfig,
+ CoinGeckoRetryableError,
+ _base_url,
+ _build_url,
+ _headers,
+ _is_rate_limited,
+ coingecko_source,
+ get_rows,
+ validate_credentials,
+)
+from posthog.temporal.data_imports.sources.coingecko.settings import COINGECKO_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: CoinGeckoResumeConfig | None = None) -> mock.MagicMock:
+ manager = mock.MagicMock()
+ manager.can_resume.return_value = can_resume
+ manager.load_state.return_value = state
+ return manager
+
+
+class TestBaseUrlAndHeaders:
+ @parameterized.expand(
+ [
+ (PLAN_DEMO, DEMO_BASE_URL),
+ (PLAN_PRO, PRO_BASE_URL),
+ ("anything_else", DEMO_BASE_URL),
+ ]
+ )
+ def test_base_url(self, plan: str, expected: str) -> None:
+ assert _base_url(plan) == expected
+
+ @parameterized.expand(
+ [
+ (PLAN_DEMO, "x-cg-demo-api-key"),
+ (PLAN_PRO, "x-cg-pro-api-key"),
+ ]
+ )
+ def test_headers_use_plan_specific_key_name(self, plan: str, header_name: str) -> None:
+ headers = _headers(plan, "secret-key")
+ assert headers[header_name] == "secret-key"
+ assert headers["Accept"] == "application/json"
+
+ def test_headers_omit_key_when_blank(self) -> None:
+ headers = _headers(PLAN_DEMO, "")
+ assert "x-cg-demo-api-key" not in headers
+
+ def test_build_url_without_params(self) -> None:
+ assert _build_url(DEMO_BASE_URL, "/coins/list", {}) == f"{DEMO_BASE_URL}/coins/list"
+
+ def test_build_url_encodes_params(self) -> None:
+ url = _build_url(DEMO_BASE_URL, "/coins/markets", {"vs_currency": "usd", "per_page": 250, "page": 1})
+ assert url == f"{DEMO_BASE_URL}/coins/markets?vs_currency=usd&per_page=250&page=1"
+
+
+class TestIsRateLimited:
+ @parameterized.expand(
+ [
+ ("http_429", 429, None, True),
+ ("ok_200", 200, [{"id": "btc"}], False),
+ ("body_envelope_429", 200, {"status": {"error_code": 429}}, True),
+ ("body_envelope_other_error", 200, {"status": {"error_code": 10002}}, False),
+ ("non_json_body", 200, ValueError("not json"), False),
+ ]
+ )
+ def test_is_rate_limited(self, _name: str, status: int, body: Any, expected: bool) -> None:
+ assert _is_rate_limited(_FakeResponse(status_code=status, json_data=body)) is expected # type: ignore[arg-type]
+
+
+class TestFetch:
+ @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(CoinGeckoRetryableError):
+ coingecko._fetch(session, "http://x", {}, mock.MagicMock()) # type: ignore[arg-type]
+
+ def test_body_embedded_rate_limit_is_retryable(self) -> None:
+ session = _FakeSession([_FakeResponse(status_code=200, json_data={"status": {"error_code": 429}})])
+ with pytest.raises(CoinGeckoRetryableError):
+ coingecko._fetch(session, "http://x", {}, 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):
+ coingecko._fetch(session, "http://x", {}, mock.MagicMock()) # type: ignore[arg-type]
+
+
+class TestValidateCredentials:
+ @parameterized.expand(
+ [
+ ("valid", 200, True),
+ ("unauthorized", 401, False),
+ ]
+ )
+ @mock.patch("posthog.temporal.data_imports.sources.coingecko.coingecko.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(PLAN_DEMO, "key") is expected
+
+ @mock.patch("posthog.temporal.data_imports.sources.coingecko.coingecko.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(PLAN_PRO, "key") is False
+
+ @mock.patch("posthog.temporal.data_imports.sources.coingecko.coingecko.make_tracked_session")
+ def test_pings_plan_host_with_key(self, mock_session: mock.MagicMock) -> None:
+ get = mock_session.return_value.get
+ get.return_value = _FakeResponse(status_code=200)
+ validate_credentials(PLAN_PRO, "secret")
+ url = get.call_args.args[0]
+ assert url == f"{PRO_BASE_URL}/ping"
+ assert get.call_args.kwargs["headers"]["x-cg-pro-api-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 TestGetRows:
+ def _run(self, endpoint: str, responses: list[_FakeResponse], manager: mock.MagicMock) -> list[list[dict]]:
+ session = _FakeSession(responses)
+ with mock.patch(
+ "posthog.temporal.data_imports.sources.coingecko.coingecko.make_tracked_session", return_value=session
+ ):
+ return list(get_rows(PLAN_DEMO, "key", endpoint, mock.MagicMock(), manager))
+
+ def test_single_request_endpoint_yields_once(self) -> None:
+ manager = _manager()
+ rows = [{"id": "bitcoin", "symbol": "btc", "name": "Bitcoin"}]
+ batches = self._run("coins_list", [_FakeResponse(json_data=rows)], manager)
+ assert batches == [rows]
+ manager.save_state.assert_not_called()
+
+ def test_single_request_empty_yields_nothing(self) -> None:
+ batches = self._run("coins_list", [_FakeResponse(json_data=[])], _manager())
+ assert batches == []
+
+ def test_paginated_walks_until_short_page(self) -> None:
+ manager = _manager()
+ full_page = [{"id": f"c{i}"} for i in range(PAGE_SIZE)]
+ short_page = [{"id": "last"}]
+ batches = self._run(
+ "coins_markets", [_FakeResponse(json_data=full_page), _FakeResponse(json_data=short_page)], manager
+ )
+ assert batches == [full_page, short_page]
+ # State saved once after the first full page so a crash resumes at page 2.
+ manager.save_state.assert_called_once_with(CoinGeckoResumeConfig(page=2))
+
+ def test_paginated_terminates_on_empty_page(self) -> None:
+ manager = _manager()
+ full_page = [{"id": f"c{i}"} for i in range(PAGE_SIZE)]
+ batches = self._run("coins_markets", [_FakeResponse(json_data=full_page), _FakeResponse(json_data=[])], manager)
+ assert batches == [full_page]
+ manager.save_state.assert_called_once_with(CoinGeckoResumeConfig(page=2))
+
+ def test_paginated_resumes_from_saved_page(self) -> None:
+ manager = _manager(can_resume=True, state=CoinGeckoResumeConfig(page=3))
+ short_page = [{"id": "x"}]
+ session = _FakeSession([_FakeResponse(json_data=short_page)])
+ with mock.patch(
+ "posthog.temporal.data_imports.sources.coingecko.coingecko.make_tracked_session", return_value=session
+ ):
+ batches = list(get_rows(PLAN_DEMO, "key", "coins_markets", mock.MagicMock(), manager))
+ assert batches == [short_page]
+ assert "page=3" in session.requested_urls[0]
+
+ def test_paginated_sends_extra_params(self) -> None:
+ manager = _manager()
+ session = _FakeSession([_FakeResponse(json_data=[{"id": "btc"}])])
+ with mock.patch(
+ "posthog.temporal.data_imports.sources.coingecko.coingecko.make_tracked_session", return_value=session
+ ):
+ list(get_rows(PLAN_DEMO, "key", "coins_markets", mock.MagicMock(), manager))
+ assert "vs_currency=usd" in session.requested_urls[0]
+
+ def test_redacts_api_key_in_samples(self) -> None:
+ manager = _manager()
+ session = _FakeSession([_FakeResponse(json_data=[{"id": "btc"}])])
+ with mock.patch(
+ "posthog.temporal.data_imports.sources.coingecko.coingecko.make_tracked_session", return_value=session
+ ) as mock_session:
+ list(get_rows(PLAN_DEMO, "secret", "coins_markets", mock.MagicMock(), manager))
+ # 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 TestCoinGeckoSource:
+ @parameterized.expand(
+ [
+ ("coins_list", ["id"]),
+ ("coins_markets", ["id"]),
+ ("coins_categories", ["id"]),
+ ("coins_categories_list", ["category_id"]),
+ ("exchanges", ["id"]),
+ ("exchanges_list", ["id"]),
+ ("asset_platforms", ["id"]),
+ ]
+ )
+ def test_primary_keys_per_endpoint(self, endpoint: str, expected_keys: list[str]) -> None:
+ response = coingecko_source(PLAN_DEMO, "key", endpoint, mock.MagicMock(), mock.MagicMock())
+ assert response.name == endpoint
+ assert response.primary_keys == expected_keys
+
+ def test_every_settings_endpoint_builds_a_source_response(self) -> None:
+ for endpoint in COINGECKO_ENDPOINTS:
+ response = coingecko_source(PLAN_DEMO, "key", endpoint, mock.MagicMock(), mock.MagicMock())
+ assert response.name == endpoint
+ assert response.primary_keys == COINGECKO_ENDPOINTS[endpoint].primary_keys
diff --git a/posthog/temporal/data_imports/sources/coingecko/tests/test_coingecko_source.py b/posthog/temporal/data_imports/sources/coingecko/tests/test_coingecko_source.py
new file mode 100644
index 000000000000..e4afc1ad3bc2
--- /dev/null
+++ b/posthog/temporal/data_imports/sources/coingecko/tests/test_coingecko_source.py
@@ -0,0 +1,133 @@
+import pytest
+from unittest import mock
+
+from posthog.schema import ReleaseStatus, SourceFieldInputConfig, SourceFieldInputConfigType, SourceFieldSelectConfig
+
+from posthog.temporal.data_imports.sources.coingecko.coingecko import CoinGeckoResumeConfig
+from posthog.temporal.data_imports.sources.coingecko.settings import ENDPOINTS
+from posthog.temporal.data_imports.sources.coingecko.source import CoinGeckoSource
+from posthog.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from posthog.temporal.data_imports.sources.generated_configs import CoinGeckoSourceConfig
+
+from products.data_warehouse.backend.types import ExternalDataSourceType
+
+
+class TestCoinGeckoSource:
+ def setup_method(self) -> None:
+ self.source = CoinGeckoSource()
+ self.team_id = 123
+ self.config = CoinGeckoSourceConfig(api_key="CG-test", plan="demo")
+
+ def test_source_type(self) -> None:
+ assert self.source.source_type == ExternalDataSourceType.COINGECKO
+
+ def test_get_source_config(self) -> None:
+ config = self.source.get_source_config
+
+ assert config.name.value == "CoinGecko"
+ assert config.label == "CoinGecko"
+ assert config.releaseStatus == ReleaseStatus.ALPHA
+ # A finished source is visible — no unreleasedSource flag.
+ assert config.unreleasedSource is None
+ assert config.iconPath == "/static/services/coingecko.png"
+
+ assert [f.name for f in config.fields] == ["plan", "api_key"]
+
+ def test_plan_field_is_select_defaulting_to_demo(self) -> None:
+ plan_field = next(f for f in self.source.get_source_config.fields if f.name == "plan")
+ assert isinstance(plan_field, SourceFieldSelectConfig)
+ assert plan_field.defaultValue == "demo"
+ assert {option.value for option in plan_field.options} == {"demo", "pro"}
+
+ def test_api_key_field_is_secret_password(self) -> None:
+ config = self.source.get_source_config
+ key_field = next(f for f in 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
+
+ @pytest.mark.parametrize(
+ "observed_error",
+ [
+ "401 Client Error: Unauthorized for url: https://api.coingecko.com/api/v3/coins/markets",
+ "401 Client Error: Unauthorized for url: https://pro-api.coingecko.com/api/v3/exchanges",
+ ],
+ )
+ def test_non_retryable_errors_match_auth_failures(self, observed_error: str) -> None:
+ non_retryable_errors = self.source.get_non_retryable_errors()
+ assert any(key in observed_error for key in non_retryable_errors)
+
+ @pytest.mark.parametrize(
+ "other_error",
+ [
+ "429 Client Error: Too Many Requests for url: https://api.coingecko.com/api/v3/coins/list",
+ "500 Server Error for url: https://api.coingecko.com/api/v3/exchanges",
+ ],
+ )
+ def test_non_retryable_errors_does_not_match_transient(self, other_error: str) -> None:
+ non_retryable_errors = self.source.get_non_retryable_errors()
+ assert not any(key in other_error for key in non_retryable_errors)
+
+ def test_get_schemas_covers_all_endpoints_full_refresh_only(self) -> None:
+ schemas = self.source.get_schemas(self.config, self.team_id)
+
+ assert {schema.name for schema in schemas} == set(ENDPOINTS)
+ # CoinGecko's catalog/snapshot endpoints have no server-side timestamp filter.
+ assert all(not schema.supports_incremental for schema in schemas)
+ assert all(not schema.supports_append for schema in schemas)
+
+ def test_get_schemas_filtered_by_names(self) -> None:
+ schemas = self.source.get_schemas(self.config, self.team_id, names=["coins_markets"])
+ assert len(schemas) == 1
+ assert schemas[0].name == "coins_markets"
+
+ 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 CoinGecko API key. Check that the key is correct and that CoinGecko is reachable.",
+ ),
+ ],
+ )
+ @mock.patch("posthog.temporal.data_imports.sources.coingecko.source.validate_coingecko_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("demo", "CG-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 CoinGeckoResumeConfig
+
+ @mock.patch("posthog.temporal.data_imports.sources.coingecko.source.coingecko_source")
+ def test_source_for_pipeline_plumbs_arguments(self, mock_cg_source: mock.MagicMock) -> None:
+ inputs = mock.MagicMock()
+ inputs.schema_name = "coins_markets"
+ manager = mock.MagicMock()
+
+ self.source.source_for_pipeline(self.config, manager, inputs)
+
+ mock_cg_source.assert_called_once()
+ kwargs = mock_cg_source.call_args.kwargs
+ assert kwargs["plan"] == "demo"
+ assert kwargs["api_key"] == "CG-test"
+ assert kwargs["endpoint"] == "coins_markets"
+ assert kwargs["resumable_source_manager"] is manager
+
+ def test_canonical_descriptions_cover_key_endpoints(self) -> None:
+ descriptions = self.source.get_canonical_descriptions()
+ assert "coins_markets" in descriptions
+ assert "current_price" in descriptions["coins_markets"]["columns"]
diff --git a/posthog/temporal/data_imports/sources/generated_configs.py b/posthog/temporal/data_imports/sources/generated_configs.py
index 51c231992757..e5b850c4d155 100644
--- a/posthog/temporal/data_imports/sources/generated_configs.py
+++ b/posthog/temporal/data_imports/sources/generated_configs.py
@@ -730,7 +730,8 @@ class CoinApiSourceConfig(config.Config):
@config.config
class CoinGeckoSourceConfig(config.Config):
- pass
+ api_key: str
+ plan: Literal["demo", "pro"] = config.value(default="demo")
@config.config