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 ding_connect import source (#66738)

Tom Owers14783da31fa4
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
index 807e5035e720..9265010e0741 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
@@ -117,6 +117,7 @@ the row lists both.
| datadog | HTTP | requests | ✅ |
| deel | HTTP | requests | ✅ |
| delighted | HTTP | requests | ✅ |
+| ding_connect | HTTP | requests | ✅ |
| dixa | HTTP | requests | ✅ |
| docuseal | HTTP | requests | ✅ |
| doit | HTTP | requests | ✅ |
@@ -372,7 +373,6 @@ doesn't conflict with concurrent PRs.
- dbt
- deputy
- devin_ai
-- ding_connect
- display_video_360
- dockerhub
- docusign
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/ding_connect/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/ding_connect/canonical_descriptions.py
new file mode 100644
index 000000000000..c8fd03610190
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/ding_connect/canonical_descriptions.py
@@ -0,0 +1,102 @@
+"""Canonical, documentation-sourced descriptions for DingConnect endpoints and columns.
+
+Sourced from the official DingConnect API V1 reference (https://www.dingconnect.com/Api/Description).
+Keyed by the resource names in `settings.py` `ENDPOINTS`, which match the
+`ExternalDataSchema.name` of a synced DingConnect table. Columns absent here fall back to LLM enrichment.
+"""
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (
+ CanonicalDescriptions,
+)
+
+_DOCS_URL = "https://www.dingconnect.com/Api/Description"
+
+CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
+ "Countries": {
+ "description": "A country that DingConnect operates in.",
+ "docs_url": _DOCS_URL,
+ "columns": {
+ "CountryIso": "Alphabetic 2 character ISO 3166-1 country code.",
+ "CountryName": "English country name.",
+ "InternationalDialingInformation": "Phone number dialing information for the country.",
+ "RegionCodes": "Regions supported within the country.",
+ },
+ },
+ "Currencies": {
+ "description": "A currency that DingConnect supports.",
+ "docs_url": _DOCS_URL,
+ "columns": {
+ "CurrencyIso": "Alphabetic 3 character ISO 4217 currency code.",
+ "CurrencyName": "English currency name.",
+ },
+ },
+ "Providers": {
+ "description": "A mobile operator or biller whose products can be sold through DingConnect.",
+ "docs_url": _DOCS_URL,
+ "columns": {
+ "ProviderCode": "Uniquely identifies a provider.",
+ "CountryIso": "The country within which the provider operates.",
+ "Name": "The English trading name of the provider.",
+ "ShortName": "A shortened name for space-restricted UI elements.",
+ "ValidationRegex": "Account numbers must match this regular expression.",
+ "CustomerCareNumber": "Customer care number of the provider.",
+ "RegionCodes": "Regions supported by the provider within the country.",
+ },
+ },
+ "Products": {
+ "description": "A sellable product (e.g. a top-up amount) offered by a provider.",
+ "docs_url": _DOCS_URL,
+ "columns": {
+ "ProviderCode": "The provider of the product.",
+ "SkuCode": "Unique product identifier, submitted with SendTransfer.",
+ "LocalizationKey": "Key to be used in conjunction with GetProductDescriptions.",
+ "SettingDefinitions": "Name/value pairs that should be submitted during SendTransfer.",
+ "Maximum": "The maximum price that can be sold.",
+ "Minimum": "The minimum price that can be sold.",
+ "CommissionRate": "The commission rate applied when selling the product.",
+ "ProcessingMode": "Transaction processing mode for this product.",
+ "RedemptionMechanism": "Whether the customer must act further to redeem the transfer.",
+ "Benefits": "The benefit type the transfer grants the target account.",
+ "ValidityPeriodIso": "How long the product is valid for after purchase (ISO 8601 duration).",
+ "RegionCode": "Region for this product.",
+ },
+ },
+ "Promotions": {
+ "description": "A time-bound promotion applied to a provider's products.",
+ "docs_url": _DOCS_URL,
+ "columns": {
+ "ProviderCode": "The code of the provider that the promotion applies to.",
+ "StartUtc": "Start date and time in UTC of the promotion.",
+ "EndUtc": "End date and time in UTC of the promotion.",
+ "CurrencyIso": "Currency the promotion applies to, usually the same as the provider.",
+ "ValidityPeriodIso": "Validity of the promotion (ISO 8601 duration).",
+ "MinimumSendAmount": "Minimum amount to be sent to qualify, in the distributor's currency.",
+ "LocalizationKey": "Key to be used in conjunction with GetPromotionDescriptions.",
+ },
+ },
+ "Balance": {
+ "description": "The distributor's current account balance.",
+ "docs_url": _DOCS_URL,
+ "columns": {
+ "Balance": "The distributor's balance.",
+ "CurrencyIso": "ISO 4217 currency code of the balance.",
+ },
+ },
+ "TransferRecords": {
+ "description": "A record of a transfer (top-up) that was sent through DingConnect. Only retained upstream for ~2 months.",
+ "docs_url": _DOCS_URL,
+ "columns": {
+ "TransferRef": "The unique identifier for the transfer within DingConnect's system.",
+ "DistributorRef": "The distributor's own identifier for the transfer.",
+ "SkuCode": "The unique product SkuCode that was transferred.",
+ "Price": "The resulting price of the transfer.",
+ "CommissionApplied": "The commission earned for selling this transfer.",
+ "StartedUtc": "The UTC datetime when processing the transfer was started.",
+ "CompletedUtc": "The UTC datetime that the transfer was recorded as completed.",
+ "ProcessingState": "The current state of the transfer (e.g. Submitted, Processing, Complete, Failed, Cancelled).",
+ "ReceiptText": "Provider-specific receipt text for the transfer.",
+ "ReceiptParams": "Name/value pairs of data contained in the receipt text.",
+ "AccountNumber": "The account number targeted in the transfer.",
+ },
+ },
+}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/ding_connect/ding_connect.py b/products/warehouse_sources/backend/temporal/data_imports/sources/ding_connect/ding_connect.py
new file mode 100644
index 000000000000..4574229fbf26
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/ding_connect/ding_connect.py
@@ -0,0 +1,196 @@
+import dataclasses
+from collections.abc import Iterator
+from typing import Any, Optional
+
+import requests
+from structlog.types import FilteringBoundLogger
+from tenacity import retry, retry_if_exception_type, stop_after_attempt, wait_exponential_jitter
+
+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import SourceResponse
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.http import make_tracked_session
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from products.warehouse_sources.backend.temporal.data_imports.sources.ding_connect.settings import (
+ DING_CONNECT_ENDPOINTS,
+ DingConnectEndpointConfig,
+)
+
+DING_CONNECT_BASE_URL = "https://api.dingconnect.com"
+
+# ListTransferRecords requires a Take (page size) and bypasses already-returned rows with Skip.
+TRANSFER_RECORDS_PAGE_SIZE = 100
+
+# Envelope keys returned alongside the data on every DingConnect response. Stripped from the
+# single-object GetBalance response so only the balance fields land in the row.
+_ENVELOPE_KEYS = ("ResultCode", "ErrorCodes", "ThereAreMoreItems")
+
+
+class DingConnectRetryableError(Exception):
+ pass
+
+
+class DingConnectResumeConfig:
+ # Number of TransferRecords rows already returned; the Skip value the next page resumes from.
+ # Only the paginated TransferRecords endpoint persists this; reference endpoints complete in a
+ # single request and never save state.
+ skip: int = 0
+
+
+def _get_headers(api_key: str) -> dict[str, str]:
+ return {
+ "api_key": api_key,
+ "Accept": "application/json",
+ "Content-Type": "application/json",
+ }
+
+
+@retry(
+ retry=retry_if_exception_type((DingConnectRetryableError, requests.ReadTimeout, requests.ConnectionError)),
+ stop=stop_after_attempt(5),
+ wait=wait_exponential_jitter(initial=1, max=30),
+ reraise=True,
+)
+def _request(
+ session: requests.Session,
+ method: str,
+ url: str,
+ headers: dict[str, str],
+ logger: FilteringBoundLogger,
+ json_body: Optional[dict[str, Any]] = None,
+) -> dict[str, Any]:
+ response = session.request(method, url, headers=headers, json=json_body, timeout=60)
+
+ if response.status_code == 429 or response.status_code >= 500:
+ raise DingConnectRetryableError(f"DingConnect API error (retryable): status={response.status_code}, url={url}")
+
+ if not response.ok:
+ # Truncate the body: DingConnect error responses can echo row data (e.g. AccountNumber from
+ # TransferRecords), so we log only a short preview to avoid persisting PII in logs.
+ logger.error(f"DingConnect API error: status={response.status_code}, body={response.text[:500]}, url={url}")
+ response.raise_for_status()
+
+ return response.json()
+
+
+def validate_credentials(api_key: str) -> bool:
+ # GetBalance is the cheapest call that proves both the key is valid and an account is attached.
+ url = f"{DING_CONNECT_BASE_URL}/api/V1/GetBalance"
+ try:
+ response = make_tracked_session(redact_values=(api_key,)).get(url, headers=_get_headers(api_key), timeout=30)
+ return response.status_code == 200
+ except Exception:
+ return False
+
+
+def _flatten_transfer_record(record: dict[str, Any]) -> dict[str, Any]:
+ """Lift the nested TransferId identifiers to the top level so TransferRef is a usable primary key."""
+ transfer_id = record.get("TransferId")
+ if isinstance(transfer_id, dict):
+ record = {**record}
+ record["TransferRef"] = transfer_id["TransferRef"]
+ record["DistributorRef"] = transfer_id.get("DistributorRef")
+ return record
+
+
+def _row_from_single_object(body: dict[str, Any]) -> dict[str, Any]:
+ """Build a single row from an envelope that carries the payload at the top level (GetBalance)."""
+ return {key: value for key, value in body.items() if key not in _ENVELOPE_KEYS}
+
+
+def _get_reference_rows(
+ session: requests.Session,
+ config: DingConnectEndpointConfig,
+ headers: dict[str, str],
+ logger: FilteringBoundLogger,
+) -> Iterator[list[dict[str, Any]]]:
+ url = f"{DING_CONNECT_BASE_URL}{config.path}"
+ body = _request(session, config.method, url, headers, logger)
+
+ if config.data_selector == "":
+ yield [_row_from_single_object(body)]
+ return
+
+ items = body.get(config.data_selector, []) or []
+ if items:
+ yield items
+
+
+def _get_transfer_record_rows(
+ session: requests.Session,
+ config: DingConnectEndpointConfig,
+ headers: dict[str, str],
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[DingConnectResumeConfig],
+) -> Iterator[list[dict[str, Any]]]:
+ url = f"{DING_CONNECT_BASE_URL}{config.path}"
+
+ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None
+ skip = resume.skip if resume is not None else 0
+ if skip:
+ logger.debug(f"DingConnect: resuming TransferRecords from skip={skip}")
+
+ while True:
+ body = _request(
+ session,
+ config.method,
+ url,
+ headers,
+ logger,
+ json_body={"Skip": skip, "Take": TRANSFER_RECORDS_PAGE_SIZE},
+ )
+
+ items = body.get(config.data_selector, []) or []
+ if items:
+ yield [_flatten_transfer_record(item) for item in items]
+
+ # `ThereAreMoreItems` is the documented continuation flag; fall back to a short final page.
+ there_are_more = body.get("ThereAreMoreItems")
+ has_next = there_are_more if there_are_more is not None else len(items) == TRANSFER_RECORDS_PAGE_SIZE
+ if not items or not has_next:
+ break
+
+ skip += TRANSFER_RECORDS_PAGE_SIZE
+ # Save AFTER yielding so a crash re-yields the last page rather than skipping it; the
+ # full-refresh replace plus the TransferRef primary key dedupe any re-pulled rows.
+ resumable_source_manager.save_state(DingConnectResumeConfig(skip=skip))
+
+
+def get_rows(
+ api_key: str,
+ endpoint: str,
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[DingConnectResumeConfig],
+) -> Iterator[list[dict[str, Any]]]:
+ config = DING_CONNECT_ENDPOINTS[endpoint]
+ headers = _get_headers(api_key)
+ session = make_tracked_session(redact_values=(api_key,))
+
+ if config.paginated:
+ yield from _get_transfer_record_rows(session, config, headers, logger, resumable_source_manager)
+ else:
+ yield from _get_reference_rows(session, config, headers, logger)
+
+
+def ding_connect_source(
+ api_key: str,
+ endpoint: str,
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[DingConnectResumeConfig],
+) -> SourceResponse:
+ config = DING_CONNECT_ENDPOINTS[endpoint]
+
+ return SourceResponse(
+ name=endpoint,
+ items=lambda: get_rows(
+ api_key=api_key,
+ endpoint=endpoint,
+ logger=logger,
+ resumable_source_manager=resumable_source_manager,
+ ),
+ primary_keys=config.primary_keys,
+ partition_count=1 if config.partition_key else None,
+ partition_size=1 if config.partition_key else None,
+ partition_mode="datetime" if config.partition_key else None,
+ partition_format="month" if config.partition_key else None,
+ partition_keys=[config.partition_key] if config.partition_key else None,
+ )
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/ding_connect/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/ding_connect/settings.py
new file mode 100644
index 000000000000..7a871ed75f0e
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/ding_connect/settings.py
@@ -0,0 +1,81 @@
+from dataclasses import dataclass, field
+from typing import Literal, Optional
+
+from products.warehouse_sources.backend.types import IncrementalField
+
+DingConnectMethod = Literal["GET", "POST"]
+
+
+@dataclass
+class DingConnectEndpointConfig:
+ name: str
+ path: str
+ method: DingConnectMethod = "GET"
+ # Key in the response envelope holding the row list. "" means the body itself is a single
+ # object (GetBalance) which we wrap into a one-row list.
+ data_selector: str = "Items"
+ primary_keys: list[str] = field(default_factory=lambda: ["id"])
+ # Stable creation-style datetime field to partition by; None for small static lookups.
+ partition_key: Optional[str] = None
+ # ListTransferRecords is the only unbounded endpoint and pages via Skip/Take in the POST body.
+ # Reference endpoints return their whole (bounded) list in a single response.
+ paginated: bool = False
+ incremental_fields: list[IncrementalField] = field(default_factory=list)
+ should_sync_default: bool = True
+
+
+# DingConnect's REST API exposes reference/catalog lookups (Countries, Currencies, Providers,
+# Products, Promotions, Balance) plus transaction history (TransferRecords). None of these expose
+# a server-side timestamp filter — the catalog endpoints are static lookups and ListTransferRecords
+# only accepts Skip/Take offset paging — so every table is full refresh. Transfer history is also
+# only retained for ~2 months upstream, so each sync reflects the currently-retained window.
+DING_CONNECT_ENDPOINTS: dict[str, DingConnectEndpointConfig] = {
+ "Countries": DingConnectEndpointConfig(
+ name="Countries",
+ path="/api/V1/GetCountries",
+ primary_keys=["CountryIso"],
+ ),
+ "Currencies": DingConnectEndpointConfig(
+ name="Currencies",
+ path="/api/V1/GetCurrencies",
+ primary_keys=["CurrencyIso"],
+ ),
+ "Providers": DingConnectEndpointConfig(
+ name="Providers",
+ path="/api/V1/GetProviders",
+ primary_keys=["ProviderCode"],
+ ),
+ "Products": DingConnectEndpointConfig(
+ name="Products",
+ path="/api/V1/GetProducts",
+ primary_keys=["SkuCode"],
+ ),
+ # Promotions carry no unique identifier, so dedupe on the (provider, currency, start) tuple.
+ "Promotions": DingConnectEndpointConfig(
+ name="Promotions",
+ path="/api/V1/GetPromotions",
+ primary_keys=["ProviderCode", "CurrencyIso", "StartUtc"],
+ ),
+ # GetBalance returns a single object rather than an Items list; we wrap it into one row keyed
+ # on the currency so a full-refresh replace keeps exactly one current-balance row per currency.
+ "Balance": DingConnectEndpointConfig(
+ name="Balance",
+ path="/api/V1/GetBalance",
+ data_selector="",
+ primary_keys=["CurrencyIso"],
+ ),
+ "TransferRecords": DingConnectEndpointConfig(
+ name="TransferRecords",
+ path="/api/V1/ListTransferRecords",
+ method="POST",
+ paginated=True,
+ primary_keys=["TransferRef"],
+ partition_key="StartedUtc",
+ ),
+}
+
+ENDPOINTS = tuple(DING_CONNECT_ENDPOINTS.keys())
+
+INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {
+ name: config.incremental_fields for name, config in DING_CONNECT_ENDPOINTS.items()
+}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/ding_connect/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/ding_connect/source.py
index 2d592839c712..15f4bcfc2ba8 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/ding_connect/source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/ding_connect/source.py
@@ -1,30 +1,147 @@
-from typing import cast
+from typing import Optional, cast
from posthog.schema import (
DataWarehouseSourceCategory,
ExternalDataSourceType as SchemaExternalDataSourceType,
+ ReleaseStatus,
SourceConfig,
+ SourceFieldInputConfig,
+ SourceFieldInputConfigType,
)
-from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, SimpleSource
+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import (
+ SourceInputs,
+ SourceResponse,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, ResumableSource
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (
+ CanonicalDescriptions,
+)
from products.warehouse_sources.backend.temporal.data_imports.sources.common.registry import SourceRegistry
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.schema import SourceSchema
+from products.warehouse_sources.backend.temporal.data_imports.sources.ding_connect.ding_connect import (
+ DingConnectResumeConfig,
+ ding_connect_source,
+ validate_credentials as validate_ding_connect_credentials,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.ding_connect.settings import (
+ ENDPOINTS,
+ INCREMENTAL_FIELDS,
+)
from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs import DingConnectSourceConfig
from products.warehouse_sources.backend.types import ExternalDataSourceType
@SourceRegistry.register
-class DingConnectSource(SimpleSource[DingConnectSourceConfig]):
+class DingConnectSource(ResumableSource[DingConnectSourceConfig, DingConnectResumeConfig]):
+ lists_tables_without_credentials = True # static endpoint catalog — safe for public docs
+
@property
def source_type(self) -> ExternalDataSourceType:
return ExternalDataSourceType.DINGCONNECT
+ def get_non_retryable_errors(self) -> dict[str, str | None]:
+ return {
+ # An invalid or revoked api_key surfaces as a 401 when `_request` calls
+ # `raise_for_status()`. Retrying can never satisfy a credential problem. Match the
+ # stable status text and base host, not the per-request path.
+ "401 Client Error: Unauthorized for url: https://api.dingconnect.com": "Your DingConnect API key is invalid or has been revoked. Generate a new key under the Developer tab of your DingConnect account settings, then reconnect.",
+ "403 Client Error: Forbidden for url: https://api.dingconnect.com": "Your DingConnect API key does not have permission to access this data. Check the key's permissions in your DingConnect account settings, then reconnect.",
+ }
+
+ def get_canonical_descriptions(self) -> CanonicalDescriptions:
+ from products.warehouse_sources.backend.temporal.data_imports.sources.ding_connect.canonical_descriptions import (
+ CANONICAL_DESCRIPTIONS,
+ )
+
+ return CANONICAL_DESCRIPTIONS
+
+ def get_schemas(
+ self,
+ config: DingConnectSourceConfig,
+ team_id: int,
+ with_counts: bool = False,
+ names: list[str] | None = None,
+ force_refresh: bool = False,
+ ) -> list[SourceSchema]:
+ def _description(endpoint: str) -> str | None:
+ if endpoint == "TransferRecords":
+ # DingConnect only retains transfer history for ~2 months, so each full-refresh
+ # sync reflects the currently-retained window.
+ return "Transfer history is only retained upstream for ~2 months. Full refresh only"
+ if endpoint == "Balance":
+ return "Current account balance per currency. Full refresh only"
+ return None
+
+ # No DingConnect endpoint exposes a server-side timestamp filter, so every table is full
+ # refresh: the catalog endpoints are static lookups and ListTransferRecords only offers
+ # Skip/Take offset paging.
+ schemas = [
+ SourceSchema(
+ name=endpoint,
+ supports_incremental=False,
+ supports_append=False,
+ incremental_fields=INCREMENTAL_FIELDS.get(endpoint, []),
+ description=_description(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: DingConnectSourceConfig, team_id: int, schema_name: Optional[str] = None
+ ) -> tuple[bool, str | None]:
+ if validate_ding_connect_credentials(config.api_key):
+ return True, None
+
+ return False, "Invalid DingConnect API key"
+
+ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[DingConnectResumeConfig]:
+ return ResumableSourceManager[DingConnectResumeConfig](inputs, DingConnectResumeConfig)
+
+ def source_for_pipeline(
+ self,
+ config: DingConnectSourceConfig,
+ resumable_source_manager: ResumableSourceManager[DingConnectResumeConfig],
+ inputs: SourceInputs,
+ ) -> SourceResponse:
+ return ding_connect_source(
+ api_key=config.api_key,
+ endpoint=inputs.schema_name,
+ logger=inputs.logger,
+ resumable_source_manager=resumable_source_manager,
+ )
+
@property
def get_source_config(self) -> SourceConfig:
return SourceConfig(
name=SchemaExternalDataSourceType.DING_CONNECT,
- category=DataWarehouseSourceCategory.COMMUNICATION,
- label="Ding Connect",
- iconPath="/static/services/ding_connect.png",
- fields=cast(list[FieldType], []),
+ category=DataWarehouseSourceCategory.PAYMENTS___BILLING,
+ label="DingConnect",
+ releaseStatus=ReleaseStatus.ALPHA,
unreleasedSource=True,
+ caption="""Enter your DingConnect API key to pull your DingConnect data into the PostHog Data warehouse.
+
+You can generate an API key under the **Developer** tab of your [DingConnect account settings](https://www.dingconnect.com/Account/Settings).""",
+ iconPath="/static/services/ding_connect.png",
+ docsUrl="https://posthog.com/docs/cdp/sources/ding-connect",
+ fields=cast(
+ list[FieldType],
+ [
+ SourceFieldInputConfig(
+ name="api_key",
+ label="API key",
+ type=SourceFieldInputConfigType.PASSWORD,
+ required=True,
+ placeholder="",
+ secret=True,
+ ),
+ ],
+ ),
)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/ding_connect/tests/test_ding_connect.py b/products/warehouse_sources/backend/temporal/data_imports/sources/ding_connect/tests/test_ding_connect.py
new file mode 100644
index 000000000000..fbf0ab7e7bdb
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/ding_connect/tests/test_ding_connect.py
@@ -0,0 +1,230 @@
+from typing import Any
+
+import pytest
+from unittest.mock import MagicMock
+
+from parameterized import parameterized
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.ding_connect import ding_connect
+from products.warehouse_sources.backend.temporal.data_imports.sources.ding_connect.ding_connect import (
+ DingConnectResumeConfig,
+ _flatten_transfer_record,
+ _row_from_single_object,
+ ding_connect_source,
+ get_rows,
+ validate_credentials,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.ding_connect.settings import (
+ DING_CONNECT_ENDPOINTS,
+)
+
+
+class _FakeResumableManager:
+ def __init__(self, state: DingConnectResumeConfig | None = None) -> None:
+ self._state = state
+ self.saved: list[DingConnectResumeConfig] = []
+
+ def can_resume(self) -> bool:
+ return self._state is not None
+
+ def load_state(self) -> DingConnectResumeConfig | None:
+ return self._state
+
+ def save_state(self, data: DingConnectResumeConfig) -> None:
+ self.saved.append(data)
+
+
+def _collect(endpoint: str, responses: list[dict[str, Any]], manager: _FakeResumableManager, monkeypatch: Any) -> list:
+ """Run get_rows against a queue of canned envelope responses, flattening yielded pages to rows."""
+ queue = list(responses)
+
+ def fake_request(session: Any, method: str, url: str, headers: dict, logger: Any, json_body: Any = None) -> dict:
+ return queue.pop(0)
+
+ monkeypatch.setattr(ding_connect, "_request", fake_request)
+ monkeypatch.setattr(ding_connect, "make_tracked_session", lambda **kwargs: MagicMock())
+
+ rows: list = []
+ for page in get_rows("key", endpoint, MagicMock(), manager): # type: ignore[arg-type]
+ rows.extend(page)
+ return rows
+
+
+class TestFlattenTransferRecord:
+ def test_lifts_transfer_id_fields_to_top_level(self) -> None:
+ record = {"TransferId": {"TransferRef": "TR1", "DistributorRef": "DR1"}, "SkuCode": "SKU"}
+ flattened = _flatten_transfer_record(record)
+ assert flattened["TransferRef"] == "TR1"
+ assert flattened["DistributorRef"] == "DR1"
+ assert flattened["SkuCode"] == "SKU"
+
+ def test_missing_transfer_id_is_left_untouched(self) -> None:
+ record = {"SkuCode": "SKU"}
+ assert _flatten_transfer_record(record) == {"SkuCode": "SKU"}
+
+ def test_missing_transfer_ref_fails_fast(self) -> None:
+ # TransferRef is the primary key, so a TransferId object without it must raise rather than
+ # silently writing a row with a None primary key.
+ with pytest.raises(KeyError):
+ _flatten_transfer_record({"TransferId": {"DistributorRef": "DR1"}})
+
+
+class TestRowFromSingleObject:
+ def test_strips_envelope_keys(self) -> None:
+ body = {"Balance": 100.5, "CurrencyIso": "USD", "ResultCode": 1, "ErrorCodes": []}
+ assert _row_from_single_object(body) == {"Balance": 100.5, "CurrencyIso": "USD"}
+
+
+class TestReferenceEndpoints:
+ def test_list_endpoint_yields_items(self, monkeypatch: Any) -> None:
+ responses = [{"Items": [{"CountryIso": "GB"}, {"CountryIso": "US"}], "ResultCode": 1, "ErrorCodes": []}]
+ rows = _collect("Countries", responses, _FakeResumableManager(), monkeypatch)
+ assert rows == [{"CountryIso": "GB"}, {"CountryIso": "US"}]
+
+ def test_empty_list_yields_nothing(self, monkeypatch: Any) -> None:
+ responses = [{"Items": [], "ResultCode": 1, "ErrorCodes": []}]
+ rows = _collect("Currencies", responses, _FakeResumableManager(), monkeypatch)
+ assert rows == []
+
+ def test_single_object_endpoint_wraps_one_row(self, monkeypatch: Any) -> None:
+ responses = [{"Balance": 42.0, "CurrencyIso": "EUR", "ResultCode": 1, "ErrorCodes": []}]
+ rows = _collect("Balance", responses, _FakeResumableManager(), monkeypatch)
+ assert rows == [{"Balance": 42.0, "CurrencyIso": "EUR"}]
+
+ def test_reference_endpoint_does_not_save_resume_state(self, monkeypatch: Any) -> None:
+ manager = _FakeResumableManager()
+ responses = [{"Items": [{"ProviderCode": "P1"}], "ResultCode": 1, "ErrorCodes": []}]
+ _collect("Providers", responses, manager, monkeypatch)
+ assert manager.saved == []
+
+
+class TestTransferRecordsPagination:
+ def _page(self, refs: list[str], there_are_more: bool) -> dict[str, Any]:
+ return {
+ "Items": [{"TransferId": {"TransferRef": r, "DistributorRef": f"d-{r}"}} for r in refs],
+ "ThereAreMoreItems": there_are_more,
+ "ResultCode": 1,
+ "ErrorCodes": [],
+ }
+
+ def test_single_page_flattens_and_stops(self, monkeypatch: Any) -> None:
+ manager = _FakeResumableManager()
+ rows = _collect("TransferRecords", [self._page(["TR1", "TR2"], there_are_more=False)], manager, monkeypatch)
+ assert [r["TransferRef"] for r in rows] == ["TR1", "TR2"]
+ # Only one page, so there's nothing further to resume to.
+ assert manager.saved == []
+
+ def test_follows_pagination_until_there_are_no_more_items(self, monkeypatch: Any) -> None:
+ manager = _FakeResumableManager()
+ responses = [
+ self._page(["TR1"], there_are_more=True),
+ self._page(["TR2"], there_are_more=True),
+ self._page(["TR3"], there_are_more=False),
+ ]
+ rows = _collect("TransferRecords", responses, manager, monkeypatch)
+ assert [r["TransferRef"] for r in rows] == ["TR1", "TR2", "TR3"]
+
+ def test_saves_advancing_skip_after_each_non_final_page(self, monkeypatch: Any) -> None:
+ manager = _FakeResumableManager()
+ responses = [
+ self._page(["TR1"], there_are_more=True),
+ self._page(["TR2"], there_are_more=False),
+ ]
+ _collect("TransferRecords", responses, manager, monkeypatch)
+ # State saved once (after the first page), advancing skip by the page size; the final page
+ # saves nothing so a completed sync leaves no stale resume cursor.
+ assert [c.skip for c in manager.saved] == [ding_connect.TRANSFER_RECORDS_PAGE_SIZE]
+
+ def test_resumes_from_saved_skip(self, monkeypatch: Any) -> None:
+ seen_skips: list[int] = []
+
+ def fake_request(
+ session: Any, method: str, url: str, headers: dict, logger: Any, json_body: Any = None
+ ) -> dict:
+ seen_skips.append(json_body["Skip"])
+ return self._page(["TR9"], there_are_more=False)
+
+ monkeypatch.setattr(ding_connect, "_request", fake_request)
+ monkeypatch.setattr(ding_connect, "make_tracked_session", lambda **kwargs: MagicMock())
+
+ manager = _FakeResumableManager(DingConnectResumeConfig(skip=200))
+ list(get_rows("key", "TransferRecords", MagicMock(), manager)) # type: ignore[arg-type]
+ assert seen_skips == [200]
+
+
+class TestValidateCredentials:
+ def test_status_maps_to_validity(self, monkeypatch: Any) -> None:
+ # 200 means the api_key was accepted; any other status (401 bad key, 500 transient) is treated
+ # as not-yet-valid at source-create.
+ for status_code, expected in [(200, True), (401, False), (500, False)]:
+ session = MagicMock()
+ session.get.return_value = MagicMock(status_code=status_code)
+ monkeypatch.setattr(ding_connect, "make_tracked_session", lambda *args, session=session, **kwargs: session)
+ assert validate_credentials("key") is expected
+
+ def test_network_error_is_invalid(self, monkeypatch: Any) -> None:
+ session = MagicMock()
+ session.get.side_effect = Exception("boom")
+ monkeypatch.setattr(ding_connect, "make_tracked_session", lambda **kwargs: session)
+ assert validate_credentials("key") is False
+
+
+class TestApiKeyRedaction:
+ # The api_key travels in a request header, so every tracked session that carries it must
+ # redact it from HTTP observer logs and captures.
+ def test_get_rows_redacts_api_key(self, monkeypatch: Any) -> None:
+ captured: dict[str, Any] = {}
+
+ def fake_make_tracked_session(**kwargs: Any) -> Any:
+ captured.update(kwargs)
+ return MagicMock()
+
+ monkeypatch.setattr(ding_connect, "make_tracked_session", fake_make_tracked_session)
+ monkeypatch.setattr(
+ ding_connect,
+ "_request",
+ lambda *args, **kwargs: {"Items": [], "ResultCode": 1, "ErrorCodes": []},
+ )
+
+ list(get_rows("secret-key", "Countries", MagicMock(), _FakeResumableManager())) # type: ignore[arg-type]
+ assert captured["redact_values"] == ("secret-key",)
+
+ def test_validate_credentials_redacts_api_key(self, monkeypatch: Any) -> None:
+ captured: dict[str, Any] = {}
+
+ def fake_make_tracked_session(**kwargs: Any) -> Any:
+ captured.update(kwargs)
+ session = MagicMock()
+ session.get.return_value = MagicMock(status_code=200)
+ return session
+
+ monkeypatch.setattr(ding_connect, "make_tracked_session", fake_make_tracked_session)
+
+ validate_credentials("secret-key")
+ assert captured["redact_values"] == ("secret-key",)
+
+
+class TestSourceResponse:
+ @parameterized.expand(
+ [
+ ("Countries", ["CountryIso"], None),
+ ("Currencies", ["CurrencyIso"], None),
+ ("Providers", ["ProviderCode"], None),
+ ("Products", ["SkuCode"], None),
+ ("Promotions", ["ProviderCode", "CurrencyIso", "StartUtc"], None),
+ ("Balance", ["CurrencyIso"], None),
+ ("TransferRecords", ["TransferRef"], "StartedUtc"),
+ ]
+ )
+ def test_primary_keys_and_partitioning(
+ self, endpoint: str, primary_keys: list[str], partition_key: str | None
+ ) -> None:
+ response = ding_connect_source("key", endpoint, MagicMock(), MagicMock())
+ assert response.name == endpoint
+ assert response.primary_keys == primary_keys
+ assert response.partition_keys == ([partition_key] if partition_key else None)
+ assert response.partition_mode == ("datetime" if partition_key else None)
+
+ def test_only_transfer_records_is_paginated(self) -> None:
+ paginated = {name for name, cfg in DING_CONNECT_ENDPOINTS.items() if cfg.paginated}
+ assert paginated == {"TransferRecords"}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/ding_connect/tests/test_ding_connect_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/ding_connect/tests/test_ding_connect_source.py
new file mode 100644
index 000000000000..3eb6790f6201
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/ding_connect/tests/test_ding_connect_source.py
@@ -0,0 +1,127 @@
+from typing import Any
+
+from unittest.mock import MagicMock
+
+from parameterized import parameterized
+
+from posthog.schema import DataWarehouseSourceCategory, ReleaseStatus, SourceFieldInputConfig
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.ding_connect import source as source_module
+from products.warehouse_sources.backend.temporal.data_imports.sources.ding_connect.ding_connect import (
+ DingConnectResumeConfig,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.ding_connect.settings import ENDPOINTS
+from products.warehouse_sources.backend.temporal.data_imports.sources.ding_connect.source import DingConnectSource
+from products.warehouse_sources.backend.types import ExternalDataSourceType
+
+
+class TestSourceConfig:
+ def test_source_type(self) -> None:
+ assert DingConnectSource().source_type == ExternalDataSourceType.DINGCONNECT
+
+ def test_get_source_config_basics(self) -> None:
+ config = DingConnectSource().get_source_config
+ assert config.label == "DingConnect"
+ assert config.category == DataWarehouseSourceCategory.PAYMENTS___BILLING
+ assert config.releaseStatus == ReleaseStatus.ALPHA
+ assert config.docsUrl == "https://posthog.com/docs/cdp/sources/ding-connect"
+
+ def test_source_config_has_single_required_secret_api_key(self) -> None:
+ fields = DingConnectSource().get_source_config.fields
+ assert len(fields) == 1
+ api_key_field = fields[0]
+ assert isinstance(api_key_field, SourceFieldInputConfig)
+ assert api_key_field.name == "api_key"
+ assert api_key_field.required is True
+ assert api_key_field.secret is True
+
+
+class TestGetSchemas:
+ def test_returns_every_endpoint(self) -> None:
+ schemas = DingConnectSource().get_schemas(MagicMock(), team_id=1)
+ assert {s.name for s in schemas} == set(ENDPOINTS)
+
+ def test_all_endpoints_are_full_refresh_only(self) -> None:
+ # No DingConnect endpoint exposes a server-side timestamp filter, so nothing supports
+ # incremental or append — guarding against an accidental incremental flip.
+ schemas = DingConnectSource().get_schemas(MagicMock(), team_id=1)
+ assert all(not s.supports_incremental for s in schemas)
+ assert all(not s.supports_append for s in schemas)
+
+ def test_transfer_records_notes_retention_window(self) -> None:
+ schemas = {s.name: s for s in DingConnectSource().get_schemas(MagicMock(), team_id=1)}
+ assert "2 months" in (schemas["TransferRecords"].description or "")
+
+ def test_names_filter(self) -> None:
+ schemas = DingConnectSource().get_schemas(MagicMock(), team_id=1, names=["Countries", "Balance"])
+ assert {s.name for s in schemas} == {"Countries", "Balance"}
+
+
+class TestValidateCredentials:
+ def test_valid_credentials(self, monkeypatch: Any) -> None:
+ monkeypatch.setattr(source_module, "validate_ding_connect_credentials", lambda api_key: True)
+ ok, error = DingConnectSource().validate_credentials(MagicMock(api_key="key"), team_id=1)
+ assert ok is True
+ assert error is None
+
+ def test_invalid_credentials(self, monkeypatch: Any) -> None:
+ monkeypatch.setattr(source_module, "validate_ding_connect_credentials", lambda api_key: False)
+ ok, error = DingConnectSource().validate_credentials(MagicMock(api_key="key"), team_id=1)
+ assert ok is False
+ assert error == "Invalid DingConnect API key"
+
+
+class TestResumableSourceManager:
+ def test_manager_is_bound_to_resume_config(self) -> None:
+ inputs = MagicMock()
+ manager = DingConnectSource().get_resumable_source_manager(inputs)
+ assert manager._data_class is DingConnectResumeConfig
+
+
+class TestSourceForPipeline:
+ def test_plumbs_through_to_transport(self, monkeypatch: Any) -> None:
+ captured: dict[str, Any] = {}
+ sentinel = object()
+
+ def fake_ding_connect_source(**kwargs: Any) -> Any:
+ captured.update(kwargs)
+ return sentinel
+
+ monkeypatch.setattr(source_module, "ding_connect_source", fake_ding_connect_source)
+
+ manager = MagicMock()
+ inputs = MagicMock(schema_name="TransferRecords", logger=MagicMock())
+ result = DingConnectSource().source_for_pipeline(MagicMock(api_key="key"), manager, inputs)
+
+ assert result is sentinel
+ assert captured["api_key"] == "key"
+ assert captured["endpoint"] == "TransferRecords"
+ assert captured["resumable_source_manager"] is manager
+
+
+class TestNonRetryableErrors:
+ @parameterized.expand(
+ [
+ (
+ "unauthorized",
+ "401 Client Error: Unauthorized for url: https://api.dingconnect.com/api/V1/GetCountries",
+ ),
+ (
+ "forbidden",
+ "403 Client Error: Forbidden for url: https://api.dingconnect.com/api/V1/GetProducts",
+ ),
+ ]
+ )
+ def test_credential_errors_are_non_retryable(self, _name: str, observed_error: str) -> None:
+ non_retryable_errors = DingConnectSource().get_non_retryable_errors()
+ assert any(key in observed_error for key in non_retryable_errors)
+
+ @parameterized.expand(
+ [
+ ("server_error", "500 Server Error: Internal Server Error for url: https://api.dingconnect.com"),
+ ("read_timeout", "HTTPSConnectionPool(host='api.dingconnect.com', port=443): Read timed out."),
+ ]
+ )
+ def test_transient_errors_remain_retryable(self, _name: str, other_error: str) -> None:
+ non_retryable_errors = DingConnectSource().get_non_retryable_errors()
+ assert not any(key in other_error for key in non_retryable_errors)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.py b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.py
index c5cad75892a1..cb292d3d6437 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.py
@@ -941,7 +941,7 @@ class DevinAISourceConfig(config.Config):
@config.config
class DingConnectSourceConfig(config.Config):
- pass
+ api_key: str
@config.config