: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(drip): add campaign membership, tag and custom field tables (#105909)
Tom Owersf46b5a667533
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.mdindex 7c4df6d83072..a5a611a8161b 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@@ -2641,14 +2641,14 @@ Note: Drata publishes no standalone spec file; the full OpenAPI document is embe## Drip — gaps-Today (6): `broadcasts`, `campaigns`, `forms`, `goals`, `subscribers`, `workflows`+Today (9): `broadcasts`, `campaign_subscribers`, `campaigns`, `custom_field_identifiers`, `forms`, `goals`, `subscribers`, `tags`, `workflows`Diffed against: <https://developer.drip.com/>-- [ ] `GET /v2/{account_id}/campaigns/{campaign_id}/subscribers` — campaign↔subscriber membership with subscription status; campaigns and subscribers both sync with nothing joining them (high)-- [ ] `GET /v2/{account_id}/subscribers/{id}/campaign_subscriptions` — per-subscriber campaign subscription records including started/completed state (high)-- [ ] `GET /v2/{account_id}/tags` — account tag lookup; tags drive Drip segmentation and are entirely absent (medium)-- [ ] `GET /v2/{account_id}/custom_field_identifiers` — lookup enumerating the custom field keys present on subscriber records (medium)+- [x] `GET /v2/{account_id}/campaigns/{campaign_id}/subscribers` — campaign↔subscriber membership with subscription status; campaigns and subscribers both sync with nothing joining them (high)+- [ ] `GET /v2/{account_id}/subscribers/{id}/campaign_subscriptions` — per-subscriber campaign subscription records including started/completed state (high) — not syncable at Drip's rate limit: one request per subscriber against 3,600 requests/hour. The same campaign↔subscriber join is now covered by `campaign_subscribers`, which fans out over campaigns instead.+- [x] `GET /v2/{account_id}/tags` — account tag lookup; tags drive Drip segmentation and are entirely absent (medium)+- [x] `GET /v2/{account_id}/custom_field_identifiers` — lookup enumerating the custom field keys present on subscriber records (medium)- [ ] `GET /v2/{account_id}/event_actions` — lookup of custom event action names used in the account (medium)- [ ] `GET /v2/{account_id}/workflows/{workflow_id}/triggers` — trigger definitions explaining how subscribers enter each synced workflow (medium)- [ ] `GET /v2/accounts` — account lookup to attribute rows when a token spans multiple Drip accounts (low)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/drip/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/drip/canonical_descriptions.pyindex c57820f2f68a..1e4883e14fdd 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/drip/canonical_descriptions.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/drip/canonical_descriptions.py@@ -42,6 +42,19 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {"created_at": "Time at which the campaign was created.",},},+ "campaign_subscribers": {+ "description": "Membership of an email series campaign: one row per subscriber per campaign, across active, unsubscribed and removed statuses.",+ "docs_url": "https://developer.drip.com/#list-all-subscribers-to-a-campaign",+ "columns": {+ "campaign_id": "Identifier of the campaign the subscriber belongs to.",+ "campaign_subscription_status": "Subscription status the row was listed under: active, unsubscribed or removed.",+ "id": "Unique identifier for the subscriber.",+ "email": "The subscriber's email address.",+ "status": "The subscriber's account-level subscription status.",+ "created_at": "Time at which the subscriber was created.",+ "updated_at": "Time at which the subscriber was last updated.",+ },+ },"broadcasts": {"description": "A one-time email blast sent to a segment of subscribers.","docs_url": "https://developer.drip.com/#broadcasts",@@ -88,4 +101,18 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {"created_at": "Time at which the goal was created.",},},+ "tags": {+ "description": "Every tag used in the account. Tags are the labels Drip segmentation and automation trigger on.",+ "docs_url": "https://developer.drip.com/#list-all-tags-used-in-an-account",+ "columns": {+ "tag": "The tag, as applied to subscribers.",+ },+ },+ "custom_field_identifiers": {+ "description": "Every active custom field key used on subscriber records in the account.",+ "docs_url": "https://developer.drip.com/#list-all-custom-field-identifiers-used-in-an-account",+ "columns": {+ "identifier": "The custom field key, matching a key in a subscriber's custom_fields.",+ },+ },}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/drip/drip.py b/products/warehouse_sources/backend/temporal/data_imports/sources/drip/drip.pyindex abe31c8bbbb0..996df75714b5 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/drip/drip.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/drip/drip.py@@ -1,4 +1,5 @@import dataclasses+from collections.abc import Iteratorfrom typing import Any, Optionalfrom requests import Request, Response@@ -9,13 +10,23 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common.resrest_api_resource,)from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.auth import HttpBasicAuth+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+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.typing import ClientConfigfrom products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManagerfrom products.warehouse_sources.backend.temporal.data_imports.sources.common.source_helpers import validate_via_probefrom products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceResponse-from products.warehouse_sources.backend.temporal.data_imports.sources.drip.settings import DRIP_ENDPOINTS+from products.warehouse_sources.backend.temporal.data_imports.sources.drip.settings import (+ CAMPAIGN_SUBSCRIBER_STATUS_FIELD,+ CAMPAIGN_SUBSCRIBER_STATUSES,+ DRIP_ENDPOINTS,+ DripEndpointConfig,+)DRIP_BASE_URL = "https://api.getdrip.com/v2"+REQUEST_TIMEOUT_SECONDS = 30.0@dataclasses.dataclass@@ -94,6 +105,73 @@ def _base_params(endpoint: str) -> dict[str, Any]:return params+def _client_config(api_token: str, account_id: str, per_page: Optional[int]) -> ClientConfig:+ return {+ "base_url": f"{DRIP_BASE_URL}/{account_id}",+ "headers": {"Accept": "application/json"},+ # Drip uses HTTP Basic auth with the API token as the username and an empty password;+ # supplying it via the framework auth config keeps the token redacted from logs.+ "auth": {"type": "http_basic", "username": api_token, "password": ""},+ "paginator": DripPaginator(per_page=per_page),+ "request_timeout": REQUEST_TIMEOUT_SECONDS,+ }+++def _wrap_scalar_pages(pages: Iterator[Any], column: str) -> Iterator[list[dict[str, Any]]]:+ """Turn pages of bare strings into rows.++ `/tags` and `/custom_field_identifiers` answer with a list of strings rather than objects,+ so each value becomes a single-column row.+ """+ for page in pages:+ yield [{column: value} for value in page]+++def _campaign_subscriber_pages(+ config: DripEndpointConfig,+ api_token: str,+ account_id: str,+ team_id: int,+ job_id: str,+) -> Iterator[list[dict[str, Any]]]:+ """Fan campaign membership out over campaigns, once per subscription status.++ The endpoint filters by a single status and defaults to `active`, so an unswept table would+ silently drop everyone who unsubscribed from or was removed from a campaign. The rows are+ subscriber objects and carry no campaign status of their own, hence the added column.+ """+ assert config.fanout is not None+ parent_config = DRIP_ENDPOINTS[config.fanout.parent_name]++ for status in CAMPAIGN_SUBSCRIBER_STATUSES:+ resource = build_dependent_resource(+ endpoint_configs=DRIP_ENDPOINTS,+ child_endpoint=config.name,+ fanout=dataclasses.replace(+ config.fanout,+ parent_params={"sort": parent_config.sort, "direction": parent_config.direction},+ child_params={"status": status, "direction": config.direction},+ ),+ client_config=_client_config(api_token, account_id, config.per_page),+ path_format_values={},+ team_id=team_id,+ job_id=job_id,+ db_incremental_field_last_value=None,+ page_size_param="per_page",+ # The paginator holds the page number, so parent and child each get their own.+ parent_endpoint_extra={+ "paginator": DripPaginator(per_page=parent_config.per_page),+ "data_selector": parent_config.data_key,+ },+ child_endpoint_extra={+ "paginator": DripPaginator(per_page=config.per_page),+ "data_selector": config.data_key,+ },+ )+ for page in resource:+ yield [{**row, CAMPAIGN_SUBSCRIBER_STATUS_FIELD: status} for row in page]++def drip_source(api_token: str,account_id: str,@@ -105,15 +183,22 @@ def drip_source() -> SourceResponse:config = DRIP_ENDPOINTS[endpoint]+ if config.fanout is not None:+ # Dependent resources have no resume support in the rest_source framework, so the manager+ # is intentionally not threaded into this path.+ return SourceResponse(+ name=endpoint,+ items=lambda: _campaign_subscriber_pages(config, api_token, account_id, team_id, job_id),+ primary_keys=config.primary_keys,+ partition_count=1,+ partition_size=1,+ partition_mode="datetime" if config.partition_key else None,+ partition_format="month" if config.partition_key else None,+ partition_keys=[config.partition_key] if config.partition_key else None,+ )+rest_config: RESTAPIConfig = {- "client": {- "base_url": f"{DRIP_BASE_URL}/{account_id}",- "headers": {"Accept": "application/json"},- # Drip uses HTTP Basic auth with the API token as the username and an empty password;- # supplying it via the framework auth config keeps the token redacted from logs.- "auth": {"type": "http_basic", "username": api_token, "password": ""},- "paginator": DripPaginator(per_page=config.per_page),- },+ "client": _client_config(api_token, account_id, config.per_page),"resources": [{"name": endpoint,@@ -147,9 +232,16 @@ def drip_source(initial_paginator_state=initial_paginator_state,)+ scalar_row_key = config.scalar_row_key+ items = (+ (lambda: _wrap_scalar_pages(iter(resource), scalar_row_key))+ if scalar_row_key is not None+ else (lambda: resource)+ )+return SourceResponse(name=endpoint,- items=lambda: resource,+ items=items,primary_keys=config.primary_keys,partition_count=1,partition_size=1,diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/drip/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/drip/settings.pyindex 5d14fc9b2296..cc11625f1ef7 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/drip/settings.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/drip/settings.py@@ -1,10 +1,20 @@from dataclasses import dataclass, fieldfrom typing import Optional+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.fanout import (+ DependentEndpointConfig,+)from products.warehouse_sources.backend.types import IncrementalField+DEFAULT_PAGE_SIZE = 100-@dataclass+# Campaign membership is only listable one status at a time, so a full membership table sweeps all+# three and tags each row with the status it came back under.+CAMPAIGN_SUBSCRIBER_STATUSES = ("active", "unsubscribed", "removed")+CAMPAIGN_SUBSCRIBER_STATUS_FIELD = "campaign_subscription_status"+++@dataclass(frozen=True)class DripEndpointConfig:name: strpath: str@@ -19,6 +29,21 @@ class DripEndpointConfig:# Stable datetime field to partition on. Never use updated_at (it changes and rewrites partitions).partition_key: Optional[str] = Noneincremental_fields: list[IncrementalField] = field(default_factory=list)+ # Set when the endpoint returns a bare list of strings rather than objects; each value is wrapped+ # into a row under this column name.+ scalar_row_key: Optional[str] = None+ # Set when the endpoint is scoped to one parent resource and has to be fanned out over it.+ fanout: Optional[DependentEndpointConfig] = None++ # Both read by the shared fan-out helper. Every endpoint taking part in a fan-out sets+ # per_page, and no Drip endpoint has a usable cursor field.+ @property+ def page_size(self) -> int:+ return self.per_page if self.per_page is not None else DEFAULT_PAGE_SIZE++ @property+ def default_incremental_field(self) -> Optional[str]:+ return None# Top-level, account-scoped endpoints (all require account_id as a path segment). We ship full refresh@@ -43,6 +68,24 @@ DRIP_ENDPOINTS: dict[str, DripEndpointConfig] = {sort="created_at",direction="asc",),+ # Fanned out over campaigns: the rows are subscriber objects, so the campaign they belong to is+ # copied down from the parent and the primary key pairs the two.+ "campaign_subscribers": DripEndpointConfig(+ name="campaign_subscribers",+ path="/campaigns/{campaign_id}/subscribers",+ data_key="subscribers",+ primary_keys=["campaign_id", "id"],+ per_page=1000, # documented max for this endpoint+ direction="asc",+ partition_key="created_at",+ fanout=DependentEndpointConfig(+ parent_name="campaigns",+ resolve_param="campaign_id",+ resolve_field="id",+ include_from_parent=["id"],+ parent_field_renames={"id": "campaign_id"},+ ),+ ),"broadcasts": DripEndpointConfig(name="broadcasts",path="/broadcasts",@@ -71,6 +114,20 @@ DRIP_ENDPOINTS: dict[str, DripEndpointConfig] = {data_key="goals",primary_keys=["id"],),+ "tags": DripEndpointConfig(+ name="tags",+ path="/tags",+ data_key="tags",+ primary_keys=["tag"],+ scalar_row_key="tag",+ ),+ "custom_field_identifiers": DripEndpointConfig(+ name="custom_field_identifiers",+ path="/custom_field_identifiers",+ data_key="custom_field_identifiers",+ primary_keys=["identifier"],+ scalar_row_key="identifier",+ ),}ENDPOINTS = tuple(DRIP_ENDPOINTS.keys())diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/drip/tests/test_drip.py b/products/warehouse_sources/backend/temporal/data_imports/sources/drip/tests/test_drip.pyindex cc7d2f256a22..83f5863d2b5d 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/drip/tests/test_drip.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/drip/tests/test_drip.py@@ -15,7 +15,11 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.drip.dripdrip_source,validate_credentials,)-from products.warehouse_sources.backend.temporal.data_imports.sources.drip.settings import DRIP_ENDPOINTS, ENDPOINTS+from products.warehouse_sources.backend.temporal.data_imports.sources.drip.settings import (+ CAMPAIGN_SUBSCRIBER_STATUSES,+ DRIP_ENDPOINTS,+ ENDPOINTS,+)# RESTClient builds its session via make_tracked_session in the rest_client module.CLIENT_SESSION_PATCH = "products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.rest_client.make_tracked_session"@@ -278,3 +282,63 @@ class TestDripSourceResponse:)assert response.partition_keys == ["created_at"]assert response.partition_format == "month"+++class TestScalarEndpoints:+ @parameterized.expand(+ [+ ("tags", "tag", ["Customer", "SEO"]),+ ("custom_field_identifiers", "identifier", ["first_name", "last_name"]),+ ]+ )+ @mock.patch(CLIENT_SESSION_PATCH)+ def test_bare_strings_become_single_column_rows(self, endpoint, column, values, MockSession) -> None:+ session = MockSession.return_value+ _wire(session, [_page(DRIP_ENDPOINTS[endpoint].data_key, values)])++ rows = _run(session, endpoint, _make_manager())++ assert rows == [{column: value} for value in values]+++class TestCampaignSubscribersFanout:+ @mock.patch(CLIENT_SESSION_PATCH)+ def test_fans_out_over_campaigns_for_every_status(self, MockSession) -> None:+ session = MockSession.return_value+ # One campaign page, then one subscriber page per campaign for each of the three statuses.+ responses = [_page("campaigns", [{"id": 10}, {"id": 11}])]+ for index, _status in enumerate(CAMPAIGN_SUBSCRIBER_STATUSES):+ if index:+ responses.append(_page("campaigns", [{"id": 10}, {"id": 11}]))+ responses.append(_page("subscribers", [{"id": f"s{index}0"}]))+ responses.append(_page("subscribers", [{"id": f"s{index}1"}]))+ captured = _wire(session, responses)++ rows = _run(session, "campaign_subscribers", _make_manager())++ assert rows == [+ {"id": f"s{index}{offset}", "campaign_id": campaign, "campaign_subscription_status": status}+ for index, status in enumerate(CAMPAIGN_SUBSCRIBER_STATUSES)+ for offset, campaign in enumerate([10, 11])+ ]+ child_requests = [c.params for c in captured if "status" in c.params]+ assert [c["status"] for c in child_requests] == [+ status for status in CAMPAIGN_SUBSCRIBER_STATUSES for _ in range(2)+ ]+ assert all(c["per_page"] == 1000 and c["direction"] == "asc" for c in child_requests)++ @mock.patch(CLIENT_SESSION_PATCH)+ def test_child_pages_are_followed_per_campaign(self, MockSession) -> None:+ session = MockSession.return_value+ responses = []+ for index, _status in enumerate(CAMPAIGN_SUBSCRIBER_STATUSES):+ responses.append(_page("campaigns", [{"id": 10}]))+ responses.append(_page("subscribers", [{"id": f"a{index}"}], total_pages=2))+ responses.append(_page("subscribers", [{"id": f"b{index}"}], total_pages=2))+ captured = _wire(session, responses)++ rows = _run(session, "campaign_subscribers", _make_manager())++ assert [row["id"] for row in rows] == ["a0", "b0", "a1", "b1", "a2", "b2"]+ child_pages = [c.params["page"] for c in captured if "status" in c.params]+ assert child_pages == [1, 2, 1, 2, 1, 2]