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): add CDC Open Data import source (#84327)

Tom Owers82bf10a496f1
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/cdc_open_data/cdc_open_data.py b/products/warehouse_sources/backend/temporal/data_imports/sources/cdc_open_data/cdc_open_data.py
new file mode 100644
index 000000000000..5756bf7a734b
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/cdc_open_data/cdc_open_data.py
@@ -0,0 +1,162 @@
+import dataclasses
+from datetime import UTC, date, datetime
+from typing import Any, Optional
+from urllib.parse import urlencode
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.cdc_open_data.settings import (
+ CDC_BASE_URL,
+ PAGE_SIZE,
+ SOCRATA_ID_FIELD,
+ SOCRATA_UPDATED_AT_FIELD,
+)
+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.rest_source import (
+ ClientConfig,
+ EndpointResource,
+ RESTAPIConfig,
+ rest_api_resource,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.paginators import (
+ OffsetPaginator,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.typing import AuthConfig
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.source_helpers import validate_via_probe
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceResponse
+
+APP_TOKEN_HEADER = "X-App-Token"
+
+
[email protected](frozen=False)
+class CdcOpenDataResumeConfig:
+ next_offset: int
+
+
+def _format_where_value(value: Any) -> str:
+ """Format an incremental cursor value for a Socrata `$where` timestamp comparison."""
+ if isinstance(value, datetime):
+ utc_dt = value.replace(tzinfo=UTC) if value.tzinfo is None else value.astimezone(UTC)
+ return utc_dt.strftime("%Y-%m-%dT%H:%M:%S")
+ if isinstance(value, date):
+ return value.strftime("%Y-%m-%dT00:00:00")
+ return str(value)
+
+
+def _auth_config(app_token: str) -> Optional[AuthConfig]:
+ if not app_token:
+ return None
+ return {"type": "api_key", "api_key": app_token, "name": APP_TOKEN_HEADER, "location": "header"}
+
+
+def _probe_url(dataset_id: str) -> str:
+ return f"{CDC_BASE_URL}/resource/{dataset_id}.json?{urlencode({'$limit': 1})}"
+
+
+def cdc_open_data_source(
+ dataset_id: str,
+ app_token: str,
+ team_id: int,
+ job_id: str,
+ resumable_source_manager: ResumableSourceManager[CdcOpenDataResumeConfig],
+ should_use_incremental_field: bool,
+ db_incremental_field_last_value: Optional[Any],
+) -> SourceResponse:
+ params: dict[str, Any] = {
+ # Every dataset's own columns vary, but every dataset carries these Socrata system
+ # fields; requesting them explicitly (rather than relying on a version-specific
+ # `$select`) works across SODA 2.0/2.1 alike.
+ "$$exclude_system_fields": "false",
+ "$order": f"{SOCRATA_UPDATED_AT_FIELD},{SOCRATA_ID_FIELD}"
+ if should_use_incremental_field
+ else SOCRATA_ID_FIELD,
+ }
+ if should_use_incremental_field and db_incremental_field_last_value is not None:
+ formatted_value = _format_where_value(db_incremental_field_last_value)
+ params["$where"] = f"{SOCRATA_UPDATED_AT_FIELD} > '{formatted_value}'"
+
+ paginator = OffsetPaginator(
+ limit=PAGE_SIZE,
+ offset_param="$offset",
+ limit_param="$limit",
+ total_path=None,
+ )
+
+ 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 = {"offset": resume_config.next_offset}
+
+ def save_checkpoint(state: Optional[dict[str, Any]]) -> None:
+ offset = state.get("offset") if state else None
+ if offset is not None:
+ resumable_source_manager.save_state(CdcOpenDataResumeConfig(next_offset=int(offset)))
+
+ client: ClientConfig = {
+ "base_url": CDC_BASE_URL,
+ "paginator": paginator,
+ }
+ auth = _auth_config(app_token)
+ if auth is not None:
+ client["auth"] = auth
+
+ resource_config: EndpointResource = {
+ "name": dataset_id,
+ "write_disposition": {"disposition": "merge", "strategy": "upsert"}
+ if should_use_incremental_field
+ else "replace",
+ "endpoint": {
+ "path": f"/resource/{dataset_id}.json",
+ "params": params,
+ # A dataset endpoint always returns a bare JSON array; a non-list body means a
+ # transient/error payload rather than zero rows.
+ "data_selector_required": True,
+ },
+ "table_format": "delta",
+ }
+ config: RESTAPIConfig = {
+ "client": client,
+ "resources": [resource_config],
+ }
+
+ resource = rest_api_resource(
+ config,
+ team_id,
+ job_id,
+ None,
+ resume_hook=save_checkpoint,
+ initial_paginator_state=initial_paginator_state,
+ )
+
+ return SourceResponse(
+ name=dataset_id,
+ items=lambda: resource,
+ primary_keys=[SOCRATA_ID_FIELD],
+ column_hints=resource.column_hints,
+ sort_mode="asc",
+ )
+
+
+def validate_cdc_open_data_credentials(app_token: str, dataset_id: str) -> tuple[bool, str | None]:
+ """Probe one dataset's resource endpoint to confirm it exists and the app token (if any) is valid."""
+ headers = {APP_TOKEN_HEADER: app_token} if app_token else None
+ ok, status = validate_via_probe(
+ lambda: make_tracked_session(redact_values=(app_token,) if app_token else ()),
+ _probe_url(dataset_id),
+ headers=headers,
+ )
+ if ok:
+ return True, None
+ if status == 404:
+ return (
+ False,
+ f"Dataset '{dataset_id}' was not found on data.cdc.gov. Check the dataset ID in its data.cdc.gov URL.",
+ )
+ if status == 403:
+ return (
+ False,
+ "Invalid CDC Open Data app token. Check the token, or leave it blank to use the shared public pool.",
+ )
+ if status is None:
+ return False, "Could not reach data.cdc.gov. Check your network connection and try again."
+ return False, f"data.cdc.gov returned HTTP {status} for dataset '{dataset_id}'."
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/cdc_open_data/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/cdc_open_data/settings.py
new file mode 100644
index 000000000000..9dae436169c6
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/cdc_open_data/settings.py
@@ -0,0 +1,56 @@
+"""Endpoint catalog and constants for the CDC Open Data (Socrata SODA) connector.
+
+CDC Open Data (data.cdc.gov) publishes every dataset behind the same generic Socrata SODA REST
+API rather than a fixed set of named endpoints, so "endpoints" here means the dataset 4x4 IDs
+the user configures, not a vendor-defined catalog.
+"""
+
+import re
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.schema import incremental_field
+from products.warehouse_sources.backend.types import IncrementalField, IncrementalFieldType
+
+CDC_BASE_URL = "https://data.cdc.gov"
+
+# Socrata assigns every dataset a "4x4" identifier: two 4-character alphanumeric groups joined
+# by a hyphen (e.g. "9bhg-hcku"), visible in the dataset's data.cdc.gov URL.
+DATASET_ID_PATTERN = re.compile(r"^[a-zA-Z0-9]{4}-[a-zA-Z0-9]{4}$")
+
+# Caps how many datasets a single source can fan out into. Each configured ID becomes its own
+# schema, database row, and Temporal schedule, so this bounds setup-time resource usage rather
+# than any vendor-side limit.
+MAX_DATASET_IDS = 50
+
+# Socrata system fields present on every dataset regardless of its own columns. Only returned
+# when `$$exclude_system_fields=false` is sent (see cdc_open_data.py).
+SOCRATA_ID_FIELD = ":id"
+SOCRATA_UPDATED_AT_FIELD = ":updated_at"
+
+# SODA 2.0 endpoints cap $limit at 50,000; 2.1/3.0 are unbounded. 10k keeps each page's JSON
+# payload (and in-memory parse) modest for wide datasets while still bounding round trips.
+PAGE_SIZE = 10_000
+
+# `:updated_at` is the only field guaranteed to exist and be filterable on every dataset,
+# regardless of the dataset's own columns, so it's the sole incremental candidate offered.
+# A full-table republish (common on CDC's surveillance datasets) bumps `:updated_at` on every
+# row, so an incremental sync after a republish re-fetches the whole dataset via merge rather
+# than missing anything.
+INCREMENTAL_FIELDS: list[IncrementalField] = [
+ incremental_field(
+ field=SOCRATA_UPDATED_AT_FIELD,
+ field_type=IncrementalFieldType.DateTime,
+ label="Last updated (:updated_at)",
+ ),
+]
+
+
+def parse_dataset_ids(raw: str) -> list[str]:
+ """Split the user-entered dataset IDs field into a deduplicated, order-preserving list."""
+ seen: set[str] = set()
+ dataset_ids: list[str] = []
+ for token in re.split(r"[,\n]+", raw or ""):
+ dataset_id = token.strip()
+ if dataset_id and dataset_id not in seen:
+ seen.add(dataset_id)
+ dataset_ids.append(dataset_id)
+ return dataset_ids
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/cdc_open_data/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/cdc_open_data/source.py
index a1110c8b1b1d..dc8f73a96471 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/cdc_open_data/source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/cdc_open_data/source.py
@@ -1,13 +1,31 @@
-from typing import cast
+from typing import Optional, cast
from posthog.schema import (
DataWarehouseSourceCategory,
ExternalDataSourceType as SchemaExternalDataSourceType,
+ ReleaseStatus,
SourceConfig,
+ SourceFieldInputConfig,
+ SourceFieldInputConfigType,
)
-from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, SimpleSource
+from products.warehouse_sources.backend.temporal.data_imports.sources.cdc_open_data.cdc_open_data import (
+ CdcOpenDataResumeConfig,
+ cdc_open_data_source,
+ validate_cdc_open_data_credentials,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.cdc_open_data.settings import (
+ DATASET_ID_PATTERN,
+ INCREMENTAL_FIELDS,
+ MAX_DATASET_IDS,
+ SOCRATA_ID_FIELD,
+ parse_dataset_ids,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, ResumableSource
from products.warehouse_sources.backend.temporal.data_imports.sources.common.registry import SourceRegistry
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.schema import SourceSchema
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceInputs, SourceResponse
from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.cdcopendata import (
CdcOpenDataSourceConfig,
)
@@ -15,18 +33,134 @@ from products.warehouse_sources.backend.types import ExternalDataSourceType
@SourceRegistry.register
-class CdcOpenDataSource(SimpleSource[CdcOpenDataSourceConfig]):
+class CdcOpenDataSource(ResumableSource[CdcOpenDataSourceConfig, CdcOpenDataResumeConfig]):
+ api_docs_url = "https://dev.socrata.com/consumers/getting-started.html"
+
@property
def source_type(self) -> ExternalDataSourceType:
return ExternalDataSourceType.CDCOPENDATA
+ def get_non_retryable_errors(self) -> dict[str, str | None]:
+ return {
+ "403 Client Error: Forbidden for url: https://data.cdc.gov": "Invalid CDC Open Data app token. Check the token in the source settings, or remove it to use the shared public pool.",
+ "404 Client Error: Not Found for url: https://data.cdc.gov": "Dataset not found on data.cdc.gov. Check the dataset ID in the source settings.",
+ }
+
+ def get_schemas(
+ self,
+ config: CdcOpenDataSourceConfig,
+ team_id: int,
+ with_counts: bool = False,
+ names: list[str] | None = None,
+ force_refresh: bool = False,
+ api_version: str | None = None,
+ ) -> list[SourceSchema]:
+ dataset_ids = parse_dataset_ids(config.dataset_ids)
+ schemas = [
+ SourceSchema(
+ name=dataset_id,
+ supports_incremental=True,
+ supports_append=True,
+ incremental_fields=INCREMENTAL_FIELDS,
+ detected_primary_keys=[SOCRATA_ID_FIELD],
+ )
+ for dataset_id in dataset_ids
+ ]
+
+ if names is not None:
+ names_set = set(names)
+ schemas = [schema for schema in schemas if schema.name in names_set]
+
+ return schemas
+
+ def validate_credentials(
+ self,
+ config: CdcOpenDataSourceConfig,
+ team_id: int,
+ schema_name: Optional[str] = None,
+ api_version: str | None = None,
+ ) -> tuple[bool, str | None]:
+ dataset_ids = parse_dataset_ids(config.dataset_ids)
+ if not dataset_ids:
+ return False, "Enter at least one CDC dataset ID to sync."
+
+ if len(dataset_ids) > MAX_DATASET_IDS:
+ return (
+ False,
+ f"Enter at most {MAX_DATASET_IDS} CDC dataset IDs. You entered {len(dataset_ids)}.",
+ )
+
+ invalid_dataset_id = next(
+ (dataset_id for dataset_id in dataset_ids if not DATASET_ID_PATTERN.match(dataset_id)), None
+ )
+ if invalid_dataset_id is not None:
+ return (
+ False,
+ f"'{invalid_dataset_id}' doesn't look like a CDC dataset ID. Use the 4x4 ID from the "
+ "dataset's data.cdc.gov URL, e.g. '9bhg-hcku'.",
+ )
+
+ probe_dataset_id = schema_name if schema_name in dataset_ids else dataset_ids[0]
+ return validate_cdc_open_data_credentials(config.app_token or "", probe_dataset_id)
+
+ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[CdcOpenDataResumeConfig]:
+ return ResumableSourceManager[CdcOpenDataResumeConfig](inputs, CdcOpenDataResumeConfig)
+
+ def source_for_pipeline(
+ self,
+ config: CdcOpenDataSourceConfig,
+ resumable_source_manager: ResumableSourceManager[CdcOpenDataResumeConfig],
+ inputs: SourceInputs,
+ ) -> SourceResponse:
+ return cdc_open_data_source(
+ dataset_id=inputs.schema_name,
+ app_token=config.app_token or "",
+ team_id=inputs.team_id,
+ job_id=inputs.job_id,
+ resumable_source_manager=resumable_source_manager,
+ should_use_incremental_field=inputs.should_use_incremental_field,
+ db_incremental_field_last_value=inputs.db_incremental_field_last_value
+ if inputs.should_use_incremental_field
+ else None,
+ )
+
@property
def get_source_config(self) -> SourceConfig:
return SourceConfig(
name=SchemaExternalDataSourceType.CDC_OPEN_DATA,
category=DataWarehouseSourceCategory.ANALYTICS,
label="CDC Open Data (data.cdc.gov)",
+ releaseStatus=ReleaseStatus.ALPHA,
+ keywords=["cdc", "public health", "socrata", "covid"],
+ caption="""Sync one or more datasets from [data.cdc.gov](https://data.cdc.gov) into the PostHog Data warehouse.
+
+Find a dataset's ID in its data.cdc.gov URL — for example `9bhg-hcku` in `https://data.cdc.gov/d/9bhg-hcku`. Browse the full catalog at [data.cdc.gov](https://data.cdc.gov).
+
+No account is required. Optionally, register a free [Socrata app token](https://support.socrata.com/hc/en-us/articles/210138558-Generating-an-App-Token) to avoid the shared public rate limit.
+""",
+ docsUrl="https://posthog.com/docs/cdp/sources/cdc-open-data",
iconPath="/static/services/cdc_open_data.png",
- fields=cast(list[FieldType], []),
- unreleasedSource=True,
+ fields=cast(
+ list[FieldType],
+ [
+ SourceFieldInputConfig(
+ name="dataset_ids",
+ label="Dataset IDs",
+ type=SourceFieldInputConfigType.TEXTAREA,
+ required=True,
+ placeholder="9bhg-hcku, vbim-akqf",
+ secret=False,
+ caption="Separate multiple dataset IDs with commas or new lines. Each dataset becomes its own table.",
+ ),
+ SourceFieldInputConfig(
+ name="app_token",
+ label="App token (optional)",
+ type=SourceFieldInputConfigType.PASSWORD,
+ required=False,
+ placeholder="",
+ secret=True,
+ caption="Lifts the shared per-IP rate limit. Leave blank to use the public pool.",
+ ),
+ ],
+ ),
)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/cdc_open_data/tests/test_cdc_open_data.py b/products/warehouse_sources/backend/temporal/data_imports/sources/cdc_open_data/tests/test_cdc_open_data.py
new file mode 100644
index 000000000000..2cc30fddc303
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/cdc_open_data/tests/test_cdc_open_data.py
@@ -0,0 +1,239 @@
+import json
+from collections.abc import Iterable
+from datetime import UTC, date, datetime, timedelta
+from typing import Any, cast
+
+from unittest.mock import MagicMock, patch
+
+from parameterized import parameterized
+from requests import Response
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.cdc_open_data.cdc_open_data import (
+ CdcOpenDataResumeConfig,
+ _auth_config,
+ _format_where_value,
+ _probe_url,
+ cdc_open_data_source,
+ validate_cdc_open_data_credentials,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.cdc_open_data.settings import PAGE_SIZE
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+
+
+class TestFormatWhereValue:
+ @parameterized.expand(
+ [
+ ("naive_datetime", datetime(2024, 6, 1, 12, 30, 0), "2024-06-01T12:30:00"),
+ (
+ "aware_datetime_converted_to_utc",
+ datetime(2024, 6, 1, 12, 30, 0, tzinfo=UTC) + timedelta(hours=0),
+ "2024-06-01T12:30:00",
+ ),
+ ("date_only", date(2024, 6, 1), "2024-06-01T00:00:00"),
+ ("string_passthrough", "2024-06-01T12:30:00", "2024-06-01T12:30:00"),
+ ]
+ )
+ def test_formats_value_for_soql_comparison(self, _name: str, value: Any, expected: str) -> None:
+ assert _format_where_value(value) == expected
+
+
+class TestAuthConfig:
+ def test_no_app_token_means_anonymous_request(self) -> None:
+ assert _auth_config("") is None
+
+ def test_app_token_becomes_header_auth(self) -> None:
+ auth = _auth_config("my-token")
+ assert auth == {"type": "api_key", "api_key": "my-token", "name": "X-App-Token", "location": "header"}
+
+
+class TestProbeUrl:
+ def test_probe_url_targets_dataset_resource_with_limit_one(self) -> None:
+ url = _probe_url("9bhg-hcku")
+ assert url == "https://data.cdc.gov/resource/9bhg-hcku.json?%24limit=1"
+
+
+def _make_http_response(body: 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 TestValidateCdcOpenDataCredentials:
+ @parameterized.expand(
+ [
+ ("reachable", 200, (True, None)),
+ (
+ "missing_dataset",
+ 404,
+ (
+ False,
+ "Dataset 'aaaa-aaaa' was not found on data.cdc.gov. Check the dataset ID in its data.cdc.gov URL.",
+ ),
+ ),
+ (
+ "invalid_app_token",
+ 403,
+ (
+ False,
+ "Invalid CDC Open Data app token. Check the token, or leave it blank to use the shared public pool.",
+ ),
+ ),
+ (
+ "unreachable",
+ None,
+ (False, "Could not reach data.cdc.gov. Check your network connection and try again."),
+ ),
+ ("unexpected_status", 500, (False, "data.cdc.gov returned HTTP 500 for dataset 'aaaa-aaaa'.")),
+ ]
+ )
+ def test_maps_probe_status_to_message(
+ self, _name: str, probe_status: int | None, expected: tuple[bool, str | None]
+ ) -> None:
+ with patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.cdc_open_data.cdc_open_data.validate_via_probe",
+ return_value=(probe_status == 200, probe_status),
+ ):
+ assert validate_cdc_open_data_credentials("some-token", "aaaa-aaaa") == expected
+
+ def test_redacts_app_token_from_captured_samples(self) -> None:
+ with patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.cdc_open_data.cdc_open_data.validate_via_probe",
+ return_value=(True, 200),
+ ) as mock_probe:
+ validate_cdc_open_data_credentials("super-secret-token", "9bhg-hcku")
+ session_factory = mock_probe.call_args.args[0]
+ with patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.cdc_open_data.cdc_open_data.make_tracked_session"
+ ) as mock_make_session:
+ session_factory()
+ mock_make_session.assert_called_once_with(redact_values=("super-secret-token",))
+
+ def test_no_app_token_sends_no_header(self) -> None:
+ with patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.cdc_open_data.cdc_open_data.validate_via_probe",
+ return_value=(True, 200),
+ ) as mock_probe:
+ validate_cdc_open_data_credentials("", "9bhg-hcku")
+ assert mock_probe.call_args.kwargs["headers"] is None
+
+
+class TestCdcOpenDataSourceResumeBehavior:
+ """End-to-end resume behaviour of ``cdc_open_data_source`` via ``rest_api_resource``."""
+
+ def _drive(
+ self,
+ manager: MagicMock,
+ responses: list[Response],
+ should_use_incremental_field: bool = False,
+ db_incremental_field_last_value: Any = None,
+ ) -> 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(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.rest_client.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_response = cdc_open_data_source(
+ dataset_id="9bhg-hcku",
+ app_token="",
+ team_id=123,
+ job_id="test_job",
+ resumable_source_manager=manager,
+ should_use_incremental_field=should_use_incremental_field,
+ db_incremental_field_last_value=db_incremental_field_last_value,
+ )
+ list(cast(Iterable[Any], source_response.items()))
+ return mock_session, sent_params
+
+ def test_full_refresh_orders_by_id_with_no_where_filter(self) -> None:
+ manager = MagicMock(spec=ResumableSourceManager)
+ manager.can_resume.return_value = False
+
+ responses = [_make_http_response([{":id": "row-1"}])]
+ _, sent_params = self._drive(manager, responses)
+
+ assert sent_params[0]["$order"] == ":id"
+ assert "$where" not in sent_params[0]
+ assert sent_params[0]["$$exclude_system_fields"] == "false"
+
+ def test_incremental_sync_adds_where_filter_and_orders_by_updated_at(self) -> None:
+ manager = MagicMock(spec=ResumableSourceManager)
+ manager.can_resume.return_value = False
+
+ responses = [_make_http_response([{":id": "row-1", ":updated_at": "2024-06-02T00:00:00.000"}])]
+ _, sent_params = self._drive(
+ manager,
+ responses,
+ should_use_incremental_field=True,
+ db_incremental_field_last_value=datetime(2024, 6, 1, 0, 0, 0),
+ )
+
+ assert sent_params[0]["$order"] == ":updated_at,:id"
+ assert sent_params[0]["$where"] == ":updated_at > '2024-06-01T00:00:00'"
+
+ def test_incremental_sync_without_last_value_omits_where_filter(self) -> None:
+ # First-ever incremental sync has no watermark yet, so it must not filter anything out.
+ manager = MagicMock(spec=ResumableSourceManager)
+ manager.can_resume.return_value = False
+
+ responses = [_make_http_response([{":id": "row-1"}])]
+ _, sent_params = self._drive(manager, responses, should_use_incremental_field=True)
+
+ assert "$where" not in sent_params[0]
+
+ def test_fresh_run_saves_offset_after_each_non_terminal_page(self) -> None:
+ manager = MagicMock(spec=ResumableSourceManager)
+ manager.can_resume.return_value = False
+
+ full_page = [{":id": f"row-{i}"} for i in range(PAGE_SIZE)]
+ responses = [
+ _make_http_response(full_page),
+ _make_http_response([{":id": "row-last"}]),
+ ]
+ _, sent_params = self._drive(manager, responses)
+
+ offsets_sent = [p.get("$offset") for p in sent_params]
+ assert offsets_sent == [0, PAGE_SIZE]
+
+ saved = [call.args[0] for call in manager.save_state.call_args_list]
+ assert saved == [CdcOpenDataResumeConfig(next_offset=PAGE_SIZE)]
+
+ def test_resume_seeds_paginator_with_saved_offset(self) -> None:
+ manager = MagicMock(spec=ResumableSourceManager)
+ manager.can_resume.return_value = True
+ manager.load_state.return_value = CdcOpenDataResumeConfig(next_offset=40_000)
+
+ responses = [_make_http_response([{":id": "row-1"}])]
+ _, sent_params = self._drive(manager, responses)
+
+ assert sent_params[0]["$offset"] == 40_000
+ manager.load_state.assert_called_once()
+
+ def test_terminal_short_page_does_not_save_state(self) -> None:
+ manager = MagicMock(spec=ResumableSourceManager)
+ manager.can_resume.return_value = False
+
+ responses = [_make_http_response([{":id": "only"}])]
+ self._drive(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([{":id": "a"}])]
+ self._drive(manager, responses)
+
+ manager.load_state.assert_not_called()
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/cdc_open_data/tests/test_cdc_open_data_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/cdc_open_data/tests/test_cdc_open_data_source.py
new file mode 100644
index 000000000000..5ccf04b0abf0
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/cdc_open_data/tests/test_cdc_open_data_source.py
@@ -0,0 +1,165 @@
+from unittest import mock
+
+from parameterized import parameterized
+
+from posthog.schema import SourceFieldInputConfig
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.cdc_open_data import source as source_module
+from products.warehouse_sources.backend.temporal.data_imports.sources.cdc_open_data.cdc_open_data import (
+ CdcOpenDataResumeConfig,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.cdc_open_data.settings import (
+ MAX_DATASET_IDS,
+ SOCRATA_UPDATED_AT_FIELD,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.cdc_open_data.source import CdcOpenDataSource
+from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.cdcopendata import (
+ CdcOpenDataSourceConfig,
+)
+from products.warehouse_sources.backend.types import ExternalDataSourceType
+
+
+class TestCdcOpenDataSource:
+ def setup_method(self) -> None:
+ self.source = CdcOpenDataSource()
+ self.config = CdcOpenDataSourceConfig(dataset_ids="9bhg-hcku, vbim-akqf\nhk9y-quqm", app_token=None)
+
+ def test_source_type(self) -> None:
+ assert self.source.source_type == ExternalDataSourceType.CDCOPENDATA
+
+ def test_config_exposes_dataset_ids_and_app_token_fields(self) -> None:
+ fields = self.source.get_source_config.fields
+ assert [f.name for f in fields] == ["dataset_ids", "app_token"]
+ dataset_ids_field = next(f for f in fields if f.name == "dataset_ids")
+ app_token_field = next(f for f in fields if f.name == "app_token")
+ assert isinstance(dataset_ids_field, SourceFieldInputConfig)
+ assert isinstance(app_token_field, SourceFieldInputConfig)
+ assert dataset_ids_field.required is True
+ assert app_token_field.required is False
+
+ def test_ships_released_on_alpha(self) -> None:
+ # A finished source must not carry `unreleasedSource=True` (that hides it entirely);
+ # ALPHA is the correct soft label for a new, lightly-tested but visible source.
+ config = self.source.get_source_config
+ assert config.unreleasedSource is not True
+ assert config.releaseStatus is not None
+ assert config.releaseStatus.value == "alpha"
+
+ def test_does_not_advertise_a_static_table_catalog(self) -> None:
+ # The table set is whatever dataset IDs the user configures, not a vendor-fixed
+ # catalog, so this must stay False (the base default) or public docs would try to
+ # render a table list from an empty placeholder config.
+ assert self.source.lists_tables_without_credentials is False
+
+ def test_get_schemas_returns_one_schema_per_dataset_id(self) -> None:
+ schemas = self.source.get_schemas(self.config, team_id=1)
+ assert [s.name for s in schemas] == ["9bhg-hcku", "vbim-akqf", "hk9y-quqm"]
+ for schema in schemas:
+ assert schema.supports_incremental is True
+ assert schema.supports_append is True
+ assert schema.detected_primary_keys == [":id"]
+ assert [f["field"] for f in schema.incremental_fields] == [SOCRATA_UPDATED_AT_FIELD]
+
+ def test_get_schemas_dedupes_and_trims_whitespace(self) -> None:
+ config = CdcOpenDataSourceConfig(dataset_ids=" 9bhg-hcku ,9bhg-hcku\n vbim-akqf", app_token=None)
+ schemas = self.source.get_schemas(config, team_id=1)
+ assert [s.name for s in schemas] == ["9bhg-hcku", "vbim-akqf"]
+
+ def test_get_schemas_empty_when_no_dataset_ids_configured(self) -> None:
+ config = CdcOpenDataSourceConfig(dataset_ids="", app_token=None)
+ assert self.source.get_schemas(config, team_id=1) == []
+
+ def test_get_schemas_names_filter_narrows_result(self) -> None:
+ schemas = self.source.get_schemas(self.config, team_id=1, names=["vbim-akqf"])
+ assert [s.name for s in schemas] == ["vbim-akqf"]
+
+ @parameterized.expand(
+ [
+ ("forbidden", "403 Client Error: Forbidden for url: https://data.cdc.gov/resource/x.json?%24limit=1"),
+ ("not_found", "404 Client Error: Not Found for url: https://data.cdc.gov/resource/x.json?%24limit=1"),
+ ]
+ )
+ def test_non_retryable_errors_cover_bad_token_and_missing_dataset(self, _name: str, observed: str) -> None:
+ assert any(key in observed for key in self.source.get_non_retryable_errors())
+
+ def test_validate_credentials_requires_at_least_one_dataset_id(self) -> None:
+ config = CdcOpenDataSourceConfig(dataset_ids=" ", app_token=None)
+ with mock.patch.object(source_module, "validate_cdc_open_data_credentials") as mock_validate:
+ valid, message = self.source.validate_credentials(config, team_id=1)
+ assert valid is False
+ assert message == "Enter at least one CDC dataset ID to sync."
+ mock_validate.assert_not_called()
+
+ def test_validate_credentials_rejects_malformed_dataset_id_without_probing(self) -> None:
+ config = CdcOpenDataSourceConfig(dataset_ids="not-a-valid-id-at-all", app_token=None)
+ with mock.patch.object(source_module, "validate_cdc_open_data_credentials") as mock_validate:
+ valid, message = self.source.validate_credentials(config, team_id=1)
+ assert valid is False
+ assert message is not None and "not-a-valid-id-at-all" in message
+ mock_validate.assert_not_called()
+
+ def test_validate_credentials_rejects_too_many_dataset_ids_without_probing(self) -> None:
+ too_many_ids = ",".join(f"{i:04d}-{i:04d}" for i in range(MAX_DATASET_IDS + 1))
+ config = CdcOpenDataSourceConfig(dataset_ids=too_many_ids, app_token=None)
+ with mock.patch.object(source_module, "validate_cdc_open_data_credentials") as mock_validate:
+ valid, message = self.source.validate_credentials(config, team_id=1)
+ assert valid is False
+ assert message is not None and str(MAX_DATASET_IDS) in message
+ mock_validate.assert_not_called()
+
+ def test_validate_credentials_probes_first_dataset_at_source_create(self) -> None:
+ with mock.patch.object(
+ source_module, "validate_cdc_open_data_credentials", return_value=(True, None)
+ ) as mock_validate:
+ valid, message = self.source.validate_credentials(self.config, team_id=1, schema_name=None)
+ assert (valid, message) == (True, None)
+ mock_validate.assert_called_once_with("", "9bhg-hcku")
+
+ def test_validate_credentials_probes_the_requested_schema(self) -> None:
+ with mock.patch.object(
+ source_module, "validate_cdc_open_data_credentials", return_value=(True, None)
+ ) as mock_validate:
+ self.source.validate_credentials(self.config, team_id=1, schema_name="vbim-akqf")
+ mock_validate.assert_called_once_with("", "vbim-akqf")
+
+ def test_validate_credentials_falls_back_to_first_dataset_for_unknown_schema_name(self) -> None:
+ with mock.patch.object(
+ source_module, "validate_cdc_open_data_credentials", return_value=(True, None)
+ ) as mock_validate:
+ self.source.validate_credentials(self.config, team_id=1, schema_name="not-configured")
+ mock_validate.assert_called_once_with("", "9bhg-hcku")
+
+ def test_resumable_manager_bound_to_resume_config(self) -> None:
+ inputs = mock.MagicMock()
+ manager = self.source.get_resumable_source_manager(inputs)
+ assert manager._data_class is CdcOpenDataResumeConfig
+
+ @parameterized.expand(
+ [
+ ("incremental_sync_passes_last_value", True, "2024-01-01", "2024-01-01"),
+ ("full_refresh_omits_last_value", False, "2024-01-01", None),
+ ]
+ )
+ def test_source_for_pipeline_passes_expected_kwargs(
+ self, _name: str, should_use_incremental_field: bool, last_value: str, expected_last_value: str | None
+ ) -> None:
+ inputs = mock.MagicMock()
+ inputs.schema_name = "9bhg-hcku"
+ inputs.team_id = 1
+ inputs.job_id = "job-1"
+ inputs.should_use_incremental_field = should_use_incremental_field
+ inputs.db_incremental_field_last_value = last_value
+ manager = mock.MagicMock()
+
+ with mock.patch.object(source_module, "cdc_open_data_source") as mock_source:
+ self.source.source_for_pipeline(self.config, manager, inputs)
+
+ mock_source.assert_called_once()
+ _, kwargs = mock_source.call_args
+ assert kwargs["dataset_id"] == "9bhg-hcku"
+ assert kwargs["app_token"] == "" # `config.app_token` is None; the source coerces it to ""
+ assert kwargs["team_id"] == 1
+ assert kwargs["job_id"] == "job-1"
+ assert kwargs["resumable_source_manager"] is manager
+ assert kwargs["should_use_incremental_field"] == should_use_incremental_field
+ assert kwargs["db_incremental_field_last_value"] == expected_last_value
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/cdcopendata.py b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/cdcopendata.py
index 82bb3fa7f03a..ebb145697259 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/cdcopendata.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/cdcopendata.py
@@ -6,4 +6,5 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common imp
@config.config
class CdcOpenDataSourceConfig(config.Config):
- pass
+ dataset_ids: str
+ app_token: str | None = None