:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(data-warehouse): add Courier source (#73209)
Tom Owers60d60eb527e7
diff --git a/frontend/public/services/courier.png b/frontend/public/services/courier.pngindex 11bf5a540225..6c41211952a6 100644Binary files a/frontend/public/services/courier.png and b/frontend/public/services/courier.png differdiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.mdindex 32cfdc114b41..f24ab0835d71 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md@@ -160,6 +160,7 @@ the row lists both.| copper | HTTP | requests | ✅ || coralogix | HTTP | requests | ✅ || coupa | HTTP | requests | ✅ |+| courier | HTTP | requests + `rest_source.RESTClient` | ✅ || coveralls | HTTP | requests | ✅ || crates_io | HTTP | requests | ✅ || cronitor | HTTP | requests | ✅ |@@ -848,7 +849,6 @@ doesn't conflict with concurrent PRs.- cortex- cosmosdb- couchbase-- courier- crisp- criteo- crossrefdiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/courier/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/courier/canonical_descriptions.pynew file mode 100644index 000000000000..951d0f55a658--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/courier/canonical_descriptions.py@@ -0,0 +1,76 @@+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (+ CanonicalDescriptions,+)++CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {+ "Messages": {+ "description": "A message you've sent through Courier, with its current delivery status and engagement timestamps.",+ "docs_url": "https://www.courier.com/docs/reference/messages/list",+ "columns": {+ "id": "Unique identifier associated with the message (the result from a /send or /send/list call).",+ "enqueued": "UTC timestamp at which Courier received the message request.",+ "event": "Unique identifier associated with the event that triggered the message.",+ "notification": "Unique identifier associated with the notification used to send the message.",+ "recipient": "Unique identifier associated with the recipient of the message.",+ "status": "Current status of the message (e.g. ENQUEUED, SENT, DELIVERED, OPENED, CLICKED, UNDELIVERABLE).",+ "clicked": "UTC timestamp at which the recipient first clicked a tracked link, if any.",+ "delivered": "UTC timestamp at which the integration provider delivered the message, if any.",+ "error": "Message describing the error that occurred, if the send failed.",+ "opened": "UTC timestamp at which the recipient first opened the message, if any.",+ "reason": "Reason for the current status (e.g. BOUNCED, FILTERED, UNSUBSCRIBED, PROVIDER_ERROR), if applicable.",+ "sent": "UTC timestamp at which Courier passed the message to the integration provider, if any.",+ },+ },+ "AuditEvents": {+ "description": "An account-level activity log entry recording an action taken by a user or API key in your Courier workspace.",+ "docs_url": "https://www.courier.com/docs/reference/audit-events/list",+ "columns": {+ "auditEventId": "Unique identifier for the audit event.",+ "actor": "The user or API key that performed the action, including their id and email.",+ "source": "The origin of the action (e.g. dashboard, api).",+ "target": "The resource the action was performed on.",+ "timestamp": "UTC timestamp at which the action occurred.",+ "type": "The type of action that was performed (e.g. resource.created, resource.updated).",+ },+ },+ "Audiences": {+ "description": "A saved, filter-defined segment of recipients used to target notifications.",+ "docs_url": "https://www.courier.com/docs/reference/audiences/list",+ "columns": {+ "id": "Unique identifier for the audience.",+ "name": "Name of the audience.",+ "description": "Description of the audience.",+ "created_at": "Timestamp at which the audience was created.",+ "updated_at": "Timestamp at which the audience was last updated.",+ "filter": "Filter configuration (rules and operator) defining audience membership.",+ "operator": "Logical operator (AND/OR) combining the top-level filter rules.",+ },+ },+ "Brands": {+ "description": "A branding profile (colors, logo, templates) that can be applied to messages sent through Courier.",+ "docs_url": "https://www.courier.com/docs/reference/brands/list",+ "columns": {+ "id": "Unique identifier for the brand.",+ "name": "Name of the brand.",+ "created": "Timestamp at which the brand was created.",+ "updated": "Timestamp at which the brand was last updated.",+ "published": "Timestamp at which the brand was last published, if any.",+ "settings": "Brand settings, including email and in-app configuration.",+ "snippets": "Reusable Handlebars snippets available to templates using this brand.",+ "version": "Version identifier of the brand.",+ },+ },+ "Tenants": {+ "description": "A tenant used to scope notification sending and preferences for a group of recipients (e.g. a customer account).",+ "docs_url": "https://www.courier.com/docs/reference/tenants/list",+ "columns": {+ "id": "Unique identifier for the tenant.",+ "name": "Name of the tenant.",+ "brand_id": "Brand used for the tenant when one is not specified by the send call.",+ "parent_tenant_id": "Parent tenant's id, if this tenant is nested under another.",+ "properties": "Arbitrary properties accessible to a template.",+ "user_profile": "A user profile object merged with the recipient's profile on send.",+ "default_preferences": "Notification preferences used for the tenant when the recipient hasn't specified their own.",+ },+ },+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/courier/courier.py b/products/warehouse_sources/backend/temporal/data_imports/sources/courier/courier.pynew file mode 100644index 000000000000..82a0049351e5--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/courier/courier.py@@ -0,0 +1,184 @@+import dataclasses+from datetime import UTC, datetime+from typing import Any, Optional++from dateutil import parser as date_parser++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.rest_source import (+ RESTAPIConfig,+ rest_api_resource,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.typing import EndpointResource+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.courier.settings import (+ COURIER_BASE_URL,+ COURIER_PAGE_SIZE,+ ENDPOINTS_CONFIG,+)++# Courier returns HTTP 403 (not 401) for both a missing and an invalid bearer token, with this+# message in the body — confirmed by probing the live API with no/bad credentials.+AUTH_ERROR_MESSAGE = "Invalid or missing authentication credentials"++DEFAULT_INCREMENTAL_START = "1970-01-01T00:00:00Z"+++class CourierResumeConfig:+ cursor: str+++def _to_iso8601(value: Any) -> str:+ if isinstance(value, datetime):+ return value.isoformat()+ return str(value)+++def _normalize_row(item: dict[str, Any], timestamp_fields: tuple[str, ...]) -> dict[str, Any]:+ """Convert Courier's epoch-millisecond and ISO-8601 date fields to real datetimes.++ The warehouse then types these columns as timestamps (useful for querying) and the+ partitioner reads the datetime directly rather than misinterpreting raw millis as epoch+ seconds or leaving a string uninterpreted.+ """+ for name in timestamp_fields:+ value = item.get(name)+ if value is None:+ continue+ if isinstance(value, bool):+ continue+ if isinstance(value, int):+ item[name] = datetime.fromtimestamp(value / 1000, tz=UTC)+ elif isinstance(value, str):+ try:+ item[name] = date_parser.isoparse(value)+ except ValueError:+ pass+ return item+++def get_resource(name: str, should_use_incremental_field: bool) -> EndpointResource:+ config = ENDPOINTS_CONFIG[name]++ params: dict[str, Any] = {"limit": COURIER_PAGE_SIZE}+ if should_use_incremental_field and config.incremental_param and config.incremental_fields:+ params[config.incremental_param] = {+ "type": "incremental",+ "cursor_path": config.incremental_fields[0]["field"],+ "initial_value": DEFAULT_INCREMENTAL_START,+ "convert": _to_iso8601,+ }++ def data_map(item: dict[str, Any]) -> dict[str, Any]:+ return _normalize_row(item, config.timestamp_fields)++ endpoint_resource: EndpointResource = {+ "name": name,+ "table_name": name,+ "write_disposition": {+ "disposition": "merge",+ "strategy": "upsert",+ }+ if should_use_incremental_field+ else "replace",+ "endpoint": {+ "path": config.path,+ "params": params,+ "data_selector": config.data_selector,+ # Fail loud if Courier ever changes the response envelope key instead of silently+ # syncing 0 rows.+ "data_selector_required": True,+ },+ "table_format": "delta",+ }+ if config.timestamp_fields:+ endpoint_resource["data_map"] = data_map+ return endpoint_resource+++def courier_source(+ api_key: str,+ endpoint: str,+ team_id: int,+ job_id: str,+ resumable_source_manager: ResumableSourceManager[CourierResumeConfig],+ db_incremental_field_last_value: Optional[Any],+ should_use_incremental_field: bool = False,+) -> SourceResponse:+ config = ENDPOINTS_CONFIG[endpoint]++ rest_config: RESTAPIConfig = {+ "client": {+ "base_url": COURIER_BASE_URL,+ "auth": {+ "type": "bearer",+ "token": api_key,+ },+ "headers": {"Accept": "application/json"},+ "paginator": {+ "type": "cursor",+ "cursor_path": config.cursor_path,+ "cursor_param": "cursor",+ },+ },+ "resource_defaults": {},+ "resources": [get_resource(endpoint, should_use_incremental_field)],+ }++ 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 = {"cursor": resume_config.cursor}++ def save_checkpoint(state: Optional[dict[str, Any]]) -> None:+ # Only persist when there's a next page to resume to; the Redis TTL handles cleanup on+ # completion.+ if state and state.get("cursor"):+ resumable_source_manager.save_state(CourierResumeConfig(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,+ )++ has_partition_key = config.partition_key is not None++ return SourceResponse(+ name=endpoint,+ items=lambda: resource,+ primary_keys=list(config.primary_keys),+ partition_count=1 if has_partition_key else None,+ partition_size=1 if has_partition_key else None,+ partition_mode="datetime" if has_partition_key else None,+ partition_format="month" if has_partition_key else None,+ partition_keys=[config.partition_key] if config.partition_key else None,+ sort_mode=config.sort_mode,+ column_hints=resource.column_hints,+ )+++def validate_credentials(api_key: str) -> tuple[bool, str | None]:+ ok, status = validate_via_probe(+ lambda: make_tracked_session(redact_values=(api_key,)),+ f"{COURIER_BASE_URL}/messages?limit=1",+ headers={"Authorization": f"Bearer {api_key}", "Accept": "application/json"},+ ok_statuses=(200,),+ # Courier's bearer auth carries the token in the standard `Authorization` header, which+ # `requests` already strips on cross-origin redirects.+ allow_redirects=True,+ )+ if ok:+ return True, None++ if status == 403:+ return False, f"Courier authentication failed: {AUTH_ERROR_MESSAGE}. Please check your API key."++ return False, f"Courier API returned an unexpected response (HTTP {status})"diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/courier/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/courier/settings.pynew file mode 100644index 000000000000..563302f1f99d--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/courier/settings.py@@ -0,0 +1,88 @@+from dataclasses import dataclass, field++from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import SortMode+from products.warehouse_sources.backend.temporal.data_imports.sources.common.schema import incremental_field+from products.warehouse_sources.backend.types import IncrementalField++COURIER_BASE_URL = "https://api.courier.com"++# Courier's default page size is small (~10 messages/page per the vendor docs); raising `limit`+# cuts the round-trips a full backfill needs. No documented maximum, so we stay conservative.+COURIER_PAGE_SIZE = 100+++@dataclass(frozen=True)+class CourierEndpointConfig:+ path: str+ # The list of records is wrapped under a named key that varies per endpoint ("results" vs+ # "items").+ data_selector: str+ primary_keys: tuple[str, ...] = ("id",)+ incremental_fields: list[IncrementalField] = field(default_factory=list)+ # Request param carrying the server-side lower-bound timestamp filter.+ incremental_param: str | None = None+ # Stable datetime field to partition on; None disables partitioning.+ partition_key: str | None = None+ # Courier's list endpoints document no explicit sort param at all. Treated as newest-first+ # (matching Knock's identical no-sort-param message-log endpoint) rather than assumed+ # ascending, which would silently corrupt the incremental watermark if wrong.+ sort_mode: SortMode = "asc"+ # Where the paginator finds the next-page cursor in the response body: nested under `paging`+ # for every list endpoint except Tenants, which returns `cursor` at the top level.+ cursor_path: str = "paging.cursor"+ # Fields that arrive as epoch-millisecond ints or ISO-8601 strings and are converted to real+ # datetimes before yielding, so partitioning and incremental filtering see proper timestamps+ # instead of raw millis (which the partitioner would otherwise misread as epoch seconds).+ timestamp_fields: tuple[str, ...] = ()+++ENDPOINTS_CONFIG: dict[str, CourierEndpointConfig] = {+ # The primary stream: per-message delivery status/history. `enqueued_after` is a documented+ # server-side filter, so incremental sync genuinely reduces pages.+ "Messages": CourierEndpointConfig(+ path="/messages",+ data_selector="results",+ primary_keys=("id",),+ incremental_fields=[incremental_field("enqueued")],+ incremental_param="enqueued_after",+ partition_key="enqueued",+ sort_mode="desc",+ timestamp_fields=("enqueued", "sent", "delivered", "opened", "clicked"),+ ),+ # Account activity log. No server-side timestamp filter is documented, so full refresh only.+ "AuditEvents": CourierEndpointConfig(+ path="/audit-events",+ data_selector="results",+ primary_keys=("auditEventId",),+ partition_key="timestamp",+ timestamp_fields=("timestamp",),+ ),+ # Saved recipient segments. No server-side timestamp filter is documented.+ "Audiences": CourierEndpointConfig(+ path="/audiences",+ data_selector="items",+ primary_keys=("id",),+ partition_key="created_at",+ timestamp_fields=("created_at", "updated_at"),+ ),+ # Branding profiles (templates/colors/logos). No server-side timestamp filter, and the+ # `created`/`updated` unix timestamps are undocumented as to unit, so no partitioning.+ "Brands": CourierEndpointConfig(+ path="/brands",+ data_selector="results",+ primary_keys=("id",),+ ),+ # Multi-tenant scoping objects. No timestamp fields at all, so no partitioning.+ "Tenants": CourierEndpointConfig(+ path="/tenants",+ data_selector="items",+ primary_keys=("id",),+ cursor_path="cursor",+ ),+}++ENDPOINTS = tuple(ENDPOINTS_CONFIG.keys())++INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {+ name: config.incremental_fields for name, config in ENDPOINTS_CONFIG.items()+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/courier/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/courier/source.pyindex 5d4d0ea3750b..b30c14f8730e 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/courier/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/courier/source.py@@ -1,13 +1,37 @@-from typing import cast+from typing import Optional, castfrom 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,+ build_endpoint_schemas,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.courier.courier import (+ CourierResumeConfig,+ courier_source,+ validate_credentials as validate_courier_credentials,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.courier.settings import (+ ENDPOINTS,+ INCREMENTAL_FIELDS,+)from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.courier import (CourierSourceConfig,)@@ -15,18 +39,89 @@ from products.warehouse_sources.backend.types import ExternalDataSourceType@SourceRegistry.register-class CourierSource(SimpleSource[CourierSourceConfig]):+class CourierSource(ResumableSource[CourierSourceConfig, CourierResumeConfig]):+ lists_tables_without_credentials = True # static endpoint catalog — safe for public docs+ api_docs_url = "https://www.courier.com/docs/reference/get-started/"+@propertydef source_type(self) -> ExternalDataSourceType:return ExternalDataSourceType.COURIER+ def get_non_retryable_errors(self) -> dict[str, str | None]:+ return {+ "403 Client Error: Forbidden for url": "Your Courier API key is invalid or has been revoked. Please generate a new key in the Courier dashboard and reconnect.",+ }++ def get_canonical_descriptions(self) -> CanonicalDescriptions:+ from products.warehouse_sources.backend.temporal.data_imports.sources.courier.canonical_descriptions import (+ CANONICAL_DESCRIPTIONS,+ )++ return CANONICAL_DESCRIPTIONS++ def get_schemas(+ self,+ config: CourierSourceConfig,+ 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: CourierSourceConfig,+ team_id: int,+ schema_name: Optional[str] = None,+ api_version: str | None = None,+ ) -> tuple[bool, str | None]:+ return validate_courier_credentials(config.api_key)++ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[CourierResumeConfig]:+ return ResumableSourceManager[CourierResumeConfig](inputs, CourierResumeConfig)++ def source_for_pipeline(+ self,+ config: CourierSourceConfig,+ resumable_source_manager: ResumableSourceManager[CourierResumeConfig],+ inputs: SourceInputs,+ ) -> SourceResponse:+ return courier_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,+ )+@propertydef get_source_config(self) -> SourceConfig:return SourceConfig(name=SchemaExternalDataSourceType.COURIER,category=DataWarehouseSourceCategory.COMMUNICATION,- label="Courier (trycourier.com)",+ label="Courier",+ caption="Use an API key from the Courier dashboard under **Settings → API Keys**. Either the Live or Test key works; the key determines which environment's data is synced.",+ docsUrl="https://posthog.com/docs/cdp/sources/courier",iconPath="/static/services/courier.png",- fields=cast(list[FieldType], []),- unreleasedSource=True,+ keywords=["notifications", "messaging"],+ 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/courier/tests/test_courier.py b/products/warehouse_sources/backend/temporal/data_imports/sources/courier/tests/test_courier.pynew file mode 100644index 000000000000..c36f978a8135--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/courier/tests/test_courier.py@@ -0,0 +1,281 @@+import json+from collections.abc import Iterable+from datetime import UTC, datetime+from typing import Any, Optional, cast++from unittest.mock import MagicMock, patch++from parameterized import parameterized+from requests import Response++from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import SourceResponse+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from products.warehouse_sources.backend.temporal.data_imports.sources.courier.courier import (+ CourierResumeConfig,+ courier_source,+ get_resource,+ validate_credentials,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.courier.settings import ENDPOINTS_CONFIG++CLIENT_SESSION_PATCH = "products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.rest_client.make_tracked_session"+COURIER_SESSION_PATCH = (+ "products.warehouse_sources.backend.temporal.data_imports.sources.courier.courier.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+++def _page(endpoint: str, rows: list[dict[str, Any]], cursor: str | None) -> Response:+ """Build a page response using this endpoint's real envelope shape.++ Every endpoint but Tenants nests the cursor under `paging`; Tenants returns it at the+ response's top level.+ """+ config = ENDPOINTS_CONFIG[endpoint]+ body: dict[str, Any] = {config.data_selector: rows}+ if config.cursor_path == "cursor":+ body["cursor"] = cursor+ body["has_more"] = cursor is not None+ else:+ body["paging"] = {"more": cursor is not None, "cursor": cursor}+ return _make_http_response(body)+++class TestGetResource:+ def test_incremental_uses_enqueued_after_filter(self) -> None:+ resource = get_resource("Messages", should_use_incremental_field=True)+ params = cast(dict[str, Any], cast(dict[str, Any], resource["endpoint"])["params"])+ assert params["enqueued_after"]["type"] == "incremental"+ assert params["enqueued_after"]["cursor_path"] == "enqueued"+ assert resource["write_disposition"] == {"disposition": "merge", "strategy": "upsert"}++ @parameterized.expand([("Messages",), ("AuditEvents",), ("Audiences",), ("Brands",), ("Tenants",)])+ def test_full_refresh_sends_no_timestamp_filter(self, endpoint: str) -> None:+ resource = get_resource(endpoint, should_use_incremental_field=False)+ params = cast(dict[str, Any], cast(dict[str, Any], resource["endpoint"])["params"])+ assert set(params) == {"limit"}+ assert resource["write_disposition"] == "replace"++ @parameterized.expand([("AuditEvents",), ("Audiences",), ("Brands",), ("Tenants",)])+ def test_endpoints_without_a_server_filter_ignore_incremental_flag(self, endpoint: str) -> None:+ # These endpoints have no documented server-side timestamp filter, so even if asked for+ # an incremental run there is no filter param to add.+ resource = get_resource(endpoint, should_use_incremental_field=True)+ params = cast(dict[str, Any], cast(dict[str, Any], resource["endpoint"])["params"])+ assert set(params) == {"limit"}+++class TestCourierSourceTransport:+ def _drive(+ self,+ endpoint: str,+ manager: MagicMock,+ responses: list[Response],+ should_use_incremental_field: bool = False,+ db_incremental_field_last_value: Optional[Any] = None,+ ) -> tuple[SourceResponse, list[dict[str, Any]], 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(CLIENT_SESSION_PATCH) as mock_session_factory:+ mock_session = mock_session_factory.return_value+ mock_session.headers = {}+ mock_session.prepare_request.side_effect = lambda req: req+ mock_session.send.side_effect = fake_send++ source_response = courier_source(+ api_key="sk_test",+ endpoint=endpoint,+ team_id=123,+ job_id="test_job",+ resumable_source_manager=manager,+ db_incremental_field_last_value=db_incremental_field_last_value,+ should_use_incremental_field=should_use_incremental_field,+ )+ rows = [row for chunk in cast(Iterable[Any], source_response.items()) for row in chunk]+ return source_response, sent_params, rows++ @parameterized.expand(+ [+ ("Messages",),+ ("AuditEvents",),+ ("Audiences",),+ ("Brands",),+ ("Tenants",),+ ]+ )+ def test_rows_extracted_from_endpoint_envelope(self, endpoint: str) -> None:+ # A swapped `data_selector` ("results" vs "items", or the wrong top-level cursor key for+ # Tenants) silently syncs 0 rows instead of raising, so this locks the real shape in.+ manager = MagicMock(spec=ResumableSourceManager)+ manager.can_resume.return_value = False++ responses = [_page(endpoint, [{"id": "a"}, {"id": "b"}], cursor=None)]+ _, _, rows = self._drive(endpoint, manager, responses)++ assert [row["id"] for row in rows] == ["a", "b"]++ def test_fresh_run_pages_on_cursor_and_saves_state(self) -> None:+ manager = MagicMock(spec=ResumableSourceManager)+ manager.can_resume.return_value = False++ responses = [+ _page("Messages", [{"id": "m1"}], cursor="cursor-1"),+ _page("Messages", [{"id": "m2"}], cursor="cursor-2"),+ _page("Messages", [{"id": "m3"}], cursor=None),+ ]+ _, sent_params, rows = self._drive("Messages", manager, responses)++ assert [p.get("cursor") for p in sent_params] == [None, "cursor-1", "cursor-2"]+ assert all(p.get("limit") == 100 for p in sent_params)+ assert [row["id"] for row in rows] == ["m1", "m2", "m3"]++ saved = [call.args[0] for call in manager.save_state.call_args_list]+ assert saved == [CourierResumeConfig(cursor="cursor-1"), CourierResumeConfig(cursor="cursor-2")]++ def test_tenants_pages_on_top_level_cursor(self) -> None:+ # Tenants is the one endpoint whose cursor lives at the response's top level rather than+ # nested under `paging` — a regression here silently disables pagination.+ manager = MagicMock(spec=ResumableSourceManager)+ manager.can_resume.return_value = False++ responses = [+ _page("Tenants", [{"id": "t1"}], cursor="cursor-1"),+ _page("Tenants", [{"id": "t2"}], cursor=None),+ ]+ _, sent_params, rows = self._drive("Tenants", manager, responses)++ assert [p.get("cursor") for p in sent_params] == [None, "cursor-1"]+ assert [row["id"] for row in rows] == ["t1", "t2"]++ def test_resume_seeds_paginator_with_saved_cursor(self) -> None:+ manager = MagicMock(spec=ResumableSourceManager)+ manager.can_resume.return_value = True+ manager.load_state.return_value = CourierResumeConfig(cursor="cursor-resumed")++ responses = [_page("Messages", [{"id": "m9"}], cursor=None)]+ _, sent_params, _ = self._drive("Messages", manager, responses)++ assert [p.get("cursor") for p in sent_params] == ["cursor-resumed"]++ def test_terminal_single_page_does_not_save_state(self) -> None:+ manager = MagicMock(spec=ResumableSourceManager)+ manager.can_resume.return_value = False++ self._drive("Messages", manager, [_page("Messages", [{"id": "only"}], cursor=None)])++ manager.save_state.assert_not_called()++ def test_incremental_run_sends_watermark_as_iso8601(self) -> None:+ manager = MagicMock(spec=ResumableSourceManager)+ manager.can_resume.return_value = False++ responses = [_page("Messages", [{"id": "m1"}], cursor=None)]+ _, sent_params, _ = self._drive(+ "Messages",+ manager,+ responses,+ should_use_incremental_field=True,+ db_incremental_field_last_value=datetime(2026, 5, 1, 12, 30),+ )++ assert sent_params[0]["enqueued_after"] == "2026-05-01T12:30:00"++ def test_incremental_first_sync_defaults_to_epoch_start(self) -> None:+ # No prior watermark (first incremental sync): must fall back to a real ISO-8601 value,+ # not stringify `None` into the literal "enqueued_after=None".+ manager = MagicMock(spec=ResumableSourceManager)+ manager.can_resume.return_value = False++ responses = [_page("Messages", [{"id": "m1"}], cursor=None)]+ _, sent_params, _ = self._drive(+ "Messages",+ manager,+ responses,+ should_use_incremental_field=True,+ db_incremental_field_last_value=None,+ )++ assert sent_params[0]["enqueued_after"] == "1970-01-01T00:00:00Z"++ def test_epoch_millis_fields_are_converted_to_datetime(self) -> None:+ # `enqueued`/`sent`/etc. arrive as epoch-millisecond ints; left unconverted, the+ # partitioner would misread them as epoch seconds and bucket everything into the wrong+ # decade.+ manager = MagicMock(spec=ResumableSourceManager)+ manager.can_resume.return_value = False++ responses = [_page("Messages", [{"id": "m1", "enqueued": 1_700_000_000_000, "sent": None}], cursor=None)]+ _, _, rows = self._drive("Messages", manager, responses)++ assert rows[0]["enqueued"] == datetime.fromtimestamp(1_700_000_000_000 / 1000, tz=UTC)+ assert rows[0]["sent"] is None++ def test_iso_string_fields_are_converted_to_datetime(self) -> None:+ manager = MagicMock(spec=ResumableSourceManager)+ manager.can_resume.return_value = False++ responses = [_page("Audiences", [{"id": "a1", "created_at": "2026-01-15T10:30:00Z"}], cursor=None)]+ _, _, rows = self._drive("Audiences", manager, responses)++ assert rows[0]["created_at"] == datetime(2026, 1, 15, 10, 30, 0, tzinfo=UTC)++ @parameterized.expand(+ [+ ("Messages", ["enqueued"], "desc"),+ ("AuditEvents", ["timestamp"], "asc"),+ ("Audiences", ["created_at"], "asc"),+ ("Brands", None, "asc"),+ ("Tenants", None, "asc"),+ ]+ )+ def test_source_response_partitioning_and_sort_mode(+ self, endpoint: str, partition_keys: list[str] | None, sort_mode: str+ ) -> None:+ manager = MagicMock(spec=ResumableSourceManager)+ manager.can_resume.return_value = False++ source_response, _, _ = self._drive(endpoint, manager, [_page(endpoint, [], cursor=None)])++ assert source_response.primary_keys == list(ENDPOINTS_CONFIG[endpoint].primary_keys)+ assert source_response.sort_mode == sort_mode+ assert source_response.partition_keys == partition_keys+ assert source_response.partition_mode == ("datetime" if partition_keys else None)+++class TestValidateCredentials:+ @parameterized.expand(+ [+ ("valid", 200, (True, None)),+ (+ "invalid_key",+ 403,+ (+ False,+ "Courier authentication failed: Invalid or missing authentication credentials. Please check your API key.",+ ),+ ),+ ("server_error", 500, (False, "Courier API returned an unexpected response (HTTP 500)")),+ ]+ )+ def test_status_mapping(self, _name: str, status_code: int, expected: tuple[bool, str | None]) -> None:+ with patch(COURIER_SESSION_PATCH) as mock_make_session:+ mock_make_session.return_value.get.return_value = _make_http_response({}, status_code)+ assert validate_credentials("sk_test") == expected++ def test_network_error_is_false(self) -> None:+ with patch(COURIER_SESSION_PATCH) as mock_make_session:+ mock_make_session.return_value.get.side_effect = Exception("boom")+ ok, message = validate_credentials("sk_test")+ assert ok is Falsediff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/courier/tests/test_courier_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/courier/tests/test_courier_source.pynew file mode 100644index 000000000000..67309c5fb105--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/courier/tests/test_courier_source.py@@ -0,0 +1,121 @@+from typing import Any++from unittest.mock import MagicMock, patch++from parameterized import parameterized++from posthog.schema import DataWarehouseSourceCategory, ReleaseStatus, SourceFieldInputConfig++from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from products.warehouse_sources.backend.temporal.data_imports.sources.courier.courier import CourierResumeConfig+from products.warehouse_sources.backend.temporal.data_imports.sources.courier.settings import ENDPOINTS+from products.warehouse_sources.backend.temporal.data_imports.sources.courier.source import CourierSource+from products.warehouse_sources.backend.types import ExternalDataSourceType+++def _config(api_key: str = "sk_test") -> Any:+ config = MagicMock()+ config.api_key = api_key+ return config+++class TestSourceConfig:+ def test_source_type(self) -> None:+ assert CourierSource().source_type == ExternalDataSourceType.COURIER++ def test_config_is_visible_and_alpha(self) -> None:+ config = CourierSource().get_source_config+ # A finished source must not be hidden from users.+ assert getattr(config, "unreleasedSource", None) in (None, False)+ assert config.releaseStatus == ReleaseStatus.ALPHA+ assert config.category == DataWarehouseSourceCategory.COMMUNICATION+ assert config.docsUrl == "https://posthog.com/docs/cdp/sources/courier"++ def test_fields(self) -> None:+ fields = {f.name: f for f in CourierSource().get_source_config.fields if isinstance(f, SourceFieldInputConfig)}+ assert set(fields) == {"api_key"}+ assert fields["api_key"].required is True+ assert fields["api_key"].secret is True++ def test_non_retryable_errors_cover_auth_failure(self) -> None:+ errors = CourierSource().get_non_retryable_errors()+ assert any("403" in key for key in errors)+++class TestGetSchemas:+ def test_only_server_side_filtered_endpoints_are_incremental(self) -> None:+ schemas = {s.name: s for s in CourierSource().get_schemas(_config(), team_id=1)}+ assert set(schemas) == set(ENDPOINTS)+ # Only Messages (enqueued_after) has a genuine server-side timestamp filter.+ assert {name for name, s in schemas.items() if s.supports_incremental} == {"Messages"}+ assert [f["field"] for f in schemas["Messages"].incremental_fields] == ["enqueued"]++ def test_names_filter(self) -> None:+ schemas = CourierSource().get_schemas(_config(), team_id=1, names=["Brands", "Tenants"])+ assert {s.name for s in schemas} == {"Brands", "Tenants"}++ def test_lists_tables_without_credentials(self) -> None:+ # Static endpoint catalog (no I/O) — public docs render the table list.+ assert CourierSource.lists_tables_without_credentials is True+ tables = {t["name"]: t for t in CourierSource().get_documented_tables()}+ assert set(tables) == set(ENDPOINTS)+ assert tables["Brands"]["sync_methods"] == ["Full refresh"]+ assert "Incremental" in tables["Messages"]["sync_methods"]+++class TestValidateCredentials:+ @parameterized.expand(+ [+ ("valid", (True, None)),+ ("invalid", (False, "Courier authentication failed: Invalid or missing authentication credentials.")),+ ]+ )+ def test_plumbs_transport_result(self, _name: str, result: tuple[bool, str | None]) -> None:+ with patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.courier.source.validate_courier_credentials",+ return_value=result,+ ) as mocked:+ assert CourierSource().validate_credentials(_config(), team_id=1) == result+ mocked.assert_called_once_with("sk_test")+++class TestResumableWiring:+ def test_get_resumable_source_manager_binds_data_class(self) -> None:+ inputs = MagicMock()+ inputs.logger = MagicMock()+ manager = CourierSource().get_resumable_source_manager(inputs)+ assert isinstance(manager, ResumableSourceManager)+ assert manager._data_class is CourierResumeConfig++ @parameterized.expand(+ [+ ("incremental", True, "2026-01-01"),+ # A stale watermark must not leak into a full-refresh run.+ ("full_refresh", False, None),+ ]+ )+ def test_source_for_pipeline_plumbs_arguments(+ self, _name: str, should_use_incremental_field: bool, expected_last_value: Any+ ) -> None:+ inputs = MagicMock()+ inputs.schema_name = "Messages"+ inputs.team_id = 42+ inputs.job_id = "job-1"+ inputs.should_use_incremental_field = should_use_incremental_field+ inputs.db_incremental_field_last_value = "2026-01-01"+ manager = MagicMock()++ with patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.courier.source.courier_source"+ ) as mocked:+ CourierSource().source_for_pipeline(_config(), manager, inputs)++ mocked.assert_called_once_with(+ api_key="sk_test",+ endpoint="Messages",+ team_id=42,+ job_id="job-1",+ resumable_source_manager=manager,+ should_use_incremental_field=should_use_incremental_field,+ db_incremental_field_last_value=expected_last_value,+ )diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/courier.py b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/courier.pyindex f4e1088ef488..ab7a10612eea 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/courier.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/courier.py@@ -6,4 +6,4 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common imp@config.configclass CourierSourceConfig(config.Config):- pass+ api_key: str