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 campayn import source (#66751)

Tom Owers41f855ba95e2
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 fc96df023a9e..f9f3ea9819fc 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
@@ -71,6 +71,7 @@ the row lists both.
| buildkite | HTTP | requests | ✅ |
| calendly | HTTP | requests | ✅ |
| campaign_monitor | HTTP | requests | ✅ |
+| campayn | HTTP | requests | ✅ |
| canny | HTTP | requests | ✅ |
| chargebee | HTTP | requests + `rest_source.RESTClient` | ✅ |
| chargedesk | HTTP | requests | ✅ |
@@ -332,7 +333,6 @@ doesn't conflict with concurrent PRs.
- cal_com
- callrail
- campaign_manager_360
-- campayn
- capsule_crm
- captain_data
- care_quality_commission
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/campayn/campayn.py b/products/warehouse_sources/backend/temporal/data_imports/sources/campayn/campayn.py
new file mode 100644
index 000000000000..19439bb2dbee
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/campayn/campayn.py
@@ -0,0 +1,182 @@
+import re
+from collections.abc import Iterator
+from typing import Any
+
+import requests
+from structlog.types import FilteringBoundLogger
+from tenacity import retry, retry_if_exception_type, stop_after_attempt, wait_exponential_jitter
+
+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import SourceResponse
+from products.warehouse_sources.backend.temporal.data_imports.sources.campayn.settings import (
+ CAMPAYN_ENDPOINTS,
+ CampaynEndpointConfig,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.http import make_tracked_session
+
+CAMPAYN_API_PATH = "/api/v1"
+REQUEST_TIMEOUT_SECONDS = 60
+# Per-account host: requests go to {subdomain}.campayn.com. The label is validated against this
+# pattern at source-create so a pasted URL or injection can't retarget the credential elsewhere.
+_SUBDOMAIN_PATTERN = re.compile(r"^[a-zA-Z0-9-]+$")
+
+
+class CampaynRetryableError(Exception):
+ pass
+
+
+def normalize_subdomain(subdomain: str) -> str:
+ """Reduce whatever the user entered to the bare Campayn subdomain label.
+
+ Users frequently paste the full host ("acme.campayn.com") or a URL
+ ("https://acme.campayn.com/") into the subdomain field. Collapse those to the
+ bare label so the base URL doesn't become "https://acme.campayn.com.campayn.com/".
+ """
+ subdomain = subdomain.strip()
+ if "://" in subdomain:
+ subdomain = subdomain.split("://", 1)[1]
+ # Drop any path/query left over from a pasted URL.
+ subdomain = subdomain.split("/", 1)[0]
+ # Strip a trailing ".campayn.com" so a full host collapses to the subdomain label.
+ return re.sub(r"\.campayn\.com$", "", subdomain, flags=re.IGNORECASE)
+
+
+def is_subdomain_valid(subdomain: str) -> bool:
+ return bool(_SUBDOMAIN_PATTERN.match(normalize_subdomain(subdomain)))
+
+
+def base_url(subdomain: str) -> str:
+ return f"https://{normalize_subdomain(subdomain)}.campayn.com{CAMPAYN_API_PATH}"
+
+
+def _headers(api_key: str) -> dict[str, str]:
+ # Campayn's custom auth scheme: "Authorization: TRUEREST apikey={key}".
+ return {"Authorization": f"TRUEREST apikey={api_key}", "Accept": "application/json"}
+
+
+@retry(
+ retry=retry_if_exception_type((CampaynRetryableError, requests.ReadTimeout, requests.ConnectionError)),
+ stop=stop_after_attempt(5),
+ wait=wait_exponential_jitter(initial=1, max=30),
+ reraise=True,
+)
+def _fetch(session: requests.Session, url: str, headers: dict[str, str], logger: FilteringBoundLogger) -> Any:
+ response = session.get(url, headers=headers, timeout=REQUEST_TIMEOUT_SECONDS)
+
+ if response.status_code == 429 or response.status_code >= 500:
+ raise CampaynRetryableError(f"Campayn API error (retryable): status={response.status_code}, url={url}")
+
+ if not response.ok:
+ logger.error(f"Campayn API error: status={response.status_code}, body={response.text}, url={url}")
+ response.raise_for_status()
+
+ return response.json()
+
+
+def _as_rows(payload: Any) -> list[dict[str, Any]]:
+ """Coerce a Campayn list response into a list of row dicts.
+
+ Every documented list endpoint returns a bare JSON array. We couldn't curl-verify the live API
+ (it needs a per-account subdomain + key), so we also tolerate a single object or a ``{data: [...]}``
+ wrapper defensively rather than crashing the sync if the shape differs from the docs.
+ """
+ if isinstance(payload, list):
+ return [item for item in payload if isinstance(item, dict)]
+ if isinstance(payload, dict):
+ data = payload.get("data")
+ if isinstance(data, list):
+ return [item for item in data if isinstance(item, dict)]
+ return [payload]
+ return []
+
+
+def _iter_list_ids(
+ session: requests.Session, subdomain: str, headers: dict[str, str], logger: FilteringBoundLogger
+) -> Iterator[str]:
+ payload = _fetch(session, f"{base_url(subdomain)}/lists.json", headers, logger)
+ for item in _as_rows(payload):
+ # `id` drives all fan-out, so fail fast on a malformed list record rather than silently
+ # dropping its contacts/forms.
+ yield str(item["id"])
+
+
+def get_rows(
+ subdomain: str,
+ api_key: str,
+ endpoint: str,
+ logger: FilteringBoundLogger,
+) -> Iterator[list[dict[str, Any]]]:
+ config = CAMPAYN_ENDPOINTS[endpoint]
+ headers = _headers(api_key)
+ # One session reused across every request (and, for fan-out, every list) so urllib3 keeps the
+ # connection alive instead of re-handshaking per request. `redact_values` masks the API key
+ # everywhere the tracked adapter records request headers/URLs/samples — the custom
+ # `TRUEREST apikey=...` header isn't recognised by the name-based scrubbers.
+ session = make_tracked_session(redact_values=(api_key,))
+
+ if config.fan_out_over_lists:
+ yield from _get_fan_out_rows(session, subdomain, headers, logger, config)
+ return
+
+ payload = _fetch(session, f"{base_url(subdomain)}{config.path}", headers, logger)
+ rows = _as_rows(payload)
+ if rows:
+ yield rows
+
+
+def _get_fan_out_rows(
+ session: requests.Session,
+ subdomain: str,
+ headers: dict[str, str],
+ logger: FilteringBoundLogger,
+ config: CampaynEndpointConfig,
+) -> Iterator[list[dict[str, Any]]]:
+ """Fetch a child resource (contacts/forms) per list, stamping each row with its parent ``list_id``.
+
+ Full refresh only — these endpoints expose no incremental filter. The parent ``list_id`` is part of
+ the composite primary key, so the same contact appearing under multiple lists stays a distinct row.
+ """
+ for list_id in _iter_list_ids(session, subdomain, headers, logger):
+ url = f"{base_url(subdomain)}{config.path.format(list_id=list_id)}"
+ try:
+ payload = _fetch(session, url, headers, logger)
+ except requests.HTTPError as exc:
+ # A list deleted between enumeration and this fetch 404s. Skip it rather than failing the
+ # whole sync; any other HTTP error is re-raised.
+ if exc.response is not None and exc.response.status_code == 404:
+ logger.warning(f"Campayn: list {list_id} not found while fetching {config.name}, skipping")
+ continue
+ raise
+
+ rows = [{**row, "list_id": list_id} for row in _as_rows(payload)]
+ if rows:
+ yield rows
+
+
+def campayn_source(
+ subdomain: str,
+ api_key: str,
+ endpoint: str,
+ logger: FilteringBoundLogger,
+) -> SourceResponse:
+ config = CAMPAYN_ENDPOINTS[endpoint]
+
+ return SourceResponse(
+ name=endpoint,
+ items=lambda: get_rows(subdomain=subdomain, api_key=api_key, endpoint=endpoint, logger=logger),
+ primary_keys=config.primary_keys,
+ # No stable creation-time field is exposed on any Campayn resource, so partitioning is disabled.
+ partition_mode=None,
+ )
+
+
+def validate_credentials(subdomain: str, api_key: str) -> bool:
+ # /lists.json is the cheapest read and the entry point every fan-out depends on.
+ try:
+ # `redact_values` masks the API key in tracked telemetry — the credential check runs before
+ # the source is saved, so the raw key must not leak into HTTP logs/samples here either.
+ response = make_tracked_session(redact_values=(api_key,)).get(
+ f"{base_url(subdomain)}/lists.json", headers=_headers(api_key), timeout=15
+ )
+ return response.status_code == 200
+ except Exception:
+ return False
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/campayn/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/campayn/canonical_descriptions.py
new file mode 100644
index 000000000000..24379edb7fc4
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/campayn/canonical_descriptions.py
@@ -0,0 +1,82 @@
+"""Canonical, documentation-sourced descriptions for Campayn endpoints and columns.
+
+Sourced from the official Campayn API reference (https://github.com/nebojsac/Campayn-API). Keyed by the
+table names in `settings.py` `CAMPAYN_ENDPOINTS`, which match the `ExternalDataSchema.name` of a synced
+Campayn table. Columns absent here fall back to LLM enrichment. The official docs are explicitly
+preliminary (several TODO sections), so coverage is intentionally conservative.
+"""
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (
+ CanonicalDescriptions,
+)
+
+_DOCS_BASE = "https://github.com/nebojsac/Campayn-API/blob/master/endpoints"
+
+CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
+ "lists": {
+ "description": "A contact list visible to the authenticated account.",
+ "docs_url": f"{_DOCS_BASE}/lists.md",
+ "columns": {
+ "id": "Unique identifier for the list.",
+ "list_name": "Display name of the list.",
+ "tags": "Comma-separated tags applied to the list.",
+ "contact_count": "Number of contacts currently in the list.",
+ },
+ },
+ "contacts": {
+ "description": "A contact belonging to a list. Fetched per list, so each row carries the parent list_id; the same contact can appear under multiple lists.",
+ "docs_url": f"{_DOCS_BASE}/contacts.md",
+ "columns": {
+ "id": "Unique identifier for the contact.",
+ "list_id": "Identifier of the list this contact row was fetched from (injected by PostHog).",
+ "email": "The contact's email address.",
+ "first_name": "The contact's first name.",
+ "last_name": "The contact's last name.",
+ "image_url": "URL of the contact's profile image.",
+ },
+ },
+ "forms": {
+ "description": "A signup form associated with a list (signup page, embed, WordPress, or Facebook form).",
+ "docs_url": f"{_DOCS_BASE}/forms.md",
+ "columns": {
+ "id": "Unique identifier for the form.",
+ "list_id": "Identifier of the list this form row was fetched from (injected by PostHog).",
+ "contact_list_id": "Identifier of the list the form is associated with.",
+ "form_title": "Display title of the form.",
+ "form_type": "Form type code: 0 signup page, 1 embed signup, 2 WordPress signup, 3 Facebook signup.",
+ "form_html": "Rendered HTML of the form, when available.",
+ "signup_count": "Number of signups collected through the form.",
+ },
+ },
+ "emails": {
+ "description": "An email (campaign) visible to the account, with basic delivery and engagement stats.",
+ "docs_url": f"{_DOCS_BASE}/emails.md",
+ "columns": {
+ "id": "Unique identifier for the email.",
+ "name": "Internal name of the email.",
+ "scheduled_date": "When the email is scheduled to send, if scheduled.",
+ "send_now": "Whether the email is set to send immediately.",
+ "send_count": "Number of recipients the email was sent to.",
+ "campaign_title": "Title of the campaign the email belongs to, if any.",
+ "status": "Delivery status of the email (e.g. delivered, incomplete).",
+ "unique_views": "Count of unique recipients who opened the email.",
+ "unique_responses": "Count of unique recipients who clicked through.",
+ "percent_views": "Percentage of recipients who opened the email.",
+ "percent_responses": "Percentage of recipients who clicked through.",
+ "preview_url": "URL to a hosted preview of the email.",
+ "preview_thumb": "URL to a thumbnail image of the email.",
+ },
+ },
+ "reports": {
+ "description": "Calendar of sent and scheduled emails with their report URLs. Scheduled emails have no report URL.",
+ "docs_url": f"{_DOCS_BASE}/reports.md",
+ "columns": {
+ "id": "Identifier of the email the report refers to.",
+ "name": "Name of the email.",
+ "scheduled_date": "When the email was sent or is scheduled to send (UTC).",
+ "status": "Status of the email (e.g. sent).",
+ "preview_url": "URL to a hosted preview of the email.",
+ "report_url": "URL to the email's report; null for scheduled (not yet sent) emails.",
+ },
+ },
+}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/campayn/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/campayn/settings.py
new file mode 100644
index 000000000000..d8829ef7365f
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/campayn/settings.py
@@ -0,0 +1,41 @@
+from dataclasses import dataclass, field
+
+
+@dataclass
+class CampaynEndpointConfig:
+ name: str
+ """Table name we expose to the user (snake_case)."""
+ path: str
+ """Path relative to ``/api/v1`` (e.g. ``/lists.json``). Fan-out paths carry a ``{list_id}``
+ placeholder filled in per parent list."""
+ primary_keys: list[str] = field(default_factory=lambda: ["id"])
+ # Fan out over every list returned by ``/lists.json``, fetching the child resource per list.
+ # When True, ``path`` is a template with a ``{list_id}`` placeholder and each emitted row carries
+ # the parent ``list_id`` (so the composite primary key stays unique table-wide).
+ fan_out_over_lists: bool = False
+
+
+# Campayn's public API exposes no pagination, no cursors, and no server-side timestamp filters on any
+# list endpoint, so every table is full refresh only — matching the Airbyte connector's capabilities.
+# Contacts and forms are nested under a list, so they fan out: enumerate ``/lists.json`` first, then
+# fetch the child resource per list. A contact can belong to multiple lists (and the contacts endpoint
+# returns the same contact id under each), so the contacts primary key includes the parent ``list_id``.
+CAMPAYN_ENDPOINTS: dict[str, CampaynEndpointConfig] = {
+ "lists": CampaynEndpointConfig(name="lists", path="/lists.json", primary_keys=["id"]),
+ "emails": CampaynEndpointConfig(name="emails", path="/emails.json", primary_keys=["id"]),
+ "reports": CampaynEndpointConfig(name="reports", path="/reports/calendar.json", primary_keys=["id"]),
+ "contacts": CampaynEndpointConfig(
+ name="contacts",
+ path="/lists/{list_id}/contacts.json",
+ primary_keys=["list_id", "id"],
+ fan_out_over_lists=True,
+ ),
+ "forms": CampaynEndpointConfig(
+ name="forms",
+ path="/lists/{list_id}/forms.json",
+ primary_keys=["list_id", "id"],
+ fan_out_over_lists=True,
+ ),
+}
+
+ENDPOINTS = tuple(CAMPAYN_ENDPOINTS.keys())
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/campayn/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/campayn/source.py
index 6627e09754b4..ca26db05815e 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/campayn/source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/campayn/source.py
@@ -1,30 +1,135 @@
-from typing import cast
+from typing import Optional, cast
from posthog.schema import (
DataWarehouseSourceCategory,
ExternalDataSourceType as SchemaExternalDataSourceType,
+ ReleaseStatus,
SourceConfig,
+ SourceFieldInputConfig,
+ SourceFieldInputConfigType,
)
+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import (
+ SourceInputs,
+ SourceResponse,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.campayn.campayn import (
+ campayn_source,
+ is_subdomain_valid,
+ validate_credentials as validate_campayn_credentials,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.campayn.settings import ENDPOINTS
from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, SimpleSource
+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.schema import SourceSchema
from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs import CampaynSourceConfig
from products.warehouse_sources.backend.types import ExternalDataSourceType
@SourceRegistry.register
class CampaynSource(SimpleSource[CampaynSourceConfig]):
+ lists_tables_without_credentials = True # static endpoint catalog — safe for public docs
+
@property
def source_type(self) -> ExternalDataSourceType:
return ExternalDataSourceType.CAMPAYN
+ @property
+ def connection_host_fields(self) -> list[str]:
+ # The API key is sent to {subdomain}.campayn.com, so retargeting the subdomain must re-require
+ # the key — otherwise an org member could point it at a host they control and exfiltrate it.
+ return ["subdomain"]
+
@property
def get_source_config(self) -> SourceConfig:
return SourceConfig(
name=SchemaExternalDataSourceType.CAMPAYN,
category=DataWarehouseSourceCategory.MARKETING___EMAIL,
label="Campayn",
+ releaseStatus=ReleaseStatus.ALPHA,
+ caption="""Enter your Campayn subdomain and API key to pull your Campayn email-marketing data into the PostHog Data warehouse.
+
+Your subdomain is the first part of your account host — for `acme.campayn.com`, enter `acme`. You can find and regenerate your API key in your Campayn account settings.""",
iconPath="/static/services/campayn.png",
- fields=cast(list[FieldType], []),
- unreleasedSource=True,
+ docsUrl="https://posthog.com/docs/cdp/sources/campayn",
+ fields=cast(
+ list[FieldType],
+ [
+ SourceFieldInputConfig(
+ name="subdomain",
+ label="Subdomain",
+ type=SourceFieldInputConfigType.TEXT,
+ required=True,
+ placeholder="acme",
+ secret=False,
+ ),
+ SourceFieldInputConfig(
+ name="api_key",
+ label="API key",
+ type=SourceFieldInputConfigType.PASSWORD,
+ required=True,
+ placeholder="",
+ secret=True,
+ ),
+ ],
+ ),
+ )
+
+ def get_canonical_descriptions(self) -> CanonicalDescriptions:
+ from products.warehouse_sources.backend.temporal.data_imports.sources.campayn.canonical_descriptions import (
+ CANONICAL_DESCRIPTIONS,
+ )
+
+ return CANONICAL_DESCRIPTIONS
+
+ def get_non_retryable_errors(self) -> dict[str, str | None]:
+ return {
+ "401 Client Error": "Your Campayn API key is invalid or has been regenerated. Create a new key in your Campayn account settings, then reconnect.",
+ "403 Client Error": "Your Campayn API key is not authorized for this data. Check the key's permissions, then reconnect.",
+ }
+
+ def get_schemas(
+ self,
+ config: CampaynSourceConfig,
+ team_id: int,
+ with_counts: bool = False,
+ names: list[str] | None = None,
+ force_refresh: bool = False,
+ ) -> list[SourceSchema]:
+ # Campayn's API exposes no pagination, cursors, or timestamp filters, so every table is full
+ # refresh only.
+ schemas = [
+ SourceSchema(
+ name=endpoint,
+ supports_incremental=False,
+ supports_append=False,
+ incremental_fields=[],
+ )
+ for endpoint in ENDPOINTS
+ ]
+ if names is not None:
+ names_set = set(names)
+ schemas = [s for s in schemas if s.name in names_set]
+ return schemas
+
+ def validate_credentials(
+ self, config: CampaynSourceConfig, team_id: int, schema_name: Optional[str] = None
+ ) -> tuple[bool, str | None]:
+ if not is_subdomain_valid(config.subdomain):
+ return False, "Campayn subdomain is incorrect"
+
+ if validate_campayn_credentials(config.subdomain, config.api_key):
+ return True, None
+
+ return False, "Campayn rejected the credentials. Check the subdomain and API key are correct."
+
+ def source_for_pipeline(self, config: CampaynSourceConfig, inputs: SourceInputs) -> SourceResponse:
+ return campayn_source(
+ subdomain=config.subdomain,
+ api_key=config.api_key,
+ endpoint=inputs.schema_name,
+ logger=inputs.logger,
)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/campayn/tests/test_campayn.py b/products/warehouse_sources/backend/temporal/data_imports/sources/campayn/tests/test_campayn.py
new file mode 100644
index 000000000000..c8d18e280bdf
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/campayn/tests/test_campayn.py
@@ -0,0 +1,230 @@
+from typing import Any
+
+import pytest
+from unittest import mock
+
+import requests
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.campayn.campayn import (
+ CampaynRetryableError,
+ _as_rows,
+ _fetch,
+ base_url,
+ campayn_source,
+ get_rows,
+ is_subdomain_valid,
+ normalize_subdomain,
+ validate_credentials,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.campayn.settings import (
+ CAMPAYN_ENDPOINTS,
+ ENDPOINTS,
+)
+
+SESSION_PATH = "products.warehouse_sources.backend.temporal.data_imports.sources.campayn.campayn.make_tracked_session"
+
+
+class FakeResponse:
+ def __init__(self, status_code: int = 200, json_data: Any = None) -> None:
+ self.status_code = status_code
+ self._json = json_data if json_data is not None else []
+ self.text = str(self._json)
+
+ @property
+ def ok(self) -> bool:
+ return 200 <= self.status_code < 300
+
+ def json(self) -> Any:
+ return self._json
+
+ def raise_for_status(self) -> None:
+ if not self.ok:
+ raise requests.HTTPError(
+ f"{self.status_code} Client Error", response=mock.MagicMock(status_code=self.status_code)
+ )
+
+
+class FakeSession:
+ def __init__(self, responses_by_url: dict[str, FakeResponse]) -> None:
+ self._responses_by_url = responses_by_url
+ self.calls: list[dict[str, Any]] = []
+
+ def get(self, url: str, headers: Any = None, timeout: Any = None) -> FakeResponse:
+ self.calls.append({"url": url, "headers": headers})
+ # Match by suffix so tests don't have to spell out the full subdomain host every time.
+ for suffix, response in self._responses_by_url.items():
+ if url.endswith(suffix):
+ return response
+ raise AssertionError(f"unexpected URL: {url}")
+
+
+class TestNormalizeSubdomain:
+ @pytest.mark.parametrize(
+ "raw, expected",
+ [
+ ("acme", "acme"),
+ (" acme ", "acme"),
+ ("acme.campayn.com", "acme"),
+ ("https://acme.campayn.com/", "acme"),
+ ("http://acme.campayn.com/api/v1/lists.json", "acme"),
+ ("ACME.CAMPAYN.COM", "ACME"),
+ ],
+ )
+ def test_normalize(self, raw: str, expected: str) -> None:
+ assert normalize_subdomain(raw) == expected
+
+
+class TestIsSubdomainValid:
+ @pytest.mark.parametrize(
+ "raw, expected",
+ [
+ ("acme", True),
+ ("acme-corp", True),
+ ("acme.campayn.com", True),
+ ("https://acme.campayn.com", True),
+ # Pasted paths/URLs collapse to the bare label, so these end up safe.
+ ("acme/../evil", True),
+ ("[email protected]", False),
+ ("acme.evil.com", False),
+ ("acme corp", False),
+ ("", False),
+ ],
+ )
+ def test_validity(self, raw: str, expected: bool) -> None:
+ assert is_subdomain_valid(raw) is expected
+
+
+class TestAsRows:
+ @pytest.mark.parametrize(
+ "payload, expected",
+ [
+ ([{"id": "1"}, {"id": "2"}], [{"id": "1"}, {"id": "2"}]),
+ ([{"id": "1"}, "junk"], [{"id": "1"}]),
+ ({"data": [{"id": "1"}]}, [{"id": "1"}]),
+ ({"id": "1"}, [{"id": "1"}]),
+ ("nope", []),
+ ([], []),
+ ],
+ )
+ def test_coercion(self, payload: Any, expected: list[dict[str, Any]]) -> None:
+ assert _as_rows(payload) == expected
+
+
+class TestGetRowsTopLevel:
+ def test_lists_yields_single_batch(self) -> None:
+ session = FakeSession({"/lists.json": FakeResponse(json_data=[{"id": "1"}, {"id": "2"}])})
+ with mock.patch(SESSION_PATH, return_value=session):
+ batches = list(get_rows("acme", "k", "lists", mock.MagicMock()))
+ assert batches == [[{"id": "1"}, {"id": "2"}]]
+ assert session.calls[0]["url"] == f"{base_url('acme')}/lists.json"
+ assert session.calls[0]["headers"]["Authorization"] == "TRUEREST apikey=k"
+
+ def test_empty_response_yields_nothing(self) -> None:
+ session = FakeSession({"/emails.json": FakeResponse(json_data=[])})
+ with mock.patch(SESSION_PATH, return_value=session):
+ batches = list(get_rows("acme", "k", "emails", mock.MagicMock()))
+ assert batches == []
+
+
+class TestGetRowsFanOut:
+ def test_contacts_fan_out_injects_list_id(self) -> None:
+ session = FakeSession(
+ {
+ "/lists.json": FakeResponse(json_data=[{"id": "10"}, {"id": "20"}]),
+ "/lists/10/contacts.json": FakeResponse(json_data=[{"id": "1", "email": "[email protected]"}]),
+ "/lists/20/contacts.json": FakeResponse(json_data=[{"id": "2", "email": "[email protected]"}]),
+ }
+ )
+ with mock.patch(SESSION_PATH, return_value=session):
+ batches = list(get_rows("acme", "k", "contacts", mock.MagicMock()))
+
+ assert batches == [
+ [{"id": "1", "email": "[email protected]", "list_id": "10"}],
+ [{"id": "2", "email": "[email protected]", "list_id": "20"}],
+ ]
+
+ def test_fan_out_skips_list_deleted_mid_sync(self) -> None:
+ session = FakeSession(
+ {
+ "/lists.json": FakeResponse(json_data=[{"id": "10"}, {"id": "20"}]),
+ "/lists/10/contacts.json": FakeResponse(status_code=404),
+ "/lists/20/contacts.json": FakeResponse(json_data=[{"id": "2"}]),
+ }
+ )
+ logger = mock.MagicMock()
+ with mock.patch(SESSION_PATH, return_value=session):
+ batches = list(get_rows("acme", "k", "contacts", logger))
+
+ assert batches == [[{"id": "2", "list_id": "20"}]]
+ logger.warning.assert_called_once()
+
+ def test_fan_out_reraises_non_404_http_error(self) -> None:
+ session = FakeSession(
+ {
+ "/lists.json": FakeResponse(json_data=[{"id": "10"}]),
+ "/lists/10/forms.json": FakeResponse(status_code=403),
+ }
+ )
+ with mock.patch(SESSION_PATH, return_value=session):
+ with pytest.raises(requests.HTTPError):
+ list(get_rows("acme", "k", "forms", mock.MagicMock()))
+
+
+class TestFetchRetry:
+ @pytest.mark.parametrize("status", [429, 500, 503])
+ def test_retryable_statuses_raise_retryable_error(self, status: int) -> None:
+ # Override tenacity's backoff sleep so the 5 retries don't actually wait; the decorator
+ # reraises the last CampaynRetryableError once attempts are exhausted.
+ session = FakeSession({"/lists.json": FakeResponse(status_code=status)})
+ with mock.patch(SESSION_PATH, return_value=session), mock.patch.object(_fetch.retry, "sleep"): # type: ignore[attr-defined]
+ with pytest.raises(CampaynRetryableError):
+ list(get_rows("acme", "k", "lists", mock.MagicMock()))
+
+ @pytest.mark.parametrize("status", [401, 403, 404])
+ def test_client_errors_raise_http_error(self, status: int) -> None:
+ session = FakeSession({"/lists.json": FakeResponse(status_code=status)})
+ with mock.patch(SESSION_PATH, return_value=session):
+ with pytest.raises(requests.HTTPError):
+ list(get_rows("acme", "k", "lists", mock.MagicMock()))
+
+
+class TestCampaynSource:
+ def test_all_endpoints_buildable_with_correct_primary_keys(self) -> None:
+ for endpoint in ENDPOINTS:
+ response = campayn_source("acme", "k", endpoint, mock.MagicMock())
+ assert response.name == endpoint
+ assert response.primary_keys == CAMPAYN_ENDPOINTS[endpoint].primary_keys
+ # No stable creation-time field exists, so nothing is partitioned.
+ assert response.partition_mode is None
+
+ def test_fan_out_endpoints_key_includes_parent_list_id(self) -> None:
+ assert campayn_source("acme", "k", "contacts", mock.MagicMock()).primary_keys == ["list_id", "id"]
+ assert campayn_source("acme", "k", "forms", mock.MagicMock()).primary_keys == ["list_id", "id"]
+
+
+class TestValidateCredentials:
+ @pytest.mark.parametrize(
+ "status, expected",
+ [(200, True), (401, False), (403, False), (500, False)],
+ )
+ def test_status_mapping(self, status: int, expected: bool) -> None:
+ session = mock.MagicMock()
+ session.get.return_value = FakeResponse(status_code=status)
+ with mock.patch(SESSION_PATH, return_value=session):
+ assert validate_credentials("acme", "k") is expected
+
+ def test_connection_error_returns_false(self) -> None:
+ session = mock.MagicMock()
+ session.get.side_effect = Exception("boom")
+ with mock.patch(SESSION_PATH, return_value=session):
+ assert validate_credentials("acme", "k") is False
+
+ def test_probes_lists_endpoint(self) -> None:
+ session = mock.MagicMock()
+ session.get.return_value = FakeResponse(status_code=200)
+ with mock.patch(SESSION_PATH, return_value=session):
+ validate_credentials("acme", "k")
+ called_url = (
+ session.get.call_args.args[0] if session.get.call_args.args else session.get.call_args.kwargs["url"]
+ )
+ assert called_url == f"{base_url('acme')}/lists.json"
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/campayn/tests/test_campayn_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/campayn/tests/test_campayn_source.py
new file mode 100644
index 000000000000..a4991497c9de
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/campayn/tests/test_campayn_source.py
@@ -0,0 +1,141 @@
+import pytest
+from unittest import mock
+
+from posthog.schema import ReleaseStatus, SourceFieldInputConfig, SourceFieldInputConfigType
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.campayn.settings import ENDPOINTS
+from products.warehouse_sources.backend.temporal.data_imports.sources.campayn.source import CampaynSource
+from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs import CampaynSourceConfig
+from products.warehouse_sources.backend.types import ExternalDataSourceType
+
+
+class TestCampaynSource:
+ def setup_method(self) -> None:
+ self.source = CampaynSource()
+ self.team_id = 123
+ self.config = CampaynSourceConfig(subdomain="acme", api_key="campayn-key")
+
+ def test_source_type(self) -> None:
+ assert self.source.source_type == ExternalDataSourceType.CAMPAYN
+
+ def test_get_source_config(self) -> None:
+ config = self.source.get_source_config
+ assert config.name.value == "Campayn"
+ assert config.label == "Campayn"
+ assert config.releaseStatus == ReleaseStatus.ALPHA
+ # A finished source is visible to users — the scaffold's unreleasedSource flag must be gone.
+ assert not config.unreleasedSource
+ assert config.iconPath == "/static/services/campayn.png"
+ assert config.docsUrl == "https://posthog.com/docs/cdp/sources/campayn"
+
+ field_names = [f.name for f in config.fields if isinstance(f, SourceFieldInputConfig)]
+ assert field_names == ["subdomain", "api_key"]
+
+ def test_api_key_field_is_secret_password(self) -> None:
+ config = self.source.get_source_config
+ field = next(f for f in config.fields if isinstance(f, SourceFieldInputConfig) and f.name == "api_key")
+ assert field.type == SourceFieldInputConfigType.PASSWORD
+ assert field.secret is True
+ assert field.required is True
+
+ def test_subdomain_field_is_plain_text(self) -> None:
+ config = self.source.get_source_config
+ field = next(f for f in config.fields if isinstance(f, SourceFieldInputConfig) and f.name == "subdomain")
+ assert field.type == SourceFieldInputConfigType.TEXT
+ assert field.secret is False
+ assert field.required is True
+
+ def test_subdomain_is_a_connection_host_field(self) -> None:
+ # Changing the subdomain retargets where the API key is sent, so it must re-require the secret.
+ assert self.source.connection_host_fields == ["subdomain"]
+
+ def test_lists_tables_without_credentials(self) -> None:
+ assert self.source.lists_tables_without_credentials is True
+
+ def test_get_schemas_covers_all_endpoints_as_full_refresh(self) -> None:
+ schemas = self.source.get_schemas(self.config, self.team_id)
+ assert {s.name for s in schemas} == set(ENDPOINTS)
+ assert all(s.supports_incremental is False for s in schemas)
+ assert all(s.supports_append is False for s in schemas)
+ assert all(s.incremental_fields == [] for s in schemas)
+
+ def test_get_schemas_filtered_by_names(self) -> None:
+ schemas = self.source.get_schemas(self.config, self.team_id, names=["contacts"])
+ assert len(schemas) == 1
+ assert schemas[0].name == "contacts"
+
+ def test_get_schemas_filtered_unknown_name_returns_empty(self) -> None:
+ assert self.source.get_schemas(self.config, self.team_id, names=["nope"]) == []
+
+ def test_documented_tables_render_for_public_docs(self) -> None:
+ # lists_tables_without_credentials=True + static get_schemas means the doc's Supported tables
+ # section is populated without a live connection.
+ tables = self.source.get_documented_tables()
+ assert {t["name"] for t in tables} == set(ENDPOINTS)
+ assert all("Full refresh" in t["sync_methods"] for t in tables)
+
+ @pytest.mark.parametrize(
+ "observed_error",
+ [
+ "401 Client Error: Unauthorized for url: https://acme.campayn.com/api/v1/lists.json",
+ "403 Client Error: Forbidden for url: https://acme.campayn.com/api/v1/emails.json",
+ ],
+ )
+ def test_non_retryable_errors_match_auth_failures(self, observed_error: str) -> None:
+ non_retryable = self.source.get_non_retryable_errors()
+ assert any(key in observed_error for key in non_retryable)
+
+ @pytest.mark.parametrize(
+ "unrelated_error",
+ ["429 Client Error: Too Many Requests", "500 Server Error", "Connection reset by peer"],
+ )
+ def test_non_retryable_errors_ignore_transient(self, unrelated_error: str) -> None:
+ non_retryable = self.source.get_non_retryable_errors()
+ assert not any(key in unrelated_error for key in non_retryable)
+
+ @pytest.mark.parametrize(
+ "subdomain, valid_creds, expected_valid, expected_message",
+ [
+ ("acme", True, True, None),
+ ("acme", False, False, "Campayn rejected the credentials. Check the subdomain and API key are correct."),
+ ("acme corp", True, False, "Campayn subdomain is incorrect"),
+ ("[email protected]", True, False, "Campayn subdomain is incorrect"),
+ ],
+ )
+ @mock.patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.campayn.source.validate_campayn_credentials"
+ )
+ def test_validate_credentials(
+ self,
+ mock_validate: mock.MagicMock,
+ subdomain: str,
+ valid_creds: bool,
+ expected_valid: bool,
+ expected_message: str | None,
+ ) -> None:
+ mock_validate.return_value = valid_creds
+ config = CampaynSourceConfig(subdomain=subdomain, api_key="k")
+ is_valid, message = self.source.validate_credentials(config, self.team_id)
+ assert is_valid is expected_valid
+ assert message == expected_message
+
+ @mock.patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.campayn.source.validate_campayn_credentials"
+ )
+ def test_validate_credentials_skips_api_call_for_bad_subdomain(self, mock_validate: mock.MagicMock) -> None:
+ config = CampaynSourceConfig(subdomain="acme corp", api_key="k")
+ self.source.validate_credentials(config, self.team_id)
+ mock_validate.assert_not_called()
+
+ @mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.campayn.source.campayn_source")
+ def test_source_for_pipeline_plumbs_arguments(self, mock_campayn_source: mock.MagicMock) -> None:
+ inputs = mock.MagicMock()
+ inputs.schema_name = "contacts"
+
+ self.source.source_for_pipeline(self.config, inputs)
+
+ mock_campayn_source.assert_called_once()
+ kwargs = mock_campayn_source.call_args.kwargs
+ assert kwargs["subdomain"] == "acme"
+ assert kwargs["api_key"] == "campayn-key"
+ assert kwargs["endpoint"] == "contacts"
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.py b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.py
index 1409219a51af..c6b2ee7676ca 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.py
@@ -551,7 +551,8 @@ class CampaignMonitorSourceConfig(config.Config):
@config.config
class CampaynSourceConfig(config.Config):
- pass
+ subdomain: str
+ api_key: str
@config.config