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 demodesk import source (#107258)

Tom Owers10dbf5bced8a
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 558a12a930c9..ecc11c226937 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
@@ -234,6 +234,7 @@ the row lists both.
| deel | HTTP | requests | ✅ |
| deepgram | HTTP | requests | ✅ |
| deepsource | HTTP (GraphQL) | requests | ✅ |
+| demodesk | HTTP | requests + `rest_source.RESTClient` | ✅ |
| deno_deploy | HTTP | requests | ✅ |
| depot | HTTP (Connect RPC) | requests | ✅ |
| descope | HTTP | requests + `rest_source.RESTClient` | ✅ |
@@ -678,7 +679,6 @@ the row lists both.
| statuspage | HTTP | requests | ✅ |
| stigg | HTTP | requests | ✅ |
| stockdata | HTTP | requests + `rest_source.RESTClient` | ✅ |
-| strato | HTTP | requests + `rest_source.RESTClient` | ✅ |
| streamelements | HTTP | requests | ✅ |
| stripe | HTTP (vendor SDK) + Webhook | stripe (StripeClient + RequestsClient) + `WebhookSourceManager` | ✅ (pull) / ➖ (webhook) |
| stytch | HTTP | requests | ✅ |
@@ -701,7 +701,6 @@ the row lists both.
| tempo | HTTP | requests | ✅ |
| temporalio | gRPC (vendor SDK) | temporalio (`Client`, Rust core via `temporalio.bridge`) | ⚠️ |
| tenable_vulnerability_management | HTTP (async export flow) | requests | ✅ |
-| tenjin | HTTP | requests + `rest_source.RESTClient` | ✅ |
| terraform_cloud | HTTP | requests | ✅ |
| testrail | HTTP | requests | ✅ |
| thinkific | HTTP | requests | ✅ |
@@ -990,7 +989,6 @@ doesn't conflict with concurrent PRs.
- dayforce
- db2
- deelflows
-- demodesk
- deno_deploy
- deputy
- develocity
@@ -1406,6 +1404,7 @@ doesn't conflict with concurrent PRs.
- starburst
- statsig
- stockx
+- strato
- strava
- streamlabs
- substack
@@ -1425,6 +1424,7 @@ doesn't conflict with concurrent PRs.
- tebra
- telli
- tempo
+- tenjin
- terabox
- ternary
- terra_api
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/demodesk/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/demodesk/canonical_descriptions.py
new file mode 100644
index 000000000000..12a6795ee3a5
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/demodesk/canonical_descriptions.py
@@ -0,0 +1,101 @@
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (
+ CanonicalDescriptions,
+)
+
+# Sourced from the official API reference (https://demodesk.com/api/docs/index.html) and the
+# Demodesk help center's API article.
+CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
+ "demos": {
+ "description": "A scheduled or held meeting (demo), including its status, timing, and host.",
+ "docs_url": "https://help.demodesk.com/en/articles/8518816-api-reference",
+ "columns": {
+ "id": "Internal meeting id.",
+ "status": "Meeting status: scheduled, starting, started, ending, ended, or canceled.",
+ "account": "Meeting name.",
+ "token": "Public meeting token. Not valid for recording endpoints.",
+ "link": "URL of the meeting room.",
+ "duration": "Planned meeting duration in seconds.",
+ "startDate": "Scheduled start time of the meeting.",
+ "createdAt": "When the meeting was created.",
+ "updatedAt": "When the meeting was last updated.",
+ "timeZone": "IANA time zone of the meeting.",
+ "countryCode": "Country code of the meeting.",
+ "locale": "Locale of the meeting.",
+ "relationships": "References to associated objects such as the host user, booker, participants, playbook, event type, and recordings.",
+ },
+ },
+ "demo_templates": {
+ "description": "A meeting type (event type) that meetings are booked from.",
+ "docs_url": "https://help.demodesk.com/en/articles/8518816-api-reference",
+ "columns": {
+ "id": "Internal meeting type id.",
+ },
+ },
+ "users": {
+ "description": "An active team member visible to the API key's user.",
+ "docs_url": "https://demodesk.com/api/docs/index.html",
+ "columns": {
+ "id": "Internal user id.",
+ "firstName": "First name of the user.",
+ "lastName": "Last name of the user.",
+ "email": "Primary email of the user.",
+ "role": "Permission level of the user: user, manager, or company_admin.",
+ "locale": "Locale of the user.",
+ "timeZone": "IANA time zone of the user.",
+ },
+ },
+ "recordings": {
+ "description": "A meeting recording with its processing state and access level.",
+ "docs_url": "https://demodesk.com/api/docs/index.html",
+ "columns": {
+ "recordingToken": "Public recording token identifier, used to fetch transcripts, summaries, and scorecards.",
+ "recordingId": "Internal recording id.",
+ "demoId": "Internal id of the meeting the recording belongs to.",
+ "userId": "Id of the meeting host user.",
+ "name": "Name of the recording.",
+ "recordingWebUrl": "URL to the recording view in Demodesk.",
+ "temporaryDirectUrl": "Direct link to the video file, signed with a temporary access token.",
+ "status": "Recording status: pending, ready, failure, cancelled, or expired.",
+ "postprocessingStatus": "Post-processing status (transcription, statistics, summaries): pending, done, failed, or too_short.",
+ "access": "Access permission level: company_wide, selected_groups, host_and_participants, or host_only.",
+ "createdAt": "When the recording was created.",
+ "updatedAt": "When the recording was last updated.",
+ "demoStartDate": "Start time of the recorded meeting.",
+ "durationMs": "Recording duration in milliseconds.",
+ "groupIds": "Ids of groups assigned to the meeting.",
+ },
+ },
+ "recording_summaries": {
+ "description": "An AI-generated summary attached to a recording.",
+ "docs_url": "https://demodesk.com/api/docs/index.html",
+ "columns": {
+ "recordingToken": "Token of the recording the summary belongs to.",
+ "summaryId": "Internal summary id.",
+ "promptId": "Id of the prompt the summary was generated from.",
+ "promptName": "Name of the prompt the summary was generated from.",
+ "languageCode": "Language of the summary.",
+ "content": "Summary text.",
+ "htmlContent": "Summary as HTML.",
+ "createdAt": "When the summary was created.",
+ "updatedAt": "When the summary was last updated.",
+ },
+ },
+ "recording_scorecards": {
+ "description": "A coaching scorecard linked to a recording, including per-question scores.",
+ "docs_url": "https://demodesk.com/api/docs/index.html",
+ "columns": {
+ "recordingToken": "Token of the recording the scorecard belongs to.",
+ "scorecardId": "Internal scorecard id.",
+ "templateId": "Id of the scorecard template.",
+ "templateName": "Name of the scorecard template.",
+ "score": "Overall score, 1 to 5.",
+ "comment": "Overall comment left by the scorecard giver.",
+ "languageCode": "Language of the scorecard.",
+ "giverUserId": "Id of the user who gave the scorecard.",
+ "receiverUserId": "Id of the user who received the scorecard.",
+ "questions": "Per-question results, each with position, text, criteria, score, and comment.",
+ "createdAt": "When the scorecard was created.",
+ "updatedAt": "When the scorecard was last updated.",
+ },
+ },
+}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/demodesk/demodesk.py b/products/warehouse_sources/backend/temporal/data_imports/sources/demodesk/demodesk.py
new file mode 100644
index 000000000000..4e4c8d4971e3
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/demodesk/demodesk.py
@@ -0,0 +1,318 @@
+from datetime import UTC, datetime
+from typing import Any, Optional, cast
+
+from requests import Request, Response
+from requests.exceptions import RequestException
+
+from posthog.dataclasses import frozen
+
+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 (
+ RESTAPIConfig,
+ rest_api_resource,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.fanout import (
+ build_dependent_resource,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.paginators import (
+ BasePaginator,
+ JSONResponseCursorPaginator,
+ SinglePagePaginator,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.resource import Resource
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.typing import (
+ ApiKeyAuthConfig,
+ BearerTokenAuthConfig,
+ ClientConfig,
+ Endpoint,
+ EndpointResource,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from products.warehouse_sources.backend.temporal.data_imports.sources.demodesk.settings import (
+ DEMODESK_ENDPOINTS,
+ DemodeskApiVersion,
+ DemodeskEndpointConfig,
+)
+
+BASE_URL = "https://demodesk.com/api"
+
+
+@frozen
+class DemodeskResumeConfig:
+ # v1 endpoints checkpoint a page number, v2 endpoints an opaque cursor; one field is set.
+ page: int | None = None
+ cursor: str | None = None
+ # `recording_summaries`/`recording_scorecards` fan out over `recordings`; this is the
+ # `build_dependent_resource` checkpoint (which parents finished, where the current one
+ # stopped), mutually exclusive with `page`/`cursor` above.
+ fanout_state: dict[str, Any] | None = None
+
+
+def to_iso8601(value: Any) -> str:
+ """Format an incremental watermark for the v2 Ransack datetime filters."""
+ if isinstance(value, datetime):
+ dt = value if value.tzinfo else value.replace(tzinfo=UTC)
+ return dt.astimezone(UTC).strftime("%Y-%m-%dT%H:%M:%SZ")
+ return str(value)
+
+
+class DemodeskPagePaginator(BasePaginator):
+ """Paginator for v1 list endpoints: 1-based `page` param, `meta.hasNextPage` in the response.
+
+ A response without `meta.hasNextPage` (e.g. an unpaginated collection) stops after its first
+ page, so the same paginator is safe on v1 endpoints whose pagination is undocumented.
+ """
+
+ def __init__(self) -> None:
+ super().__init__()
+ self._page = 1
+
+ def init_request(self, request: Request) -> None:
+ if request.params is None:
+ request.params = {}
+ request.params["page"] = self._page
+
+ def update_state(self, response: Response, data: Optional[list[Any]] = None) -> None:
+ try:
+ meta = response.json().get("meta") or {}
+ except Exception:
+ self._has_next_page = False
+ return
+
+ if meta.get("hasNextPage"):
+ self._page += 1
+ self._has_next_page = True
+ else:
+ self._has_next_page = False
+
+ def update_request(self, request: Request) -> None:
+ if request.params is None:
+ request.params = {}
+ request.params["page"] = self._page
+
+ def get_resume_state(self) -> Optional[dict[str, Any]]:
+ return {"page": self._page} if self._has_next_page else None
+
+ def set_resume_state(self, state: dict[str, Any]) -> None:
+ page = state.get("page")
+ if page is not None:
+ self._page = int(page)
+ self._has_next_page = True
+
+
+def demodesk_client_config(api_key: str, api_version: DemodeskApiVersion) -> ClientConfig:
+ # The same user-level API key authenticates both surfaces, but v1 takes it in a custom
+ # `api-key` header while v2 takes it as a Bearer token.
+ auth: ApiKeyAuthConfig | BearerTokenAuthConfig
+ if api_version == "v1":
+ auth = {"type": "api_key", "name": "api-key", "api_key": api_key, "location": "header"}
+ else:
+ auth = {"type": "bearer", "token": api_key}
+ return {
+ "base_url": BASE_URL,
+ "auth": auth,
+ "headers": {"Accept": "application/json"},
+ # The v1 `api-key` header isn't stripped by `requests` on a cross-host redirect the way
+ # `Authorization` is, so `allow_redirects=False` is the only thing that keeps either auth
+ # scheme's credential from following a spoofed 3xx off `BASE_URL`.
+ "allow_redirects": False,
+ # `recording_summaries` bodies carry free-text AI meeting summaries and `recordings`
+ # carries signed `temporaryDirectUrl` links; keep both out of the shared HTTP sample
+ # store (still metered and logged) rather than trust the name-based scrubbers on
+ # unstructured content.
+ "capture": False,
+ }
+
+
+def _flatten_json_api_item(item: dict[str, Any]) -> dict[str, Any]:
+ """Merge a v1 JSON:API item's `attributes` into the row root, keeping `id`/`relationships`."""
+ attributes = item.pop("attributes", None)
+ if isinstance(attributes, dict):
+ for key, value in attributes.items():
+ item.setdefault(key, value)
+ return item
+
+
+def _paginator_for(config: DemodeskEndpointConfig) -> BasePaginator:
+ if config.api_version == "v1":
+ return DemodeskPagePaginator()
+ return JSONResponseCursorPaginator(cursor_path="meta.nextCursor", cursor_param="cursor")
+
+
+def get_resource(
+ config: DemodeskEndpointConfig,
+ should_use_incremental_field: bool,
+ incremental_field_name: str | None,
+ db_incremental_field_last_value: Optional[Any],
+) -> EndpointResource:
+ params: dict[str, Any] = dict(config.params)
+ if config.api_version == "v2":
+ params["limit"] = config.page_size
+
+ endpoint: Endpoint = {
+ "path": config.path,
+ "params": params,
+ "data_selector": "data",
+ "paginator": _paginator_for(config),
+ }
+
+ # Only send the server-side floor once a real watermark exists: the first incremental sync must
+ # go out unfiltered so it captures the full history, and the pipeline still advances the
+ # watermark from the synced rows.
+ if should_use_incremental_field and db_incremental_field_last_value is not None:
+ field_name = incremental_field_name or config.default_incremental_field
+ start_param = config.incremental_param_by_field.get(field_name or "")
+ if start_param is not None:
+ endpoint["incremental"] = {
+ "start_param": start_param,
+ "cursor_path": field_name or "",
+ "initial_value": None,
+ "convert": to_iso8601,
+ }
+
+ return {
+ "name": config.name,
+ "table_name": config.name,
+ "write_disposition": {
+ "disposition": "merge",
+ "strategy": "upsert",
+ }
+ if should_use_incremental_field
+ else "replace",
+ "endpoint": endpoint,
+ "table_format": "delta",
+ }
+
+
+def _fanout_resource(
+ api_key: str,
+ config: DemodeskEndpointConfig,
+ team_id: int,
+ job_id: str,
+ db_incremental_field_last_value: Optional[Any],
+ should_use_incremental_field: bool,
+ incremental_field_name: str | None,
+ resumable_source_manager: ResumableSourceManager[DemodeskResumeConfig],
+) -> Resource:
+ assert config.fanout is not None
+ parent = DEMODESK_ENDPOINTS[config.fanout.parent_name]
+
+ initial_fanout_state: dict[str, Any] | None = None
+ if resumable_source_manager.can_resume():
+ resume_config = resumable_source_manager.load_state()
+ if resume_config is not None:
+ initial_fanout_state = resume_config.fanout_state
+
+ def save_fanout_checkpoint(state: Optional[dict[str, Any]]) -> None:
+ if state:
+ resumable_source_manager.save_state(DemodeskResumeConfig(fanout_state=state))
+
+ return cast(
+ Resource,
+ build_dependent_resource(
+ endpoint_configs={config.name: config, parent.name: parent},
+ child_endpoint=config.name,
+ fanout=config.fanout,
+ client_config=demodesk_client_config(api_key, config.api_version),
+ path_format_values={},
+ team_id=team_id,
+ job_id=job_id,
+ db_incremental_field_last_value=db_incremental_field_last_value,
+ should_use_incremental_field=should_use_incremental_field,
+ incremental_field=incremental_field_name,
+ # The child endpoints take no page-size param, and the parent's `limit` default already
+ # matches PAGE_SIZE, so no size param is sent on either request.
+ page_size_param=None,
+ parent_endpoint_extra={
+ "paginator": _paginator_for(parent),
+ "data_selector": "data",
+ },
+ child_endpoint_extra={
+ "paginator": SinglePagePaginator(),
+ "data_selector": "data",
+ },
+ resume_hook=save_fanout_checkpoint,
+ initial_paginator_state=initial_fanout_state,
+ ),
+ )
+
+
+def demodesk_source(
+ api_key: str,
+ endpoint: str,
+ team_id: int,
+ job_id: str,
+ resumable_source_manager: ResumableSourceManager[DemodeskResumeConfig],
+ db_incremental_field_last_value: Optional[Any],
+ should_use_incremental_field: bool = False,
+ incremental_field_name: str | None = None,
+) -> Resource:
+ config = DEMODESK_ENDPOINTS[endpoint]
+
+ if config.fanout is not None:
+ return _fanout_resource(
+ api_key,
+ config,
+ team_id,
+ job_id,
+ db_incremental_field_last_value,
+ should_use_incremental_field,
+ incremental_field_name,
+ resumable_source_manager,
+ )
+
+ rest_config: RESTAPIConfig = {
+ "client": demodesk_client_config(api_key, config.api_version),
+ "resource_defaults": {},
+ "resources": [
+ get_resource(config, should_use_incremental_field, incremental_field_name, db_incremental_field_last_value)
+ ],
+ }
+
+ 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:
+ if resume_config.page is not None:
+ initial_paginator_state = {"page": resume_config.page}
+ elif resume_config.cursor is not None:
+ initial_paginator_state = {"cursor": resume_config.cursor}
+
+ def save_checkpoint(state: Optional[dict[str, Any]]) -> None:
+ if not state:
+ return
+ if state.get("page") is not None:
+ resumable_source_manager.save_state(DemodeskResumeConfig(page=int(state["page"])))
+ elif state.get("cursor"):
+ resumable_source_manager.save_state(DemodeskResumeConfig(cursor=str(state["cursor"])))
+
+ resource = rest_api_resource(
+ rest_config,
+ team_id,
+ job_id,
+ db_incremental_field_last_value,
+ resume_hook=save_checkpoint,
+ initial_paginator_state=initial_paginator_state,
+ )
+ if config.flatten_json_api:
+ resource = resource.add_map(_flatten_json_api_item)
+ return resource
+
+
+def validate_credentials(api_key: str) -> tuple[bool, str | None]:
+ # `/v2/me` is the cheapest authenticated probe: it only confirms the key is genuine, without
+ # touching a resource the key may lack visibility into.
+ try:
+ res = make_tracked_session(redact_values=(api_key,), allow_redirects=False, capture=False).get(
+ f"{BASE_URL}/v2/me",
+ headers={"Authorization": f"Bearer {api_key}", "Accept": "application/json"},
+ timeout=10,
+ )
+ except RequestException as exc:
+ return False, str(exc)
+
+ if res.status_code == 200:
+ return True, None
+ if res.status_code in (401, 403):
+ return False, "Demodesk rejected the API key. Check the key in your Demodesk integration settings."
+ return False, f"Could not reach the Demodesk API (HTTP {res.status_code}). Try again shortly."
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/demodesk/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/demodesk/settings.py
new file mode 100644
index 000000000000..1d8834eb4bff
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/demodesk/settings.py
@@ -0,0 +1,124 @@
+from dataclasses import dataclass, field
+from typing import Any, Literal
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.fanout import (
+ DependentEndpointConfig,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.schema import incremental_field
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SortMode
+from products.warehouse_sources.backend.types import IncrementalField
+
+# Documented default and maximum for the v2 `limit` param.
+PAGE_SIZE = 100
+
+DemodeskApiVersion = Literal["v1", "v2"]
+
+
+@dataclass(frozen=True)
+class DemodeskEndpointConfig:
+ name: str
+ path: str
+ # Demodesk keeps two API surfaces live: v2 (recommended; recordings, users) and the legacy v1
+ # (meetings). They differ in auth scheme and pagination, so each endpoint declares its surface.
+ api_version: DemodeskApiVersion
+ primary_keys: list[str]
+ partition_key: str | None = None
+ # v1 responses are JSON:API shaped ({"id", "type", "attributes": {...}}); flatten `attributes`
+ # into the row root so columns are queryable directly.
+ flatten_json_api: bool = False
+ params: dict[str, Any] = field(default_factory=dict)
+ incremental_fields: list[IncrementalField] = field(default_factory=list)
+ # Ransack query param carrying the server-side floor for each advertised incremental field.
+ incremental_param_by_field: dict[str, str] = field(default_factory=dict)
+ default_incremental_field: str | None = None
+ sort_mode: SortMode = "asc"
+ page_size: int = PAGE_SIZE
+ fanout: DependentEndpointConfig | None = None
+
+
+DEMODESK_ENDPOINTS: dict[str, DemodeskEndpointConfig] = {
+ "demos": DemodeskEndpointConfig(
+ name="demos",
+ path="/v1/demos",
+ api_version="v1",
+ primary_keys=["id"],
+ partition_key="createdAt",
+ flatten_json_api=True,
+ # Without this filter the listing only covers meetings of the API key's own user.
+ params={"filter[all_team_members_dashboard]": "true"},
+ # Full refresh only: the v1 listing filters on `start_date` (the scheduled time, which a
+ # reschedule can move backwards) and exposes no creation/update timestamp filter, so a
+ # watermark sync could permanently skip rows.
+ ),
+ "demo_templates": DemodeskEndpointConfig(
+ name="demo_templates",
+ path="/v1/demo_templates",
+ api_version="v1",
+ primary_keys=["id"],
+ flatten_json_api=True,
+ ),
+ "users": DemodeskEndpointConfig(
+ name="users",
+ path="/v2/users",
+ api_version="v2",
+ primary_keys=["id"],
+ ),
+ "recordings": DemodeskEndpointConfig(
+ name="recordings",
+ path="/v2/recordings",
+ api_version="v2",
+ primary_keys=["recordingId"],
+ partition_key="createdAt",
+ incremental_fields=[
+ incremental_field("updatedAt"),
+ incremental_field("createdAt"),
+ ],
+ incremental_param_by_field={
+ "updatedAt": "filter[updated_at_gteq]",
+ "createdAt": "filter[created_at_gteq]",
+ },
+ default_incremental_field="updatedAt",
+ # The v2 cursor pagination documents no ordering guarantee, so the watermark must only be
+ # committed after a complete pass; "desc" is what makes the pipeline defer that commit.
+ sort_mode="desc",
+ ),
+ "recording_summaries": DemodeskEndpointConfig(
+ name="recording_summaries",
+ path="/v2/recordings/{recording_token}/summaries",
+ api_version="v2",
+ # Summary ids are not documented as globally unique, so the parent token is part of the key.
+ primary_keys=["recordingToken", "summaryId"],
+ partition_key="createdAt",
+ fanout=DependentEndpointConfig(
+ parent_name="recordings",
+ resolve_param="recording_token",
+ resolve_field="recordingToken",
+ include_from_parent=["recordingToken"],
+ parent_field_renames={"recordingToken": "recordingToken"},
+ # A recording deleted between the parent listing and this child fetch 404s; treat it
+ # as an empty child instead of failing the whole fan-out.
+ child_response_actions=[{"status_code": 404, "action": "ignore"}],
+ ),
+ ),
+ "recording_scorecards": DemodeskEndpointConfig(
+ name="recording_scorecards",
+ path="/v2/recordings/{recording_token}/scorecards",
+ api_version="v2",
+ primary_keys=["recordingToken", "scorecardId"],
+ partition_key="createdAt",
+ fanout=DependentEndpointConfig(
+ parent_name="recordings",
+ resolve_param="recording_token",
+ resolve_field="recordingToken",
+ include_from_parent=["recordingToken"],
+ parent_field_renames={"recordingToken": "recordingToken"},
+ child_response_actions=[{"status_code": 404, "action": "ignore"}],
+ ),
+ ),
+}
+
+ENDPOINTS = tuple(DEMODESK_ENDPOINTS.keys())
+
+INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {
+ name: config.incremental_fields for name, config in DEMODESK_ENDPOINTS.items() if config.incremental_fields
+}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/demodesk/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/demodesk/source.py
index db43a45a33df..655986ab762b 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/demodesk/source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/demodesk/source.py
@@ -1,8 +1,33 @@
-from typing import cast
+from typing import Optional, cast
-from products.warehouse_sources.backend.facade.source_config import DataWarehouseSourceCategory, SourceConfig
-from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, SimpleSource
+from products.warehouse_sources.backend.facade.source_config import (
+ DataWarehouseSourceCategory,
+ ReleaseStatus,
+ SourceConfig,
+ SourceFieldInputConfig,
+ SourceFieldInputConfigType,
+)
+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,
+ build_endpoint_schemas,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceInputs, SourceResponse
+from products.warehouse_sources.backend.temporal.data_imports.sources.demodesk.demodesk import (
+ DemodeskResumeConfig,
+ demodesk_source,
+ validate_credentials as validate_demodesk_credentials,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.demodesk.settings import (
+ DEMODESK_ENDPOINTS,
+ ENDPOINTS,
+ INCREMENTAL_FIELDS,
+)
from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.demodesk import (
DemodeskSourceConfig,
)
@@ -10,18 +35,122 @@ from products.warehouse_sources.backend.types import ExternalDataSourceType
@SourceRegistry.register
-class DemodeskSource(SimpleSource[DemodeskSourceConfig]):
+class DemodeskSource(ResumableSource[DemodeskSourceConfig, DemodeskResumeConfig]):
+ lists_tables_without_credentials = True # static endpoint catalog, safe for public docs
+
+ # Pinned to v2 (the vendor's recommended surface). Meeting endpoints still ride the legacy v1
+ # surface, which Demodesk keeps alive until those endpoints are migrated to v2.
+ supported_versions = ("v2",)
+ default_version = "v2"
+ api_docs_url = "https://demodesk.com/api/docs/index.html"
+
@property
def source_type(self) -> ExternalDataSourceType:
return ExternalDataSourceType.DEMODESK
+ def get_non_retryable_errors(self) -> dict[str, str | None]:
+ return {
+ "401 Client Error: Unauthorized for url": "Demodesk rejected the API key. Generate a new key in your Demodesk integration settings and reconnect.",
+ "403 Client Error: Forbidden for url": "The API key does not have access to this data. Use a company admin's API key to sync team-wide data.",
+ }
+
+ def get_canonical_descriptions(self) -> CanonicalDescriptions:
+ from products.warehouse_sources.backend.temporal.data_imports.sources.demodesk.canonical_descriptions import (
+ CANONICAL_DESCRIPTIONS,
+ )
+
+ return CANONICAL_DESCRIPTIONS
+
+ def get_schemas(
+ self,
+ config: DemodeskSourceConfig,
+ team_id: int,
+ with_counts: bool = False,
+ names: list[str] | None = None,
+ force_refresh: bool = False,
+ api_version: str | None = None,
+ ) -> list[SourceSchema]:
+ return build_endpoint_schemas(ENDPOINTS, INCREMENTAL_FIELDS, names)
+
+ def validate_credentials(
+ self,
+ config: DemodeskSourceConfig,
+ team_id: int,
+ schema_name: Optional[str] = None,
+ api_version: str | None = None,
+ ) -> tuple[bool, str | None]:
+ # requests encodes headers as latin-1, so a key with a non-ASCII character (for example an
+ # invisible one pasted from another app) would surface a raw UnicodeEncodeError.
+ if not config.api_key.isascii():
+ return (
+ False,
+ "The API key contains an unsupported character (for example an invisible one pasted "
+ "from another app). Retype it by hand and try again.",
+ )
+ return validate_demodesk_credentials(config.api_key)
+
+ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[DemodeskResumeConfig]:
+ return ResumableSourceManager[DemodeskResumeConfig](inputs, DemodeskResumeConfig)
+
+ def source_for_pipeline(
+ self,
+ config: DemodeskSourceConfig,
+ resumable_source_manager: ResumableSourceManager[DemodeskResumeConfig],
+ inputs: SourceInputs,
+ ) -> SourceResponse:
+ endpoint_config = DEMODESK_ENDPOINTS.get(inputs.schema_name)
+ if endpoint_config is None:
+ raise ValueError(f"Demodesk source has no schema named '{inputs.schema_name}'")
+
+ resource = demodesk_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,
+ should_use_incremental_field=inputs.should_use_incremental_field,
+ db_incremental_field_last_value=inputs.db_incremental_field_last_value
+ if inputs.should_use_incremental_field
+ else None,
+ incremental_field_name=inputs.incremental_field,
+ )
+
+ response = SourceResponse(
+ name=endpoint_config.name,
+ items=lambda: resource,
+ primary_keys=endpoint_config.primary_keys,
+ column_hints=resource.column_hints,
+ sort_mode=endpoint_config.sort_mode,
+ )
+ if endpoint_config.partition_key:
+ response.partition_count = 1
+ response.partition_size = 1
+ response.partition_mode = "datetime"
+ response.partition_format = "week"
+ response.partition_keys = [endpoint_config.partition_key]
+ return response
+
@property
def get_source_config(self) -> SourceConfig:
return SourceConfig(
name=ExternalDataSourceType.DEMODESK,
category=DataWarehouseSourceCategory.SALES,
label="Demodesk",
+ caption="Enter your Demodesk API key. Admins can generate one in Demodesk under integration settings, in the Demodesk API section. Use a company admin's key to sync team-wide meetings and recordings. A regular user's key only syncs what that user can see.",
+ docsUrl="https://posthog.com/docs/cdp/sources/demodesk",
iconPath="/static/services/demodesk.png",
- fields=cast(list[FieldType], []),
- unreleasedSource=True,
+ releaseStatus=ReleaseStatus.ALPHA,
+ 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/demodesk/tests/test_demodesk.py b/products/warehouse_sources/backend/temporal/data_imports/sources/demodesk/tests/test_demodesk.py
new file mode 100644
index 000000000000..7af38a22341b
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/demodesk/tests/test_demodesk.py
@@ -0,0 +1,415 @@
+import json
+from collections.abc import Iterable
+from datetime import UTC, datetime
+from typing import Any, cast
+
+import pytest
+from unittest.mock import MagicMock, patch
+
+from requests import Request, Response
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from products.warehouse_sources.backend.temporal.data_imports.sources.demodesk.demodesk import (
+ DemodeskPagePaginator,
+ DemodeskResumeConfig,
+ demodesk_source,
+ to_iso8601,
+ validate_credentials,
+)
+
+_SESSION_PATCH = (
+ "products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source"
+ ".rest_client.make_tracked_session"
+)
+
+
+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 TestDemodeskPagePaginator:
+ @pytest.mark.parametrize(
+ ("body", "expected_has_next"),
+ [
+ ({"data": [], "meta": {"currentPage": 1, "hasNextPage": True}}, True),
+ ({"data": [], "meta": {"currentPage": 1, "hasNextPage": False}}, False),
+ # An endpoint without pagination metadata must stop after its first page instead of
+ # looping on page=1 forever.
+ ({"data": []}, False),
+ ],
+ )
+ def test_update_state_stops_unless_has_next_page(self, body: dict[str, Any], expected_has_next: bool) -> None:
+ paginator = DemodeskPagePaginator()
+ paginator.update_state(_make_http_response(body))
+ assert paginator.has_next_page is expected_has_next
+
+ def test_pages_advance_from_one(self) -> None:
+ paginator = DemodeskPagePaginator()
+ request = Request(method="GET", url="https://demodesk.com/api/v1/demos")
+ paginator.init_request(request)
+ assert request.params["page"] == 1
+
+ paginator.update_state(_make_http_response({"data": [], "meta": {"hasNextPage": True}}))
+ paginator.update_request(request)
+ assert request.params["page"] == 2
+
+ def test_resume_state_round_trip(self) -> None:
+ paginator = DemodeskPagePaginator()
+ paginator.update_state(_make_http_response({"data": [], "meta": {"hasNextPage": True}}))
+ assert paginator.get_resume_state() == {"page": 2}
+
+ resumed = DemodeskPagePaginator()
+ resumed.set_resume_state({"page": 5})
+ request = Request(method="GET", url="https://demodesk.com/api/v1/demos")
+ resumed.init_request(request)
+ assert request.params["page"] == 5
+
+ def test_no_resume_state_on_terminal_page(self) -> None:
+ paginator = DemodeskPagePaginator()
+ paginator.update_state(_make_http_response({"data": [], "meta": {"hasNextPage": False}}))
+ assert paginator.get_resume_state() is None
+
+
+class RequestCapture:
+ def __init__(self, responses: list[Response] | None = None, by_url: dict[str, list[Response]] | None = None):
+ self.requests: list[Request] = []
+ self._responses = iter(responses or [])
+ self._by_url = {url: iter(items) for url, items in (by_url or {}).items()}
+
+ def send(self, request: Request, *_args: Any, **_kwargs: Any) -> Response:
+ # Requests are mutated in place by the paginator between pages, so keep a shallow copy.
+ copied = Request(method=request.method, url=request.url, headers=dict(request.headers or {}))
+ copied.params = dict(request.params or {})
+ # The mocked session skips prepare_request, where auth is normally applied; the auth
+ # classes only touch `.headers`, so applying them to the copy records what would be sent.
+ if request.auth is not None:
+ request.auth(copied)
+ self.requests.append(copied)
+ for url, response_iter in self._by_url.items():
+ if request.url and request.url.endswith(url):
+ return next(response_iter)
+ return next(self._responses)
+
+
+def _drive(
+ endpoint: str,
+ capture: RequestCapture,
+ manager: MagicMock | None = None,
+ *,
+ incremental: bool = False,
+ last_value: Any = None,
+ incremental_field_name: str | None = None,
+) -> tuple[MagicMock, list[dict[str, Any]]]:
+ if manager is None:
+ manager = MagicMock(spec=ResumableSourceManager)
+ manager.can_resume.return_value = False
+
+ with patch(_SESSION_PATCH) as MockSession:
+ mock_session = MockSession.return_value
+ mock_session.headers = {}
+ mock_session.prepare_request.side_effect = lambda req: req
+ mock_session.send.side_effect = capture.send
+
+ resource = demodesk_source(
+ api_key="test-key",
+ endpoint=endpoint,
+ team_id=123,
+ job_id="test_job",
+ resumable_source_manager=manager,
+ db_incremental_field_last_value=last_value,
+ should_use_incremental_field=incremental,
+ incremental_field_name=incremental_field_name,
+ )
+ rows: list[dict[str, Any]] = []
+ for page in cast(Iterable[Any], resource):
+ rows.extend(page if isinstance(page, list) else [page])
+ return manager, rows
+
+
+class TestDemodeskV1Demos:
+ def _pages(self) -> list[Response]:
+ return [
+ _make_http_response(
+ {
+ "data": [
+ {
+ "id": "1",
+ "type": "demos",
+ "attributes": {"account": "Acme intro", "status": "ended"},
+ "relationships": {"user": {"data": {"id": "9", "type": "users"}}},
+ }
+ ],
+ "meta": {"currentPage": 1, "hasNextPage": True},
+ }
+ ),
+ _make_http_response(
+ {
+ "data": [{"id": "2", "type": "demos", "attributes": {"account": "Acme follow-up"}}],
+ "meta": {"currentPage": 2, "hasNextPage": False},
+ }
+ ),
+ ]
+
+ def test_pages_follow_has_next_page_and_checkpoint_each_page(self) -> None:
+ capture = RequestCapture(self._pages())
+ manager, rows = _drive("demos", capture)
+
+ assert [r.params.get("page") for r in capture.requests] == [1, 2]
+ # Every page must request the team-wide view; without the filter only the key owner's
+ # meetings sync.
+ assert all(r.params.get("filter[all_team_members_dashboard]") == "true" for r in capture.requests)
+ saved = [call.args[0] for call in manager.save_state.call_args_list]
+ assert saved == [DemodeskResumeConfig(page=2)]
+
+ def test_v1_sends_api_key_header_not_bearer(self) -> None:
+ capture = RequestCapture(self._pages())
+ _drive("demos", capture)
+
+ first = capture.requests[0]
+ assert first.headers.get("api-key") == "test-key"
+ assert "Authorization" not in first.headers
+
+ def test_attributes_are_flattened_into_row_root(self) -> None:
+ capture = RequestCapture(self._pages())
+ _, rows = _drive("demos", capture)
+
+ assert rows[0]["id"] == "1"
+ assert rows[0]["account"] == "Acme intro"
+ assert "attributes" not in rows[0]
+ assert rows[0]["relationships"]["user"]["data"]["id"] == "9"
+
+ def test_resume_seeds_page(self) -> None:
+ manager = MagicMock(spec=ResumableSourceManager)
+ manager.can_resume.return_value = True
+ manager.load_state.return_value = DemodeskResumeConfig(page=7)
+
+ capture = RequestCapture([_make_http_response({"data": [], "meta": {"currentPage": 7, "hasNextPage": False}})])
+ _drive("demos", capture, manager)
+
+ assert [r.params.get("page") for r in capture.requests] == [7]
+
+ def test_terminal_single_page_saves_no_state(self) -> None:
+ capture = RequestCapture(
+ [
+ _make_http_response(
+ {"data": [{"id": "1", "type": "demos", "attributes": {}}], "meta": {"hasNextPage": False}}
+ )
+ ]
+ )
+ manager, _ = _drive("demos", capture)
+ manager.save_state.assert_not_called()
+
+
+class TestDemodeskV2Recordings:
+ def _pages(self) -> list[Response]:
+ return [
+ _make_http_response(
+ {
+ "data": [{"recordingId": "10", "recordingToken": "tokA", "createdAt": "2026-01-01T00:00:00Z"}],
+ "meta": {"hasNext": True, "limit": 100, "nextCursor": "cur-1"},
+ }
+ ),
+ _make_http_response(
+ {
+ "data": [{"recordingId": "11", "recordingToken": "tokB", "createdAt": "2026-01-02T00:00:00Z"}],
+ "meta": {"hasNext": False, "limit": 100, "nextCursor": None},
+ }
+ ),
+ ]
+
+ def test_cursor_pagination_follows_next_cursor_and_checkpoints(self) -> None:
+ capture = RequestCapture(self._pages())
+ manager, rows = _drive("recordings", capture)
+
+ assert [r.params.get("cursor") for r in capture.requests] == [None, "cur-1"]
+ assert all(r.params.get("limit") == 100 for r in capture.requests)
+ saved = [call.args[0] for call in manager.save_state.call_args_list]
+ assert saved == [DemodeskResumeConfig(cursor="cur-1")]
+ assert [row["recordingId"] for row in rows] == ["10", "11"]
+
+ def test_v2_sends_bearer_auth(self) -> None:
+ capture = RequestCapture(self._pages())
+ _drive("recordings", capture)
+
+ assert capture.requests[0].headers.get("Authorization") == "Bearer test-key"
+
+ def test_resume_seeds_cursor(self) -> None:
+ manager = MagicMock(spec=ResumableSourceManager)
+ manager.can_resume.return_value = True
+ manager.load_state.return_value = DemodeskResumeConfig(cursor="cur-resumed")
+
+ capture = RequestCapture([_make_http_response({"data": [], "meta": {"hasNext": False, "limit": 100}})])
+ _drive("recordings", capture, manager)
+
+ assert [r.params.get("cursor") for r in capture.requests] == ["cur-resumed"]
+
+ @pytest.mark.parametrize(
+ ("incremental_field_name", "expected_param"),
+ [
+ ("updatedAt", "filter[updated_at_gteq]"),
+ ("createdAt", "filter[created_at_gteq]"),
+ # No explicit choice falls back to the default cursor field.
+ (None, "filter[updated_at_gteq]"),
+ ],
+ )
+ def test_incremental_sync_with_watermark_sends_server_side_filter(
+ self, incremental_field_name: str | None, expected_param: str
+ ) -> None:
+ capture = RequestCapture([_make_http_response({"data": [], "meta": {"hasNext": False, "limit": 100}})])
+ _drive(
+ "recordings",
+ capture,
+ incremental=True,
+ last_value=datetime(2026, 1, 15, 12, 30, tzinfo=UTC),
+ incremental_field_name=incremental_field_name,
+ )
+
+ assert capture.requests[0].params.get(expected_param) == "2026-01-15T12:30:00Z"
+
+ @pytest.mark.parametrize(
+ ("incremental", "last_value"),
+ [
+ # The first incremental sync has no watermark yet and must fetch the full history.
+ (True, None),
+ (False, None),
+ # A full refresh must ignore a stale watermark left over from an earlier incremental run.
+ (False, datetime(2026, 1, 15, tzinfo=UTC)),
+ ],
+ )
+ def test_no_filter_without_watermarked_incremental_sync(self, incremental: bool, last_value: Any) -> None:
+ capture = RequestCapture([_make_http_response({"data": [], "meta": {"hasNext": False, "limit": 100}})])
+ _drive("recordings", capture, incremental=incremental, last_value=last_value)
+
+ sent = capture.requests[0].params
+ assert "filter[updated_at_gteq]" not in sent
+ assert "filter[created_at_gteq]" not in sent
+
+
+class TestDemodeskFanout:
+ def test_child_rows_carry_parent_token_and_404_parents_are_skipped(self) -> None:
+ capture = RequestCapture(
+ by_url={
+ "/v2/recordings": [
+ _make_http_response(
+ {
+ "data": [{"recordingToken": "tokA"}, {"recordingToken": "tokB"}],
+ "meta": {"hasNext": False, "limit": 100},
+ }
+ )
+ ],
+ # tokA was deleted between the listing and the child fetch; the fan-out must skip
+ # it instead of failing the whole sync.
+ "/v2/recordings/tokA/summaries": [_make_http_response({"error": {"code": "not_found"}}, 404)],
+ "/v2/recordings/tokB/summaries": [
+ _make_http_response({"data": [{"summaryId": "s1", "content": "Recap"}]})
+ ],
+ }
+ )
+ _, rows = _drive("recording_summaries", capture)
+
+ assert len(rows) == 1
+ assert rows[0]["summaryId"] == "s1"
+ assert rows[0]["recordingToken"] == "tokB"
+
+ def test_checkpoints_each_completed_parent(self) -> None:
+ capture = RequestCapture(
+ by_url={
+ "/v2/recordings": [
+ _make_http_response(
+ {
+ "data": [{"recordingToken": "tokA"}, {"recordingToken": "tokB"}],
+ "meta": {"hasNext": False, "limit": 100},
+ }
+ )
+ ],
+ "/v2/recordings/tokA/summaries": [_make_http_response({"data": [{"summaryId": "sA"}]})],
+ "/v2/recordings/tokB/summaries": [_make_http_response({"data": [{"summaryId": "sB"}]})],
+ }
+ )
+ manager, rows = _drive("recording_summaries", capture)
+
+ assert [row["summaryId"] for row in rows] == ["sA", "sB"]
+ saved = [call.args[0] for call in manager.save_state.call_args_list]
+ assert saved, "a crash mid fan-out must be able to resume, so each parent has to checkpoint"
+ last_state = saved[-1].fanout_state
+ assert last_state is not None
+ assert last_state["completed"] == ["/v2/recordings/tokA/summaries", "/v2/recordings/tokB/summaries"]
+ assert last_state["current"] is None
+
+ def test_resume_skips_already_completed_parent(self) -> None:
+ manager = MagicMock(spec=ResumableSourceManager)
+ manager.can_resume.return_value = True
+ manager.load_state.return_value = DemodeskResumeConfig(
+ fanout_state={"completed": ["/v2/recordings/tokA/summaries"], "current": None, "child_state": None}
+ )
+ capture = RequestCapture(
+ by_url={
+ "/v2/recordings": [
+ _make_http_response(
+ {
+ "data": [{"recordingToken": "tokA"}, {"recordingToken": "tokB"}],
+ "meta": {"hasNext": False, "limit": 100},
+ }
+ )
+ ],
+ # No entry for tokA's summaries: a request there would raise StopIteration,
+ # proving a resumed run does not re-fetch an already-completed parent.
+ "/v2/recordings/tokB/summaries": [_make_http_response({"data": [{"summaryId": "sB"}]})],
+ }
+ )
+ _, rows = _drive("recording_summaries", capture, manager)
+
+ assert [row["summaryId"] for row in rows] == ["sB"]
+
+
+class TestValidateCredentials:
+ @pytest.mark.parametrize(
+ ("status_code", "expected_valid", "expected_message_part"),
+ [
+ (200, True, None),
+ (401, False, "rejected the API key"),
+ (403, False, "rejected the API key"),
+ (500, False, "HTTP 500"),
+ ],
+ )
+ def test_status_mapping(self, status_code: int, expected_valid: bool, expected_message_part: str | None) -> None:
+ with patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.demodesk.demodesk.make_tracked_session"
+ ) as MockSession:
+ MockSession.return_value.get.return_value = _make_http_response({}, status_code)
+ is_valid, message = validate_credentials("test-key")
+
+ assert is_valid is expected_valid
+ if expected_message_part is None:
+ assert message is None
+ else:
+ assert message is not None and expected_message_part in message
+
+ def test_network_error_returns_false_instead_of_raising(self) -> None:
+ from requests.exceptions import ConnectionError
+
+ with patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.demodesk.demodesk.make_tracked_session"
+ ) as MockSession:
+ MockSession.return_value.get.side_effect = ConnectionError("boom")
+ is_valid, message = validate_credentials("test-key")
+
+ assert (is_valid, message) == (False, "boom")
+
+
+class TestToIso8601:
+ @pytest.mark.parametrize(
+ ("value", "expected"),
+ [
+ (datetime(2026, 1, 15, 12, 30, tzinfo=UTC), "2026-01-15T12:30:00Z"),
+ # A naive watermark from the schema config is treated as UTC, not local time.
+ (datetime(2026, 1, 15, 12, 30), "2026-01-15T12:30:00Z"),
+ ("2026-01-15T12:30:00Z", "2026-01-15T12:30:00Z"),
+ ],
+ )
+ def test_formats_watermark(self, value: Any, expected: str) -> None:
+ assert to_iso8601(value) == expected
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/demodesk/tests/test_demodesk_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/demodesk/tests/test_demodesk_source.py
new file mode 100644
index 000000000000..208e240d1d62
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/demodesk/tests/test_demodesk_source.py
@@ -0,0 +1,40 @@
+import pytest
+from unittest.mock import MagicMock, patch
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceInputs
+from products.warehouse_sources.backend.temporal.data_imports.sources.demodesk.source import DemodeskSource
+from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.demodesk import (
+ DemodeskSourceConfig,
+)
+
+_VALIDATE = (
+ "products.warehouse_sources.backend.temporal.data_imports.sources.demodesk.source.validate_demodesk_credentials"
+)
+
+
+class TestDemodeskSourceValidateCredentials:
+ def test_rejects_non_ascii_key_without_calling_the_api(self) -> None:
+ config = DemodeskSourceConfig(api_key="key​with-invisible-char")
+ with patch(_VALIDATE) as mock_validate:
+ is_valid, message = DemodeskSource().validate_credentials(config, team_id=1)
+
+ assert is_valid is False
+ assert message is not None and "unsupported character" in message
+ mock_validate.assert_not_called()
+
+ def test_forwards_ascii_key_to_the_api_probe(self) -> None:
+ config = DemodeskSourceConfig(api_key="plain-key")
+ with patch(_VALIDATE, return_value=(True, None)) as mock_validate:
+ assert DemodeskSource().validate_credentials(config, team_id=1) == (True, None)
+ mock_validate.assert_called_once_with("plain-key")
+
+
+class TestDemodeskSourceForPipeline:
+ def test_unknown_schema_raises(self) -> None:
+ inputs = MagicMock(spec=SourceInputs)
+ inputs.schema_name = "not_a_demodesk_table"
+ manager = MagicMock(spec=ResumableSourceManager)
+
+ with pytest.raises(ValueError, match="no schema named"):
+ DemodeskSource().source_for_pipeline(DemodeskSourceConfig(api_key="key"), manager, inputs)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/demodesk.py b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/demodesk.py
index 74c608ccd09d..b6561cdcef2d 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/demodesk.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/demodesk.py
@@ -6,4 +6,4 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common imp
@config.config
class DemodeskSourceConfig(config.Config):
- pass
+ api_key: str