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(courier): sync message history, audience members, list subs and templates (#103720)

Tom Owersbace19559591
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.md b/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.md
index 1bcbe1cb69f9..12726af2e301 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.md
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.md
@@ -2104,15 +2104,15 @@ Note: Coupa Core API is very large (several hundred documented resources across
## Courier — gaps
-Today (5): `Audiences`, `AuditEvents`, `Brands`, `Messages`, `Tenants`
+Today (9): `AudienceMembers`, `Audiences`, `AuditEvents`, `Brands`, `ListSubscriptions`, `MessageHistory`, `Messages`, `NotificationTemplates`, `Tenants`
Diffed against: <https://www.courier.com/docs/llms.txt>
- [ ] `lists (GET /lists)` — core recipient grouping object; currently no way to see which lists exist (high)
-- [ ] `lists/{list_id}/subscriptions` — membership table mapping users to lists - required for any audience-size or churn analysis (high)
-- [ ] `notification-templates (GET /notifications)` — lookup table resolving the template IDs carried on every synced message (high)
-- [ ] `messages/{id}/history` — per-message state transition history (queued, sent, delivered, opened, clicked) - the deliverability funnel (high)
-- [ ] `audiences/{audience_id}/members` — membership table for audiences we already sync; audiences without members are just filter definitions (high)
+- [x] `lists/{list_id}/subscriptions` — membership table mapping users to lists - required for any audience-size or churn analysis (high)
+- [x] `notification-templates (GET /notifications)` — lookup table resolving the template IDs carried on every synced message (high)
+- [x] `messages/{id}/history` — per-message state transition history (queued, sent, delivered, opened, clicked) - the deliverability funnel (high)
+- [x] `audiences/{audience_id}/members` — membership table for audiences we already sync; audiences without members are just filter definitions (high)
- [ ] `tenants/{tenant_id}/users` — membership table joining users to the tenants we already sync (medium)
- [ ] `automations (GET /automations)` — lookup for saved automation templates that trigger sends (medium)
- [ ] `journeys (GET /journeys, plus journey versions)` — journey definitions and versions needed to attribute messages to a flow (medium)
diff --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.py
index 951d0f55a658..d993afe847ab 100644
--- 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.py
@@ -21,6 +21,16 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
"sent": "UTC timestamp at which Courier passed the message to the integration provider, if any.",
},
},
+ "MessageHistory": {
+ "description": "One entry per status transition of a sent message, giving the delivery funnel behind the message's current status.",
+ "docs_url": "https://www.courier.com/docs/api-reference/messages/get-message-history",
+ "columns": {
+ "message_id": "Unique identifier of the message this transition belongs to.",
+ "type": "The status the message moved into (e.g. ENQUEUED, ROUTED, SENT, DELIVERED, OPENED, CLICKED, UNDELIVERABLE).",
+ "ts": "Timestamp at which the message entered this status.",
+ "enqueued": "UTC timestamp at which Courier received the message request.",
+ },
+ },
"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",
@@ -46,6 +56,17 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
"operator": "Logical operator (AND/OR) combining the top-level filter rules.",
},
},
+ "AudienceMembers": {
+ "description": "A user currently matching an audience's filter. Courier recalculates membership as user profiles change.",
+ "docs_url": "https://www.courier.com/docs/api-reference/audiences/list-audience-members",
+ "columns": {
+ "audience_id": "Unique identifier of the audience the user belongs to.",
+ "member_id": "Unique identifier of the user matching the audience filter.",
+ "added_at": "Timestamp at which the user was added to the audience.",
+ "audience_version": "Version of the audience filter the membership was calculated against.",
+ "reason": "Why the user matches the audience filter.",
+ },
+ },
"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",
@@ -60,6 +81,31 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
"version": "Version identifier of the brand.",
},
},
+ "ListSubscriptions": {
+ "description": "A user's subscription to a list, with the notification preferences recorded for that subscription.",
+ "docs_url": "https://www.courier.com/docs/api-reference/lists/list-subscriptions-for-a-list",
+ "columns": {
+ "list_id": "Unique identifier of the list the user is subscribed to.",
+ "recipientId": "Unique identifier of the subscribed user.",
+ "created": "Timestamp at which the subscription was created.",
+ "preferences": "Notification preferences (per category and per template) recorded for this subscription.",
+ },
+ },
+ "NotificationTemplates": {
+ "description": "A notification template in the workspace, resolving the template id every sent message carries.",
+ "docs_url": "https://www.courier.com/docs/api-reference/templates/list-notification-templates",
+ "columns": {
+ "id": "Unique identifier for the notification template.",
+ "title": "Name of the notification template.",
+ "created_at": "Timestamp at which the template was created.",
+ "updated_at": "Timestamp at which the template was last updated.",
+ "routing": "Routing configuration (method and channels) the template sends through.",
+ "tags": "Tags applied to the template.",
+ "topic_id": "Subscription topic the template is linked to.",
+ "note": "Note stored against the template. Legacy templates only.",
+ "event_ids": "Event ids mapped to this template.",
+ },
+ },
"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",
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.py
index 1c111301c370..77b6b76c121f 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/courier/courier.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/courier/courier.py
@@ -1,15 +1,29 @@
import dataclasses
from datetime import UTC, datetime
-from typing import Any, Optional
+from typing import Any, Optional, cast
from dateutil import parser as date_parser
+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.typing import EndpointResource
+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 (
+ 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 (
+ ClientConfig,
+ Endpoint,
+ EndpointResource,
+ IncrementalConfig,
+)
from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
from products.warehouse_sources.backend.temporal.data_imports.sources.common.source_helpers import validate_via_probe
from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceResponse
@@ -17,6 +31,8 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.courier.se
COURIER_BASE_URL,
COURIER_PAGE_SIZE,
ENDPOINTS_CONFIG,
+ FANOUT_ENDPOINT_CONFIGS,
+ CourierEndpointConfig,
)
# Courier returns HTTP 403 (not 401) for both a missing and an invalid bearer token, with this
@@ -26,9 +42,15 @@ AUTH_ERROR_MESSAGE = "Invalid or missing authentication credentials"
DEFAULT_INCREMENTAL_START = "1970-01-01T00:00:00Z"
+@frozen
class CourierResumeConfig:
- cursor: str
+ # Top-level endpoints resume from the cursor of the last fully-yielded page.
+ cursor: str | None = None
+ # Fan-out endpoints resume by parent: the child paths already fully synced, the one in
+ # progress, and that parent's paginator state.
+ completed: list[str] | None = None
+ current: str | None = None
+ child_state: dict[str, Any] | None = None
def _to_iso8601(value: Any) -> str:
@@ -99,31 +121,34 @@ def get_resource(name: str, should_use_incremental_field: bool) -> EndpointResou
return endpoint_resource
-def courier_source(
+def _client_config(api_key: str, config: CourierEndpointConfig) -> ClientConfig:
+ return {
+ "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",
+ },
+ }
+
+
+def _top_level_resource(
+ config: CourierEndpointConfig,
api_key: str,
endpoint: str,
team_id: int,
job_id: str,
resumable_source_manager: ResumableSourceManager[CourierResumeConfig],
+ should_use_incremental_field: bool,
db_incremental_field_last_value: Optional[Any],
- should_use_incremental_field: bool = False,
-) -> SourceResponse:
- config = ENDPOINTS_CONFIG[endpoint]
-
+) -> Resource:
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",
- },
- },
+ "client": _client_config(api_key, config),
"resource_defaults": {},
"resources": [get_resource(endpoint, should_use_incremental_field)],
}
@@ -131,7 +156,7 @@ def courier_source(
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 is not None and resume_config.cursor:
initial_paginator_state = {"cursor": resume_config.cursor}
def save_checkpoint(state: Optional[dict[str, Any]]) -> None:
@@ -140,7 +165,7 @@ def courier_source(
if state and state.get("cursor"):
resumable_source_manager.save_state(CourierResumeConfig(cursor=str(state["cursor"])))
- resource = rest_api_resource(
+ return rest_api_resource(
rest_config,
team_id,
job_id,
@@ -149,6 +174,118 @@ def courier_source(
initial_paginator_state=initial_paginator_state,
)
+
+def _fanout_resource(
+ config: CourierEndpointConfig,
+ api_key: str,
+ endpoint: str,
+ team_id: int,
+ job_id: str,
+ resumable_source_manager: ResumableSourceManager[CourierResumeConfig],
+ should_use_incremental_field: bool,
+ db_incremental_field_last_value: Optional[Any],
+) -> Resource:
+ assert config.fanout is not None
+ fanout = config.fanout
+ parent_config = FANOUT_ENDPOINT_CONFIGS[fanout.parent_name]
+
+ if config.parent_incremental_param and should_use_incremental_field:
+ # The child endpoint takes no timestamp filter, so the run is bounded by the parent
+ # listing instead. Like the Messages table, this means a record whose parent predates
+ # the watermark is not revisited, even if the vendor added an entry to it since.
+ fanout = dataclasses.replace(
+ fanout,
+ parent_params={
+ **fanout.parent_params,
+ config.parent_incremental_param: _to_iso8601(db_incremental_field_last_value)
+ if db_incremental_field_last_value
+ else DEFAULT_INCREMENTAL_START,
+ },
+ )
+
+ initial_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 and (resume_config.completed or resume_config.current):
+ initial_state = {
+ "completed": resume_config.completed or [],
+ "current": resume_config.current,
+ "child_state": resume_config.child_state,
+ }
+
+ def save_checkpoint(state: Optional[dict[str, Any]]) -> None:
+ if state is not None:
+ resumable_source_manager.save_state(
+ CourierResumeConfig(
+ completed=state.get("completed"),
+ current=state.get("current"),
+ child_state=state.get("child_state"),
+ )
+ )
+
+ child_endpoint_extra: Endpoint = {
+ "data_selector": config.data_selector,
+ "data_selector_required": True,
+ }
+ if not config.paginated:
+ child_endpoint_extra["paginator"] = SinglePagePaginator()
+
+ def no_child_time_filter(_field: str) -> IncrementalConfig | None:
+ # No Courier fan-out child accepts a timestamp filter of its own; an incremental run is
+ # bounded through the parent listing and merges on the primary key.
+ return None
+
+ resource = build_dependent_resource(
+ endpoint_configs=FANOUT_ENDPOINT_CONFIGS,
+ child_endpoint=endpoint,
+ fanout=fanout,
+ client_config=_client_config(api_key, config),
+ 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_config_factory=no_child_time_filter,
+ parent_endpoint_extra={
+ "data_selector": parent_config.data_selector,
+ "data_selector_required": True,
+ },
+ child_endpoint_extra=child_endpoint_extra,
+ resume_hook=save_checkpoint,
+ initial_paginator_state=initial_state,
+ )
+
+ child = cast(Resource, resource)
+ if config.timestamp_fields:
+ # Applied after build_dependent_resource renames the projected parent fields, so a
+ # parent timestamp is normalized under the name it ends up with.
+ child = child.add_map(lambda item: _normalize_row(item, config.timestamp_fields))
+ return child
+
+
+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]
+
+ build = _fanout_resource if config.fanout is not None else _top_level_resource
+ resource = build(
+ config,
+ api_key,
+ endpoint,
+ team_id,
+ job_id,
+ resumable_source_manager,
+ should_use_incremental_field,
+ db_incremental_field_last_value,
+ )
+
has_partition_key = config.partition_key is not None
return SourceResponse(
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.py
index 68195cde458f..ae8ed7db2083 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/courier/settings.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/courier/settings.py
@@ -1,6 +1,9 @@
from dataclasses import dataclass, field
from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import UNVERSIONED_API_VERSION
+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
@@ -24,6 +27,7 @@ COURIER_PAGE_SIZE = 100
@dataclass(frozen=True)
class CourierEndpointConfig:
+ name: str
path: str
# The list of records is wrapped under a named key that varies per endpoint ("results" vs
# "items").
@@ -45,12 +49,36 @@ class CourierEndpointConfig:
# 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, ...] = ()
+ page_size: int = COURIER_PAGE_SIZE
+ # False where the endpoint returns every record in one response and takes no cursor.
+ paginated: bool = True
+ # Set where the endpoint only exists per parent record, so rows are collected by walking the
+ # parent listing first.
+ fanout: DependentEndpointConfig | None = None
+ # Filter param on the *parent* listing, for a fan-out child whose own endpoint takes no
+ # timestamp filter. Bounding the parent walk is the only way such a child can sync
+ # incrementally instead of re-fetching every parent's records every run.
+ parent_incremental_param: str | None = None
+ @property
+ def default_incremental_field(self) -> str | None:
+ return self.incremental_fields[0]["field"] if self.incremental_fields else None
+
+
+# Parent listings a fan-out endpoint walks that are not themselves syncable tables.
+FANOUT_ONLY_CONFIGS: dict[str, CourierEndpointConfig] = {
+ "Lists": CourierEndpointConfig(
+ name="Lists",
+ path="/lists",
+ data_selector="items",
+ ),
+}
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(
+ name="Messages",
path="/messages",
data_selector="results",
primary_keys=("id",),
@@ -60,8 +88,38 @@ ENDPOINTS_CONFIG: dict[str, CourierEndpointConfig] = {
sort_mode="desc",
timestamp_fields=("enqueued", "sent", "delivered", "opened", "clicked"),
),
+ # Per-message state transitions (enqueued, sent, delivered, opened, clicked). The Messages
+ # row only carries the end state, so this is where the deliverability funnel lives.
+ "MessageHistory": CourierEndpointConfig(
+ name="MessageHistory",
+ path="/messages/{message_id}/history",
+ data_selector="results",
+ # Courier types the entries as free-form objects. `type` is the endpoint's own filter
+ # param and the response is documented as one entry per status transition with its
+ # timestamp, so the transition and its `ts` are what identifies a row within a message.
+ primary_keys=("message_id", "type", "ts"),
+ # Projected from the parent message, because the entries carry no timestamp Courier can
+ # filter on. See `parent_incremental_param`.
+ incremental_fields=[incremental_field("enqueued")],
+ parent_incremental_param="enqueued_after",
+ partition_key="enqueued",
+ sort_mode="desc",
+ timestamp_fields=("ts", "enqueued"),
+ paginated=False,
+ fanout=DependentEndpointConfig(
+ parent_name="Messages",
+ resolve_param="message_id",
+ resolve_field="id",
+ include_from_parent=["id", "enqueued"],
+ parent_field_renames={"id": "message_id", "enqueued": "enqueued"},
+ # A message archived or aged out of log retention between the listing and this
+ # fetch 404s; that parent is skipped rather than failing the whole fan-out.
+ child_response_actions=[{"status_code": 404, "action": "ignore"}],
+ ),
+ ),
# Account activity log. No server-side timestamp filter is documented, so full refresh only.
"AuditEvents": CourierEndpointConfig(
+ name="AuditEvents",
path="/audit-events",
data_selector="results",
primary_keys=("auditEventId",),
@@ -70,21 +128,72 @@ ENDPOINTS_CONFIG: dict[str, CourierEndpointConfig] = {
),
# Saved recipient segments. No server-side timestamp filter is documented.
"Audiences": CourierEndpointConfig(
+ name="Audiences",
path="/audiences",
data_selector="items",
primary_keys=("id",),
partition_key="created_at",
timestamp_fields=("created_at", "updated_at"),
),
+ # Who currently matches each audience filter. Courier recalculates membership as profiles
+ # change and exposes no timestamp filter, so full refresh only.
+ "AudienceMembers": CourierEndpointConfig(
+ name="AudienceMembers",
+ path="/audiences/{audience_id}/members",
+ data_selector="items",
+ # `member_id` is the user, unique only within its audience. Each row already carries its
+ # own `audience_id`, so nothing has to be projected from the parent to key it.
+ primary_keys=("audience_id", "member_id"),
+ partition_key="added_at",
+ timestamp_fields=("added_at",),
+ fanout=DependentEndpointConfig(
+ parent_name="Audiences",
+ resolve_param="audience_id",
+ resolve_field="id",
+ include_from_parent=[],
+ ),
+ ),
# 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(
+ name="Brands",
path="/brands",
data_selector="results",
primary_keys=("id",),
),
+ # Who is subscribed to each list. Courier documents no timestamp filter on either the list
+ # walk or the subscriptions, so full refresh only.
+ "ListSubscriptions": CourierEndpointConfig(
+ name="ListSubscriptions",
+ path="/lists/{list_id}/subscriptions",
+ data_selector="items",
+ # The subscription carries the recipient but no reference back to its list, so the
+ # parent's id is projected in to make rows joinable and unique across lists.
+ primary_keys=("list_id", "recipientId"),
+ partition_key="created",
+ timestamp_fields=("created",),
+ fanout=DependentEndpointConfig(
+ parent_name="Lists",
+ resolve_param="list_id",
+ resolve_field="id",
+ include_from_parent=["id"],
+ parent_field_renames={"id": "list_id"},
+ # A list deleted between the listing and this fetch 404s; skip that parent rather
+ # than failing the whole fan-out.
+ child_response_actions=[{"status_code": 404, "action": "ignore"}],
+ ),
+ ),
+ # The template catalog resolving the `notification` id every message carries. Like Brands,
+ # `created_at`/`updated_at` are int64s of undocumented unit, so no partitioning.
+ "NotificationTemplates": CourierEndpointConfig(
+ name="NotificationTemplates",
+ path="/notifications",
+ data_selector="results",
+ primary_keys=("id",),
+ ),
# Multi-tenant scoping objects. No timestamp fields at all, so no partitioning.
"Tenants": CourierEndpointConfig(
+ name="Tenants",
path="/tenants",
data_selector="items",
primary_keys=("id",),
@@ -92,6 +201,9 @@ ENDPOINTS_CONFIG: dict[str, CourierEndpointConfig] = {
),
}
+# Every config a fan-out can resolve a parent against, syncable or not.
+FANOUT_ENDPOINT_CONFIGS: dict[str, CourierEndpointConfig] = {**ENDPOINTS_CONFIG, **FANOUT_ONLY_CONFIGS}
+
ENDPOINTS = tuple(ENDPOINTS_CONFIG.keys())
INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {
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.py
index e284c00ccacc..ec1b815b6e36 100644
--- 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.py
@@ -2,6 +2,7 @@ import json
from collections.abc import Iterable
from datetime import UTC, datetime
from typing import Any, Optional, cast
+from urllib.parse import urlparse
from unittest.mock import MagicMock, patch
@@ -16,7 +17,10 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.courier.co
get_resource,
validate_credentials,
)
-from products.warehouse_sources.backend.temporal.data_imports.sources.courier.settings import ENDPOINTS_CONFIG
+from products.warehouse_sources.backend.temporal.data_imports.sources.courier.settings import (
+ ENDPOINTS_CONFIG,
+ FANOUT_ENDPOINT_CONFIGS,
+)
CLIENT_SESSION_PATCH = "products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.rest_client.make_tracked_session"
COURIER_SESSION_PATCH = (
@@ -38,7 +42,7 @@ def _page(endpoint: str, rows: list[dict[str, Any]], cursor: str | None) -> Resp
Every endpoint but Tenants nests the cursor under `paging`; Tenants returns it at the
response's top level.
"""
- config = ENDPOINTS_CONFIG[endpoint]
+ config = FANOUT_ENDPOINT_CONFIGS[endpoint]
body: dict[str, Any] = {config.data_selector: rows}
if config.cursor_path == "cursor":
body["cursor"] = cursor
@@ -56,14 +60,16 @@ class TestGetResource:
assert params["enqueued_after"]["cursor_path"] == "enqueued"
assert resource["write_disposition"] == {"disposition": "merge", "strategy": "upsert"}
- @parameterized.expand([("Messages",), ("AuditEvents",), ("Audiences",), ("Brands",), ("Tenants",)])
+ @parameterized.expand(
+ [("Messages",), ("AuditEvents",), ("Audiences",), ("Brands",), ("NotificationTemplates",), ("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",)])
+ @parameterized.expand([("AuditEvents",), ("Audiences",), ("Brands",), ("NotificationTemplates",), ("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.
@@ -112,6 +118,7 @@ class TestCourierSourceTransport:
("AuditEvents",),
("Audiences",),
("Brands",),
+ ("NotificationTemplates",),
("Tenants",),
]
)
@@ -237,6 +244,7 @@ class TestCourierSourceTransport:
("AuditEvents", ["timestamp"], "asc"),
("Audiences", ["created_at"], "asc"),
("Brands", None, "asc"),
+ ("NotificationTemplates", None, "asc"),
("Tenants", None, "asc"),
]
)
@@ -254,6 +262,118 @@ class TestCourierSourceTransport:
assert source_response.partition_mode == ("datetime" if partition_keys else None)
+class TestCourierFanout:
+ """Endpoints reachable only per parent record: the parent listing is walked first."""
+
+ def _drive(
+ self,
+ endpoint: str,
+ responses: list[Response],
+ should_use_incremental_field: bool = False,
+ db_incremental_field_last_value: Optional[Any] = None,
+ ) -> tuple[list[str], list[dict[str, Any]], list[dict[str, Any]]]:
+ manager = MagicMock(spec=ResumableSourceManager)
+ manager.can_resume.return_value = False
+
+ sent_paths: list[str] = []
+ sent_params: list[dict[str, Any]] = []
+ response_iter = iter(responses)
+
+ def fake_send(request: Any, *_args: Any, **_kwargs: Any) -> Response:
+ sent_paths.append(urlparse(request.url).path)
+ 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 sent_paths, sent_params, rows
+
+ def test_audience_members_are_fetched_per_audience(self) -> None:
+ paths, _, rows = self._drive(
+ "AudienceMembers",
+ [
+ _page("Audiences", [{"id": "aud-1"}, {"id": "aud-2"}], cursor=None),
+ _page("AudienceMembers", [{"audience_id": "aud-1", "member_id": "u1"}], cursor=None),
+ _page("AudienceMembers", [{"audience_id": "aud-2", "member_id": "u2"}], cursor=None),
+ ],
+ )
+
+ assert paths == ["/audiences", "/audiences/aud-1/members", "/audiences/aud-2/members"]
+ assert [(row["audience_id"], row["member_id"]) for row in rows] == [("aud-1", "u1"), ("aud-2", "u2")]
+
+ def test_list_subscriptions_carry_their_list_id(self) -> None:
+ # The subscription object has no reference back to its list, so without the projected
+ # parent id the primary key collapses to the recipient and rows collide across lists.
+ paths, _, rows = self._drive(
+ "ListSubscriptions",
+ [
+ _page("Lists", [{"id": "list-a"}], cursor=None),
+ _page("ListSubscriptions", [{"recipientId": "u1", "created": "2026-01-15T10:30:00Z"}], cursor=None),
+ ],
+ )
+
+ assert paths == ["/lists", "/lists/list-a/subscriptions"]
+ assert rows[0]["list_id"] == "list-a"
+ assert rows[0]["created"] == datetime(2026, 1, 15, 10, 30, 0, tzinfo=UTC)
+
+ def test_message_history_projects_and_normalizes_the_parent_message(self) -> None:
+ paths, _, rows = self._drive(
+ "MessageHistory",
+ [
+ _page("Messages", [{"id": "msg-1", "enqueued": 1_700_000_000_000}], cursor=None),
+ _page("MessageHistory", [{"type": "SENT", "ts": 1_700_000_001_000}], cursor=None),
+ ],
+ )
+
+ assert paths == ["/messages", "/messages/msg-1/history"]
+ assert rows[0]["message_id"] == "msg-1"
+ # The projected parent timestamp is what the table partitions on and keys its watermark
+ # from, so it has to arrive as a datetime rather than raw epoch millis.
+ assert rows[0]["enqueued"] == datetime.fromtimestamp(1_700_000_000_000 / 1000, tz=UTC)
+ assert rows[0]["ts"] == datetime.fromtimestamp(1_700_000_001_000 / 1000, tz=UTC)
+
+ def test_message_history_incremental_bounds_the_parent_listing(self) -> None:
+ # The history endpoint takes no timestamp filter, so an incremental run can only avoid
+ # re-fetching every message's history by windowing the parent listing.
+ _, params, _ = self._drive(
+ "MessageHistory",
+ [
+ _page("Messages", [{"id": "msg-1", "enqueued": 1_700_000_000_000}], cursor=None),
+ _page("MessageHistory", [{"type": "SENT", "ts": 1_700_000_001_000}], cursor=None),
+ ],
+ should_use_incremental_field=True,
+ db_incremental_field_last_value=datetime(2026, 5, 1, 12, 30),
+ )
+
+ assert params[0]["enqueued_after"] == "2026-05-01T12:30:00"
+ assert "enqueued_after" not in params[1]
+
+ def test_message_history_full_refresh_sends_no_watermark(self) -> None:
+ _, params, _ = self._drive(
+ "MessageHistory",
+ [
+ _page("Messages", [{"id": "msg-1", "enqueued": 1_700_000_000_000}], cursor=None),
+ _page("MessageHistory", [], cursor=None),
+ ],
+ )
+
+ assert all("enqueued_after" not in p for p in params)
+
+
class TestValidateCredentials:
@parameterized.expand(
[
diff --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.py
index 1bd242acf833..55e39d5fed73 100644
--- 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.py
@@ -30,8 +30,9 @@ 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"}
+ # Messages filters on `enqueued_after`; MessageHistory has no filter of its own and
+ # inherits that window through its parent listing.
+ assert {name for name, s in schemas.items() if s.supports_incremental} == {"Messages", "MessageHistory"}
assert [f["field"] for f in schemas["Messages"].incremental_fields] == ["enqueued"]
def test_lists_tables_without_credentials(self) -> None: