: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 coinmarketcap import source (#65618)
Tom Owers194f3dd5e6d0
diff --git a/posthog/temporal/data_imports/sources/SOURCES.md b/posthog/temporal/data_imports/sources/SOURCES.mdindex 5d98a0a8215b..5df2725c0aec 100644--- a/posthog/temporal/data_imports/sources/SOURCES.md+++ b/posthog/temporal/data_imports/sources/SOURCES.md@@ -74,6 +74,7 @@ the row lists both.| checkout_com | HTTP | requests | ✅ || coda | HTTP | requests | ✅ || coingecko | HTTP | requests | ✅ |+| coinmarketcap | HTTP | requests + `rest_source.RESTClient` | ✅ || commercetools | HTTP | requests | ✅ || confluence | HTTP | requests | ✅ || chartmogul | HTTP | requests | ✅ |@@ -343,7 +344,6 @@ doesn't conflict with concurrent PRs.- cockroachdb- codefresh- coin_api-- coinmarketcap- concord- configcat- constant_contactdiff --git a/posthog/temporal/data_imports/sources/coinmarketcap/canonical_descriptions.py b/posthog/temporal/data_imports/sources/coinmarketcap/canonical_descriptions.pynew file mode 100644index 000000000000..5111b026506b--- /dev/null+++ b/posthog/temporal/data_imports/sources/coinmarketcap/canonical_descriptions.py@@ -0,0 +1,81 @@+from posthog.temporal.data_imports.sources.common.canonical_descriptions import CanonicalDescriptions++# Sourced from the official CoinMarketCap API docs (https://coinmarketcap.com/api/documentation/v1/).+CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {+ "cryptocurrency_map": {+ "description": "Mapping of all cryptocurrencies tracked by CoinMarketCap to their CoinMarketCap ID.",+ "docs_url": "https://coinmarketcap.com/api/documentation/v1/#operation/getV1CryptocurrencyMap",+ "columns": {+ "id": "The unique CoinMarketCap ID for this cryptocurrency.",+ "name": "The name of this cryptocurrency.",+ "symbol": "The ticker symbol for this cryptocurrency.",+ "slug": "The web URL friendly shorthand version of this cryptocurrency name.",+ "rank": "The rank of this cryptocurrency by market capitalization.",+ "is_active": "1 if this cryptocurrency has at least one active market currently being tracked, otherwise 0.",+ "first_historical_data": "Timestamp (ISO 8601) of the earliest market data record available for this cryptocurrency.",+ "last_historical_data": "Timestamp (ISO 8601) of the latest market data record available for this cryptocurrency.",+ "platform": "Metadata about the parent cryptocurrency platform this is a token on, if any.",+ },+ },+ "listings_latest": {+ "description": "Latest market data (price, market cap, volume, supply) for all active cryptocurrencies, ranked.",+ "docs_url": "https://coinmarketcap.com/api/documentation/v1/#operation/getV1CryptocurrencyListingsLatest",+ "columns": {+ "id": "The unique CoinMarketCap ID for this cryptocurrency.",+ "name": "The name of this cryptocurrency.",+ "symbol": "The ticker symbol for this cryptocurrency.",+ "slug": "The web URL friendly shorthand version of this cryptocurrency name.",+ "cmc_rank": "The cryptocurrency's CoinMarketCap rank by market cap.",+ "num_market_pairs": "The number of active trading pairs available for this cryptocurrency across exchanges.",+ "circulating_supply": "The approximate number of coins circulating in the market.",+ "total_supply": "The approximate total amount of coins in existence right now (minus any coins verifiably burned).",+ "max_supply": "The expected maximum limit of coins ever to be available for this cryptocurrency.",+ "date_added": "Timestamp (ISO 8601) of when this cryptocurrency was added to CoinMarketCap.",+ "tags": "Tags associated with this cryptocurrency.",+ "platform": "Metadata about the parent cryptocurrency platform this is a token on, if any.",+ "last_updated": "Timestamp (ISO 8601) of when the market data for this cryptocurrency was last updated.",+ "quote": "Market quote in each currency conversion requested (e.g. USD): price, volume, market cap, and percent changes.",+ },+ },+ "categories": {+ "description": "All cryptocurrency categories (e.g. DeFi, NFTs) with aggregate market data.",+ "docs_url": "https://coinmarketcap.com/api/documentation/v1/#operation/getV1CryptocurrencyCategories",+ "columns": {+ "id": "The unique ID of this cryptocurrency category.",+ "name": "The name of this cryptocurrency category.",+ "title": "The title of this cryptocurrency category.",+ "description": "The description of this cryptocurrency category.",+ "num_tokens": "The number of tokens in this cryptocurrency category.",+ "avg_price_change": "The average price change of all tokens in this category over 24 hours.",+ "market_cap": "The market cap of all tokens within this category.",+ "market_cap_change": "The market cap change of all tokens in this category over 24 hours.",+ "volume": "The 24 hour trading volume of all tokens within this category.",+ "volume_change": "The 24 hour trading volume change of all tokens in this category.",+ "last_updated": "Timestamp (ISO 8601) of when this category was last updated.",+ },+ },+ "fiat_map": {+ "description": "All fiat currencies supported by CoinMarketCap for quote conversions.",+ "docs_url": "https://coinmarketcap.com/api/documentation/v1/#operation/getV1FiatMap",+ "columns": {+ "id": "The unique CoinMarketCap ID for this fiat currency.",+ "name": "The name of this fiat currency.",+ "sign": "The currency sign for this fiat currency.",+ "symbol": "The ticker symbol for this fiat currency.",+ },+ },+ "exchange_map": {+ "description": "Mapping of all exchanges tracked by CoinMarketCap to their CoinMarketCap exchange ID.",+ "docs_url": "https://coinmarketcap.com/api/documentation/v1/#operation/getV1ExchangeMap",+ "columns": {+ "id": "The unique CoinMarketCap ID for this exchange.",+ "name": "The name of this exchange.",+ "slug": "The web URL friendly shorthand version of this exchange name.",+ "is_active": "1 if this exchange is still being actively tracked and updated, otherwise 0.",+ "is_listed": "1 if this exchange is listed (ranked) by CoinMarketCap, otherwise 0.",+ "is_redistributable": "1 if this exchange's data is available for redistribution per CoinMarketCap licensing, otherwise 0.",+ "first_historical_data": "Timestamp (ISO 8601) of the earliest market data record available for this exchange.",+ "last_historical_data": "Timestamp (ISO 8601) of the latest market data record available for this exchange.",+ },+ },+}diff --git a/posthog/temporal/data_imports/sources/coinmarketcap/coinmarketcap.py b/posthog/temporal/data_imports/sources/coinmarketcap/coinmarketcap.pynew file mode 100644index 000000000000..012bd25ce05a--- /dev/null+++ b/posthog/temporal/data_imports/sources/coinmarketcap/coinmarketcap.py@@ -0,0 +1,155 @@+import dataclasses+from typing import Any, Optional++from posthog.temporal.data_imports.pipelines.pipeline.typings import SourceResponse+from posthog.temporal.data_imports.sources.coinmarketcap.settings import COINMARKETCAP_ENDPOINTS, PAGE_SIZE+from posthog.temporal.data_imports.sources.common.http import make_tracked_session+from posthog.temporal.data_imports.sources.common.rest_source import RESTAPIConfig, rest_api_resource+from posthog.temporal.data_imports.sources.common.rest_source.paginators import OffsetPaginator+from posthog.temporal.data_imports.sources.common.rest_source.typing import EndpointResource+from posthog.temporal.data_imports.sources.common.resumable import ResumableSourceManager++# All requests go to CoinMarketCap's Pro API host.+COINMARKETCAP_BASE_URL = "https://pro-api.coinmarketcap.com"++# Header CoinMarketCap recommends for passing the Pro API key (over the query-string form).+API_KEY_HEADER = "X-CMC_PRO_API_KEY"+++class CoinMarketCapResumeConfig:+ start: int+++class CoinMarketCapPaginator(OffsetPaginator):+ """1-based offset/limit paginator with resume support.++ CoinMarketCap's list endpoints page on `start` (1-based) and `limit`. They don't+ return a usable total in the response, and an out-of-range `start` returns an empty+ `data` list with HTTP 200, so empty-/short-page detection is the reliable stop+ condition (`total_path=None`).+ """++ def __init__(self) -> None:+ super().__init__(+ limit=PAGE_SIZE,+ offset=1, # `start` is 1-based; start=0 is rejected with a 400.+ offset_param="start",+ limit_param="limit",+ total_path=None,+ )++ def get_resume_state(self) -> Optional[dict[str, Any]]:+ if self._has_next_page:+ return {"start": self.offset}+ return None++ def set_resume_state(self, state: dict[str, Any]) -> None:+ start = state.get("start")+ if start is not None:+ self.offset = int(start)+ self._has_next_page = True+++def get_resource(endpoint: str) -> EndpointResource:+ config = COINMARKETCAP_ENDPOINTS[endpoint]+ return {+ "name": config.name,+ "table_name": config.name,+ "write_disposition": "replace",+ "endpoint": {+ "data_selector": config.data_selector,+ "path": config.path,+ "params": dict(config.extra_params),+ },+ "table_format": "delta",+ }+++def coinmarketcap_source(+ api_key: str,+ endpoint: str,+ team_id: int,+ job_id: str,+ resumable_source_manager: ResumableSourceManager[CoinMarketCapResumeConfig],+) -> SourceResponse:+ endpoint_config = COINMARKETCAP_ENDPOINTS[endpoint]++ rest_config: RESTAPIConfig = {+ "client": {+ "base_url": COINMARKETCAP_BASE_URL,+ # Going through APIKeyAuth (rather than raw headers) registers the key+ # for value-based log redaction.+ "auth": {+ "type": "api_key",+ "api_key": api_key,+ "name": API_KEY_HEADER,+ "location": "header",+ },+ "paginator": CoinMarketCapPaginator(),+ # CoinMarketCap's API responds directly, so there's no legitimate redirect+ # to follow; pinning it off keeps traffic on the validated host.+ "session": make_tracked_session(redact_values=(api_key,), allow_redirects=False),+ },+ "resource_defaults": {+ "write_disposition": "replace",+ },+ "resources": [get_resource(endpoint)],+ }++ initial_paginator_state: Optional[dict[str, Any]] = None+ if resumable_source_manager.can_resume():+ resume_config = resumable_source_manager.load_state()+ if resume_config is not None:+ initial_paginator_state = {"start": resume_config.start}++ def save_checkpoint(state: Optional[dict[str, Any]]) -> None:+ # Persist only when there's a next page to resume to; the Redis TTL handles+ # cleanup once the sync finishes. Saving happens after each page is yielded,+ # so a crash re-fetches the last page rather than skipping it.+ if state and state.get("start") is not None:+ resumable_source_manager.save_state(CoinMarketCapResumeConfig(start=int(state["start"])))++ resource = rest_api_resource(+ rest_config,+ team_id,+ job_id,+ db_incremental_field_last_value=None,+ resume_hook=save_checkpoint,+ initial_paginator_state=initial_paginator_state,+ )++ return SourceResponse(+ name=endpoint,+ items=lambda: resource,+ primary_keys=["id"],+ partition_count=1,+ partition_size=1,+ partition_mode="datetime" if endpoint_config.partition_key else None,+ partition_format="week" if endpoint_config.partition_key else None,+ partition_keys=[endpoint_config.partition_key] if endpoint_config.partition_key else None,+ sort_mode="asc",+ )+++def validate_credentials(api_key: str) -> tuple[bool, str | None]:+ """Probe the zero-credit `/v1/key/info` endpoint to confirm the key is genuine.++ Returns (is_valid, error_message). A 200 means the key authenticates; 401 means it's+ missing or invalid. Any other status / network error is surfaced verbatim.+ """+ try:+ response = make_tracked_session(redact_values=(api_key,)).get(+ f"{COINMARKETCAP_BASE_URL}/v1/key/info",+ headers={API_KEY_HEADER: api_key},+ timeout=10,+ allow_redirects=False,+ )+ except Exception as e:+ return False, str(e)++ if response.status_code == 200:+ return True, None+ if response.status_code == 401:+ return False, "Invalid CoinMarketCap API key"+ return False, f"CoinMarketCap returned an unexpected status code: {response.status_code}"diff --git a/posthog/temporal/data_imports/sources/coinmarketcap/settings.py b/posthog/temporal/data_imports/sources/coinmarketcap/settings.pynew file mode 100644index 000000000000..5a5e78dc9bcd--- /dev/null+++ b/posthog/temporal/data_imports/sources/coinmarketcap/settings.py@@ -0,0 +1,76 @@+from dataclasses import dataclass, field+from typing import Optional++from products.data_warehouse.backend.types import IncrementalField++# CoinMarketCap caps `limit` at 5000 records per page across its list endpoints.+# A larger page size means fewer HTTP calls (kinder to the per-minute rate limit);+# the monthly credit cost is per data point, so it's unaffected by page size.+PAGE_SIZE = 5000+++@dataclass+class CoinMarketCapEndpointConfig:+ name: str+ # Path on https://pro-api.coinmarketcap.com (e.g. "/v1/cryptocurrency/map").+ path: str+ # JSONPath to the list of records in the response body. Every CoinMarketCap+ # endpoint we sync wraps its collection under the top-level "data" key.+ data_selector: str = "data"+ # Stable created-style datetime field to partition by, or None to skip+ # partitioning. Only set where the field is reliably present on every row.+ partition_key: Optional[str] = None+ # Extra query params merged into every request for this endpoint (e.g. a+ # stable `sort` field for deterministic offset pagination).+ extra_params: dict[str, str] = field(default_factory=dict)+++# CoinMarketCap's REST API wraps each collection under a top-level "data" key and+# shares 1-based `start`/`limit` offset pagination across list endpoints. All of+# these are "latest"/"map" snapshots with no server-side timestamp filter, so they+# are full refresh only (see INCREMENTAL_FIELDS below).+COINMARKETCAP_ENDPOINTS: dict[str, CoinMarketCapEndpointConfig] = {+ # Static-ish map of every active cryptocurrency tracked by CoinMarketCap.+ "cryptocurrency_map": CoinMarketCapEndpointConfig(+ name="cryptocurrency_map",+ path="/v1/cryptocurrency/map",+ partition_key="first_historical_data",+ # `sort=id` gives a stable order so offset pages don't skip/duplicate rows+ # as the listing shifts during a sync.+ extra_params={"sort": "id"},+ ),+ # Latest market data (price, market cap, volume, supply) for all active coins.+ "listings_latest": CoinMarketCapEndpointConfig(+ name="listings_latest",+ path="/v1/cryptocurrency/listings/latest",+ partition_key="date_added",+ # `date_added` is a stable per-coin field; sorting by it keeps offset+ # pagination deterministic (the default `market_cap` reorders mid-sync).+ extra_params={"sort": "date_added", "sort_dir": "asc"},+ ),+ # All cryptocurrency categories (DeFi, NFTs, etc.) with aggregate market data.+ "categories": CoinMarketCapEndpointConfig(+ name="categories",+ path="/v1/cryptocurrency/categories",+ ),+ # All fiat currencies CoinMarketCap supports for quote conversions.+ "fiat_map": CoinMarketCapEndpointConfig(+ name="fiat_map",+ path="/v1/fiat/map",+ extra_params={"sort": "id"},+ ),+ # All exchanges tracked by CoinMarketCap (availability depends on plan tier).+ "exchange_map": CoinMarketCapEndpointConfig(+ name="exchange_map",+ path="/v1/exchange/map",+ extra_params={"sort": "id"},+ ),+}++ENDPOINTS = tuple(COINMARKETCAP_ENDPOINTS.keys())++# Full refresh only. CoinMarketCap's "latest"/"map" endpoints reflect current state+# with no `since`/`updated_after`-style server-side filter, so an "incremental" sync+# would re-fetch every page anyway. Historical endpoints expose `time_start`/`time_end`+# windows, but they're gated behind higher paid tiers, so they aren't synced here.+INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {}diff --git a/posthog/temporal/data_imports/sources/coinmarketcap/source.py b/posthog/temporal/data_imports/sources/coinmarketcap/source.pyindex 312282b58f37..b5331ea5347d 100644--- a/posthog/temporal/data_imports/sources/coinmarketcap/source.py+++ b/posthog/temporal/data_imports/sources/coinmarketcap/source.py@@ -1,20 +1,33 @@-from typing import cast+from typing import Optional, castfrom posthog.schema import (DataWarehouseSourceCategory,ExternalDataSourceType as SchemaExternalDataSourceType,+ ReleaseStatus,SourceConfig,+ SourceFieldInputConfig,+ SourceFieldInputConfigType,)-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.coinmarketcap.coinmarketcap import (+ CoinMarketCapResumeConfig,+ coinmarketcap_source,+ validate_credentials as validate_coinmarketcap_credentials,+)+from posthog.temporal.data_imports.sources.coinmarketcap.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 CanonicalDescriptionsfrom 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 SourceSchemafrom posthog.temporal.data_imports.sources.generated_configs import CoinMarketCapSourceConfigfrom products.data_warehouse.backend.types import ExternalDataSourceType@SourceRegistry.register-class CoinMarketCapSource(SimpleSource[CoinMarketCapSourceConfig]):+class CoinMarketCapSource(ResumableSource[CoinMarketCapSourceConfig, CoinMarketCapResumeConfig]):@propertydef source_type(self) -> ExternalDataSourceType:return ExternalDataSourceType.COINMARKETCAP@@ -25,7 +38,84 @@ class CoinMarketCapSource(SimpleSource[CoinMarketCapSourceConfig]):name=SchemaExternalDataSourceType.COIN_MARKET_CAP,category=DataWarehouseSourceCategory.FINANCE___ACCOUNTING,label="CoinMarketCap",+ releaseStatus=ReleaseStatus.ALPHA,+ caption="""Enter your CoinMarketCap Pro API key to sync cryptocurrency and market data into the PostHog Data warehouse.++Create a key from your [CoinMarketCap developer dashboard](https://pro.coinmarketcap.com/account). The key grants read access to every endpoint listed below; some (e.g. exchanges) require a higher plan tier.""",iconPath="/static/services/coinmarketcap.png",- fields=cast(list[FieldType], []),+ docsUrl="https://posthog.com/docs/cdp/sources/coinmarketcap",+ # Kept hidden from the new-source wizard for now; flip this off to release.unreleasedSource=True,+ fields=cast(+ list[FieldType],+ [+ SourceFieldInputConfig(+ name="api_key",+ label="API key",+ type=SourceFieldInputConfigType.PASSWORD,+ required=True,+ placeholder="",+ secret=True,+ ),+ ],+ ),+ )++ def get_canonical_descriptions(self) -> CanonicalDescriptions:+ from posthog.temporal.data_imports.sources.coinmarketcap.canonical_descriptions import ( # noqa: PLC0415+ CANONICAL_DESCRIPTIONS,+ )++ return CANONICAL_DESCRIPTIONS++ def get_non_retryable_errors(self) -> dict[str, str | None]:+ return {+ # A missing or invalid Pro API key surfaces as a 401 when the pipeline calls+ # `raise_for_status()`. Retrying can never satisfy a credential problem.+ "401 Client Error": "Your CoinMarketCap API key is invalid or has been revoked. Create a new key in your CoinMarketCap developer dashboard, then reconnect.",+ "Unauthorized for url": "Your CoinMarketCap API key is invalid or has been revoked. Create a new key in your CoinMarketCap developer dashboard, then reconnect.",+ }++ def get_schemas(+ self,+ config: CoinMarketCapSourceConfig,+ team_id: int,+ with_counts: bool = False,+ names: list[str] | None = None,+ force_refresh: bool = False,+ ) -> list[SourceSchema]:+ schemas = [+ SourceSchema(+ name=endpoint,+ supports_incremental=(fields := INCREMENTAL_FIELDS.get(endpoint)) is not None,+ supports_append=fields is not None,+ incremental_fields=fields or [],+ )+ 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: CoinMarketCapSourceConfig, team_id: int, schema_name: Optional[str] = None+ ) -> tuple[bool, str | None]:+ return validate_coinmarketcap_credentials(config.api_key)++ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[CoinMarketCapResumeConfig]:+ return ResumableSourceManager[CoinMarketCapResumeConfig](inputs, CoinMarketCapResumeConfig)++ def source_for_pipeline(+ self,+ config: CoinMarketCapSourceConfig,+ resumable_source_manager: ResumableSourceManager[CoinMarketCapResumeConfig],+ inputs: SourceInputs,+ ) -> SourceResponse:+ return coinmarketcap_source(+ api_key=config.api_key,+ endpoint=inputs.schema_name,+ team_id=inputs.team_id,+ job_id=inputs.job_id,+ resumable_source_manager=resumable_source_manager,)diff --git a/posthog/temporal/data_imports/sources/coinmarketcap/tests/test_coinmarketcap.py b/posthog/temporal/data_imports/sources/coinmarketcap/tests/test_coinmarketcap.pynew file mode 100644index 000000000000..e6bd89df6d96--- /dev/null+++ b/posthog/temporal/data_imports/sources/coinmarketcap/tests/test_coinmarketcap.py@@ -0,0 +1,250 @@+import json+from collections.abc import Iterable+from typing import Any, cast++import pytest+from unittest.mock import MagicMock, patch++from requests import Request, Response++from posthog.temporal.data_imports.sources.coinmarketcap.coinmarketcap import (+ API_KEY_HEADER,+ CoinMarketCapPaginator,+ CoinMarketCapResumeConfig,+ coinmarketcap_source,+ get_resource,+ validate_credentials,+)+from posthog.temporal.data_imports.sources.coinmarketcap.settings import COINMARKETCAP_ENDPOINTS, ENDPOINTS, PAGE_SIZE+from posthog.temporal.data_imports.sources.common.resumable import ResumableSourceManager+++def _full_page() -> list[dict[str, Any]]:+ return [{"id": i} for i in range(PAGE_SIZE)]+++class TestCoinMarketCapPaginator:+ def test_initial_state_is_one_based(self) -> None:+ paginator = CoinMarketCapPaginator()+ # CoinMarketCap's `start` is 1-based; start=0 is rejected with a 400.+ assert paginator.offset == 1+ assert paginator.limit == PAGE_SIZE+ assert paginator.has_next_page is True++ def test_init_request_emits_start_and_limit(self) -> None:+ paginator = CoinMarketCapPaginator()+ request = Request(method="GET", url="https://pro-api.coinmarketcap.com/v1/cryptocurrency/map")+ paginator.init_request(request)+ assert request.params["start"] == 1+ assert request.params["limit"] == PAGE_SIZE++ def test_advances_start_by_limit_on_full_page(self) -> None:+ paginator = CoinMarketCapPaginator()+ paginator.update_state(MagicMock(), _full_page())+ assert paginator.offset == 1 + PAGE_SIZE+ assert paginator.has_next_page is True++ def test_stops_on_short_page(self) -> None:+ paginator = CoinMarketCapPaginator()+ paginator.update_state(MagicMock(), [{"id": 1}])+ assert paginator.has_next_page is False++ def test_stops_on_empty_page(self) -> None:+ # An out-of-range `start` returns an empty `data` list with HTTP 200.+ paginator = CoinMarketCapPaginator()+ paginator.update_state(MagicMock(), [])+ assert paginator.has_next_page is False++ def test_get_resume_state_when_next_page(self) -> None:+ paginator = CoinMarketCapPaginator()+ paginator.update_state(MagicMock(), _full_page())+ assert paginator.get_resume_state() == {"start": 1 + PAGE_SIZE}++ def test_get_resume_state_none_on_terminal_page(self) -> None:+ paginator = CoinMarketCapPaginator()+ paginator.update_state(MagicMock(), [])+ assert paginator.get_resume_state() is None++ def test_set_resume_state_round_trip(self) -> None:+ paginator = CoinMarketCapPaginator()+ paginator.set_resume_state({"start": 5001})+ assert paginator.offset == 5001+ assert paginator.has_next_page is True++ request = Request(method="GET", url="https://pro-api.coinmarketcap.com/v1/cryptocurrency/map")+ paginator.init_request(request)+ assert request.params["start"] == 5001++ def test_set_resume_state_ignores_missing_start(self) -> None:+ paginator = CoinMarketCapPaginator()+ paginator.set_resume_state({})+ assert paginator.offset == 1+++class TestGetResource:+ @pytest.mark.parametrize("endpoint", list(ENDPOINTS))+ def test_resource_shape(self, endpoint: str) -> None:+ resource = get_resource(endpoint)+ config = COINMARKETCAP_ENDPOINTS[endpoint]++ assert resource["name"] == endpoint+ assert resource["table_name"] == endpoint+ assert resource["write_disposition"] == "replace"+ assert resource["table_format"] == "delta"++ endpoint_def = cast(dict[str, Any], resource["endpoint"])+ assert endpoint_def["path"] == config.path+ assert endpoint_def["path"].startswith("/v1/")+ assert endpoint_def["data_selector"] == "data"++ @pytest.mark.parametrize("endpoint", ["cryptocurrency_map", "listings_latest", "fiat_map", "exchange_map"])+ def test_paginated_endpoints_pass_a_stable_sort(self, endpoint: str) -> None:+ # A stable `sort` keeps offset pagination from skipping/duplicating rows mid-sync.+ endpoint_def = cast(dict[str, Any], get_resource(endpoint)["endpoint"])+ assert "sort" in endpoint_def["params"]+++def _make_http_response(body: dict[str, Any], status_code: int = 200) -> Response:+ resp = Response()+ resp.status_code = status_code+ resp._content = json.dumps(body).encode()+ resp.headers["Content-Type"] = "application/json"+ return resp+++class TestCoinMarketCapSourceResumeBehavior:+ """End-to-end resume behaviour of ``coinmarketcap_source`` via ``rest_api_resource``."""++ def _drive(+ self, endpoint: str, manager: MagicMock, responses: list[Response]+ ) -> tuple[MagicMock, list[dict[str, Any]]]:+ sent_params: list[dict[str, Any]] = []+ response_iter = iter(responses)++ def fake_send(request: Any, *_args: Any, **_kwargs: Any) -> Response:+ sent_params.append(dict(request.params or {}))+ return next(response_iter)++ with patch(+ "posthog.temporal.data_imports.sources.coinmarketcap.coinmarketcap.make_tracked_session"+ ) as MockSession:+ mock_session = MockSession.return_value+ mock_session.headers = {}+ mock_session.prepare_request.side_effect = lambda req: req+ mock_session.send.side_effect = fake_send++ source = coinmarketcap_source(+ api_key="test-key",+ endpoint=endpoint,+ team_id=123,+ job_id="test_job",+ resumable_source_manager=manager,+ )+ list(cast(Iterable[Any], source.items()))+ return mock_session, sent_params++ def _page_body(self, items: list[dict[str, Any]]) -> dict[str, Any]:+ return {"data": items, "status": {"error_code": 0, "error_message": None}}++ @pytest.mark.parametrize("endpoint", ["cryptocurrency_map", "listings_latest", "fiat_map"])+ def test_fresh_run_saves_start_after_each_non_terminal_page(self, endpoint: str) -> None:+ manager = MagicMock(spec=ResumableSourceManager)+ manager.can_resume.return_value = False++ responses = [+ _make_http_response(self._page_body(_full_page())),+ _make_http_response(self._page_body([{"id": "x"}])),+ ]+ _, sent_params = self._drive(endpoint, manager, responses)++ # First request starts at 1; the second carries the advanced start.+ assert [p.get("start") for p in sent_params] == [1, 1 + PAGE_SIZE]++ saved = [call.args[0] for call in manager.save_state.call_args_list]+ assert saved == [CoinMarketCapResumeConfig(start=1 + PAGE_SIZE)]++ def test_resume_seeds_paginator_with_saved_start(self) -> None:+ manager = MagicMock(spec=ResumableSourceManager)+ manager.can_resume.return_value = True+ manager.load_state.return_value = CoinMarketCapResumeConfig(start=1 + PAGE_SIZE)++ responses = [+ _make_http_response(self._page_body([{"id": "resumed"}])),+ ]+ _, sent_params = self._drive("cryptocurrency_map", manager, responses)++ assert [p.get("start") for p in sent_params] == [1 + PAGE_SIZE]+ manager.load_state.assert_called_once()++ def test_terminal_single_page_does_not_save_state(self) -> None:+ manager = MagicMock(spec=ResumableSourceManager)+ manager.can_resume.return_value = False++ responses = [+ _make_http_response(self._page_body([{"id": "only"}])),+ ]+ self._drive("cryptocurrency_map", manager, responses)++ manager.save_state.assert_not_called()++ def test_does_not_load_state_when_cannot_resume(self) -> None:+ manager = MagicMock(spec=ResumableSourceManager)+ manager.can_resume.return_value = False++ responses = [+ _make_http_response(self._page_body([{"id": "a"}])),+ ]+ self._drive("cryptocurrency_map", manager, responses)++ manager.load_state.assert_not_called()+++class TestValidateCredentials:+ @pytest.mark.parametrize(+ ("status_code", "expected_valid"),+ [+ (200, True),+ (401, False),+ (429, False),+ (500, False),+ ],+ )+ def test_status_code_mapping(self, status_code: int, expected_valid: bool) -> None:+ with patch(+ "posthog.temporal.data_imports.sources.coinmarketcap.coinmarketcap.make_tracked_session"+ ) as MockSession:+ mock_session = MockSession.return_value+ response = MagicMock()+ response.status_code = status_code+ mock_session.get.return_value = response++ valid, error = validate_credentials("test-key")+ assert valid is expected_valid+ if expected_valid:+ assert error is None+ else:+ assert error is not None++ def test_sends_key_in_header(self) -> None:+ with patch(+ "posthog.temporal.data_imports.sources.coinmarketcap.coinmarketcap.make_tracked_session"+ ) as MockSession:+ mock_session = MockSession.return_value+ response = MagicMock()+ response.status_code = 200+ mock_session.get.return_value = response++ validate_credentials("test-key")++ headers = mock_session.get.call_args.kwargs["headers"]+ assert headers[API_KEY_HEADER] == "test-key"+ assert mock_session.get.call_args.kwargs["allow_redirects"] is False++ def test_network_error_returns_message(self) -> None:+ with patch(+ "posthog.temporal.data_imports.sources.coinmarketcap.coinmarketcap.make_tracked_session"+ ) as MockSession:+ MockSession.return_value.get.side_effect = Exception("boom")+ valid, error = validate_credentials("test-key")+ assert valid is False+ assert error == "boom"diff --git a/posthog/temporal/data_imports/sources/coinmarketcap/tests/test_coinmarketcap_source.py b/posthog/temporal/data_imports/sources/coinmarketcap/tests/test_coinmarketcap_source.pynew file mode 100644index 000000000000..3ef828dbacbe--- /dev/null+++ b/posthog/temporal/data_imports/sources/coinmarketcap/tests/test_coinmarketcap_source.py@@ -0,0 +1,132 @@+from typing import Any++import pytest+from unittest import mock++from posthog.schema import ReleaseStatus, SourceFieldInputConfig, SourceFieldInputConfigType++from posthog.temporal.data_imports.pipelines.pipeline.typings import SourceInputs+from posthog.temporal.data_imports.sources.coinmarketcap.coinmarketcap import CoinMarketCapResumeConfig+from posthog.temporal.data_imports.sources.coinmarketcap.settings import ENDPOINTS+from posthog.temporal.data_imports.sources.coinmarketcap.source import CoinMarketCapSource+from posthog.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from posthog.temporal.data_imports.sources.generated_configs import CoinMarketCapSourceConfig++from products.data_warehouse.backend.types import ExternalDataSourceType+++def _make_inputs(**overrides: Any) -> SourceInputs:+ defaults: dict[str, Any] = {+ "schema_name": "listings_latest",+ "schema_id": "schema-1",+ "source_id": "source-1",+ "team_id": 123,+ "should_use_incremental_field": False,+ "db_incremental_field_last_value": None,+ "db_incremental_field_earliest_value": None,+ "incremental_field": None,+ "incremental_field_type": None,+ "job_id": "job-1",+ "logger": mock.MagicMock(),+ "reset_pipeline": False,+ }+ defaults.update(overrides)+ return SourceInputs(**defaults)+++class TestCoinMarketCapSource:+ def setup_method(self) -> None:+ self.source = CoinMarketCapSource()+ self.team_id = 123+ self.config = CoinMarketCapSourceConfig(api_key="test-key")++ def test_source_type(self) -> None:+ assert self.source.source_type == ExternalDataSourceType.COINMARKETCAP++ def test_get_source_config(self) -> None:+ config = self.source.get_source_config++ assert config.name.value == "CoinMarketCap"+ assert config.label == "CoinMarketCap"+ # Shipped hidden behind unreleasedSource for now, labelled alpha.+ assert config.unreleasedSource is True+ assert config.releaseStatus == ReleaseStatus.ALPHA+ assert config.iconPath == "/static/services/coinmarketcap.png"++ assert len(config.fields) == 1+ (api_key_field,) = config.fields+ assert isinstance(api_key_field, SourceFieldInputConfig)+ assert api_key_field.name == "api_key"+ assert api_key_field.type == SourceFieldInputConfigType.PASSWORD+ assert api_key_field.required is True+ assert api_key_field.secret is True++ @pytest.mark.parametrize("expected_key", ["401 Client Error", "Unauthorized for url"])+ def test_non_retryable_errors(self, expected_key: str) -> None:+ assert expected_key in self.source.get_non_retryable_errors()++ def test_get_schemas_all_full_refresh(self) -> None:+ schemas = self.source.get_schemas(self.config, self.team_id)++ assert {s.name for s in schemas} == set(ENDPOINTS)+ # Every CoinMarketCap "latest"/"map" endpoint is a current-state snapshot with no+ # server-side timestamp filter, so all schemas are full refresh only.+ assert all(not s.supports_incremental for s in schemas)+ assert all(not s.supports_append for s in schemas)+ assert all(s.incremental_fields == [] for s in schemas)++ def test_get_schemas_filtered_by_names(self) -> None:+ schemas = self.source.get_schemas(self.config, self.team_id, names=["fiat_map"])+ assert len(schemas) == 1+ assert schemas[0].name == "fiat_map"++ def test_get_schemas_unknown_name_returns_empty(self) -> None:+ assert self.source.get_schemas(self.config, self.team_id, names=["nonexistent"]) == []++ def test_canonical_descriptions_cover_every_endpoint(self) -> None:+ descriptions = self.source.get_canonical_descriptions()+ # Every advertised endpoint should have a curated description so it isn't sent to the LLM.+ assert set(descriptions.keys()) == set(ENDPOINTS)++ @pytest.mark.parametrize(+ ("mock_return", "expected_valid", "expected_message"),+ [+ ((True, None), True, None),+ ((False, "Invalid CoinMarketCap API key"), False, "Invalid CoinMarketCap API key"),+ ],+ )+ @mock.patch("posthog.temporal.data_imports.sources.coinmarketcap.source.validate_coinmarketcap_credentials")+ def test_validate_credentials(+ self,+ mock_validate: mock.MagicMock,+ mock_return: tuple[bool, str | None],+ 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(self.config.api_key)++ def test_get_resumable_source_manager_bound_to_resume_config(self) -> None:+ manager = self.source.get_resumable_source_manager(_make_inputs())+ assert isinstance(manager, ResumableSourceManager)+ assert manager._data_class is CoinMarketCapResumeConfig++ @mock.patch("posthog.temporal.data_imports.sources.coinmarketcap.source.coinmarketcap_source")+ def test_source_for_pipeline_plumbs_arguments(self, mock_source: mock.MagicMock) -> None:+ inputs = _make_inputs(schema_name="cryptocurrency_map", team_id=99, job_id="job-xyz")+ manager = mock.MagicMock(spec=ResumableSourceManager)++ self.source.source_for_pipeline(self.config, manager, inputs)++ mock_source.assert_called_once_with(+ api_key="test-key",+ endpoint="cryptocurrency_map",+ team_id=99,+ job_id="job-xyz",+ resumable_source_manager=manager,+ )diff --git a/posthog/temporal/data_imports/sources/generated_configs.py b/posthog/temporal/data_imports/sources/generated_configs.pyindex 57219ecaa929..af40cc9b8e5a 100644--- a/posthog/temporal/data_imports/sources/generated_configs.py+++ b/posthog/temporal/data_imports/sources/generated_configs.py@@ -747,7 +747,7 @@ class CoinGeckoSourceConfig(config.Config):@config.configclass CoinMarketCapSourceConfig(config.Config):- pass+ api_key: str@config.config