: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): implement bigmailer import source (#66756)
Tom Owersd369368a0905
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.mdindex 48faa06865fc..66f636b44dd3 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md@@ -59,6 +59,7 @@ the row lists both.| azure_devops | HTTP | requests | ✅ || bamboohr | HTTP | requests | ✅ || beamer | HTTP | requests | ✅ |+| bigmailer | HTTP | requests | ✅ || bigquery | HTTP + gRPC | google-cloud-bigquery + bigquery-storage | ✅ (HTTP + gRPC) || bing_ads | HTTP (vendor SDK, SOAP) | bingads SDK | ⚠️ || braintree | HTTP (GraphQL) | requests | ✅ |@@ -307,7 +308,6 @@ doesn't conflict with concurrent PRs.- babelforce- basecamp- bigcommerce-- bigmailer- bitly- blogger- bluetallydiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/bigmailer/bigmailer.py b/products/warehouse_sources/backend/temporal/data_imports/sources/bigmailer/bigmailer.pynew file mode 100644index 000000000000..3a6807f4536b--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/bigmailer/bigmailer.py@@ -0,0 +1,208 @@+import dataclasses+from collections.abc import Iterator+from typing import Any+from urllib.parse import urlencode++import requests+from structlog.types import FilteringBoundLogger++from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import SourceResponse+from products.warehouse_sources.backend.temporal.data_imports.sources.bigmailer.settings import (+ BIGMAILER_ENDPOINTS,+ BigMailerEndpointConfig,+)+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.resumable import ResumableSourceManager++BIGMAILER_BASE_URL = "https://api.bigmailer.io/v1"+# The API caps list responses at 100 objects per page; request the max to minimise round trips+# against the 10 req/s account rate limit.+PAGE_SIZE = 100+REQUEST_TIMEOUT_SECONDS = 60++# Stable substring matched by BigMailerSource.get_non_retryable_errors to permanently fail the sync+# on a credential problem instead of retrying. Kept identical to the raised exception text.+AUTH_ERROR_MESSAGE = "BigMailer API key is invalid or lacks the required permissions"+++class BigMailerAuthError(Exception):+ """Raised when the API rejects the key (HTTP 400 'Invalid api key', 401, or 403).++ An invalid or insufficiently-permissioned key can never be fixed by retrying, so this is+ surfaced as a non-retryable error rather than looping the sync.+ """+++class BigMailerResumeConfig:+ # Cursor for the next page to fetch. None starts a list at its first page.+ cursor: str | None = None+ # The brand currently being processed. A stable brand-ID bookmark (not a positional index) so a+ # brand added or removed between a crash and the retry can't resume us into the wrong brand. None+ # for the account-level endpoints (brands, users).+ brand_id: str | None = None+++def _get_headers(api_key: str) -> dict[str, str]:+ return {"X-API-Key": api_key, "Accept": "application/json"}+++def _build_url(path: str, cursor: str | None) -> str:+ params: dict[str, Any] = {"limit": PAGE_SIZE}+ if cursor:+ params["cursor"] = cursor+ return f"{BIGMAILER_BASE_URL}{path}?{urlencode(params)}"+++def _fetch_page(session: requests.Session, url: str, logger: FilteringBoundLogger) -> dict:+ """Fetch a single list page. The tracked session retries 429/5xx with backoff, so by the time we+ inspect the response any transient errors are already exhausted."""+ response = session.get(url, timeout=REQUEST_TIMEOUT_SECONDS)++ # An invalid key returns 400 with `{"type": "invalid_request_error", "message": "Invalid api key"}`;+ # insufficient permissions surface as 401/403. None of these are retryable.+ if response.status_code in (401, 403) or (response.status_code == 400 and "api key" in response.text.lower()):+ raise BigMailerAuthError(AUTH_ERROR_MESSAGE)++ if not response.ok:+ logger.error(f"BigMailer API error: status={response.status_code}, body={response.text}, url={url}")+ response.raise_for_status()++ return response.json()+++def _iter_pages(+ session: requests.Session,+ path: str,+ logger: FilteringBoundLogger,+ manager: ResumableSourceManager[BigMailerResumeConfig],+ start_cursor: str | None,+ brand_id: str | None,+) -> Iterator[list[dict]]:+ """Page through a list endpoint, yielding one page of raw rows at a time.++ Saves resume state AFTER yielding each page (pointing at the next page) so a crash re-fetches the+ in-flight page rather than skipping it — the merge dedupes the re-pulled rows on the primary key.+ """+ cursor = start_cursor+ while True:+ data = _fetch_page(session, _build_url(path, cursor), logger)+ items = data.get("data", []) or []++ if items:+ yield items++ # The API always returns a `cursor`, but only `has_more` tells us another page exists.+ next_cursor = data.get("cursor") if data.get("has_more") else None+ if not next_cursor:+ break+ manager.save_state(BigMailerResumeConfig(cursor=next_cursor, brand_id=brand_id))+ cursor = next_cursor+++def _iter_brand_ids(session: requests.Session, logger: FilteringBoundLogger) -> Iterator[str]:+ """Page through /brands and yield each brand id, for fanning out brand-scoped endpoints."""+ cursor: str | None = None+ while True:+ data = _fetch_page(session, _build_url("/brands", cursor), logger)+ for item in data.get("data", []) or []:+ yield item["id"]+ cursor = data.get("cursor") if data.get("has_more") else None+ if not cursor:+ break+++def _get_top_level_rows(+ session: requests.Session,+ config: BigMailerEndpointConfig,+ logger: FilteringBoundLogger,+ manager: ResumableSourceManager[BigMailerResumeConfig],+) -> Iterator[list[dict]]:+ resume = manager.load_state() if manager.can_resume() else None+ start_cursor = resume.cursor if resume else None+ yield from _iter_pages(session, config.path, logger, manager, start_cursor, brand_id=None)+++def _get_brand_scoped_rows(+ session: requests.Session,+ config: BigMailerEndpointConfig,+ logger: FilteringBoundLogger,+ manager: ResumableSourceManager[BigMailerResumeConfig],+) -> Iterator[list[dict]]:+ """Fan out a brand-scoped endpoint over every brand, injecting `brand_id` into each row.++ Child objects (lists, segments, campaigns, …) don't carry their brand id in the response, so we+ add it here to keep the composite ["brand_id", "id"] key unique across the whole table.+ """+ brand_ids = list(_iter_brand_ids(session, logger))++ # Resolve the saved brand-ID bookmark to the slice of brands still to process. If the bookmarked+ # brand no longer exists (deleted between runs), start over — merge dedupes the re-pulled rows.+ resume = manager.load_state() if manager.can_resume() else None+ remaining = brand_ids+ resume_cursor: str | None = None+ if resume is not None and resume.brand_id is not None and resume.brand_id in brand_ids:+ remaining = brand_ids[brand_ids.index(resume.brand_id) :]+ resume_cursor = resume.cursor+ logger.debug(f"BigMailer: resuming {config.name} from brand_id={resume.brand_id}, cursor={resume_cursor}")++ for index, brand_id in enumerate(remaining):+ path = config.path.format(brand_id=brand_id)+ start_cursor = resume_cursor # only the resumed-into brand uses the saved cursor+ resume_cursor = None++ for items in _iter_pages(session, path, logger, manager, start_cursor, brand_id=brand_id):+ yield [{**item, "brand_id": brand_id} for item in items]++ # Advance the bookmark to the next brand so a crash between brands resumes correctly. Its first+ # page is fetched fresh (cursor=None).+ if index + 1 < len(remaining):+ manager.save_state(BigMailerResumeConfig(cursor=None, brand_id=remaining[index + 1]))+++def get_rows(+ api_key: str,+ endpoint: str,+ logger: FilteringBoundLogger,+ manager: ResumableSourceManager[BigMailerResumeConfig],+) -> Iterator[list[dict]]:+ config = BIGMAILER_ENDPOINTS[endpoint]+ # One session reused across every page (and every brand, for fan-out) so urllib3 keeps the+ # connection alive instead of re-handshaking per request. The api key is redacted from logged URLs.+ session = make_tracked_session(headers=_get_headers(api_key), redact_values=(api_key,))++ if config.brand_scoped:+ yield from _get_brand_scoped_rows(session, config, logger, manager)+ else:+ yield from _get_top_level_rows(session, config, logger, manager)+++def validate_credentials(api_key: str) -> bool:+ """Cheap probe that the key is genuine. /brands is account-wide and always reachable for a valid+ key, so a 200 confirms the credential without needing any specific brand or scope."""+ try:+ session = make_tracked_session(headers=_get_headers(api_key), redact_values=(api_key,))+ response = session.get(_build_url("/brands", cursor=None), timeout=REQUEST_TIMEOUT_SECONDS)+ return response.status_code == 200+ except Exception:+ return False+++def bigmailer_source(+ api_key: str,+ endpoint: str,+ logger: FilteringBoundLogger,+ manager: ResumableSourceManager[BigMailerResumeConfig],+) -> SourceResponse:+ config = BIGMAILER_ENDPOINTS[endpoint]++ return SourceResponse(+ name=endpoint,+ items=lambda: get_rows(api_key=api_key, endpoint=endpoint, logger=logger, manager=manager),+ primary_keys=config.primary_keys,+ partition_count=1,+ partition_size=1,+ partition_mode="datetime",+ partition_format="month",+ partition_keys=[config.partition_key],+ )diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/bigmailer/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/bigmailer/canonical_descriptions.pynew file mode 100644index 000000000000..05d094464978--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/bigmailer/canonical_descriptions.py@@ -0,0 +1,186 @@+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (+ CanonicalDescriptions,+)++# Descriptions taken from the official BigMailer API reference (https://docs.bigmailer.io/reference).+# `created` is UNIX epoch seconds on every object. Brand-scoped tables carry an injected `brand_id`+# column linking each row back to its brand.+CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {+ "brands": {+ "description": "Brands in your BigMailer account. A brand groups its own contacts, lists, campaigns and senders.",+ "docs_url": "https://docs.bigmailer.io/reference/listbrands",+ "columns": {+ "id": "Unique identifier of the brand.",+ "name": "Name of the brand.",+ "from_name": "Default 'From' name used for the brand's campaigns.",+ "from_email": "Default 'From' email address used for the brand's campaigns.",+ "num_contacts": "Number of contacts in the brand.",+ "contact_limit": "Maximum number of contacts allowed in the brand.",+ "url": "Brand website URL.",+ "created": "Time at which the brand was created, in seconds since the UNIX epoch.",+ },+ },+ "users": {+ "description": "Users (team members) with access to your BigMailer account.",+ "docs_url": "https://docs.bigmailer.io/reference/listusers",+ "columns": {+ "id": "Unique identifier of the user.",+ "email": "Email address of the user.",+ "role": "Account role of the user.",+ "is_owner": "Whether the user is the account owner.",+ "is_activated": "Whether the user has activated their account.",+ "created": "Time at which the user was created, in seconds since the UNIX epoch.",+ },+ },+ "contacts": {+ "description": "Contacts (subscribers) in a brand, with their field values, list memberships and bounce/complaint counts.",+ "docs_url": "https://docs.bigmailer.io/reference/listcontacts",+ "columns": {+ "id": "Unique identifier of the contact.",+ "brand_id": "Identifier of the brand the contact belongs to.",+ "email": "Email address of the contact.",+ "field_values": "Custom field values stored against the contact.",+ "list_ids": "Identifiers of the lists the contact is part of.",+ "unsubscribe_all": "True if the contact has unsubscribed from all message types.",+ "unsubscribe_ids": "Identifiers of message types the contact has unsubscribed from.",+ "num_soft_bounces": "Number of times a campaign to this contact has soft bounced.",+ "num_hard_bounces": "Number of times a campaign to this contact has hard bounced.",+ "num_complaints": "Number of times a campaign to this contact triggered a complaint.",+ "created": "Time at which the contact was created, in seconds since the UNIX epoch.",+ },+ },+ "lists": {+ "description": "Contact lists in a brand. Campaigns are sent to one or more lists.",+ "docs_url": "https://docs.bigmailer.io/reference/listlists",+ "columns": {+ "id": "Unique identifier of the list.",+ "brand_id": "Identifier of the brand the list belongs to.",+ "name": "Name of the list.",+ "all": "True if this is the brand's catch-all 'all contacts' list.",+ "num_contacts": "Number of contacts in the list.",+ "created": "Time at which the list was created, in seconds since the UNIX epoch.",+ },+ },+ "segments": {+ "description": "Segments in a brand: saved filters over contacts defined by a set of conditions.",+ "docs_url": "https://docs.bigmailer.io/reference/listsegments",+ "columns": {+ "id": "Unique identifier of the segment.",+ "brand_id": "Identifier of the brand the segment belongs to.",+ "name": "Name of the segment.",+ "operator": "Logical operator (and/or) combining the segment conditions.",+ "conditions": "Conditions that define which contacts match the segment.",+ "created": "Time at which the segment was created, in seconds since the UNIX epoch.",+ },+ },+ "fields": {+ "description": "Custom fields in a brand, used for personalization merge tags and segmentation.",+ "docs_url": "https://docs.bigmailer.io/reference/listfields",+ "columns": {+ "id": "Unique identifier of the field.",+ "brand_id": "Identifier of the brand the field belongs to.",+ "name": "Name of the field.",+ "type": "Data type of the field (e.g. string, integer, date).",+ "merge_tag_name": "Merge tag used to reference the field in campaign content.",+ "created": "Time at which the field was created, in seconds since the UNIX epoch.",+ },+ },+ "bulk_campaigns": {+ "description": "Bulk (one-off) email campaigns in a brand, with their configuration and aggregate send metrics.",+ "docs_url": "https://docs.bigmailer.io/reference/listbulkcampaigns",+ "columns": {+ "id": "Unique identifier of the campaign.",+ "brand_id": "Identifier of the brand the campaign belongs to.",+ "name": "Name of the campaign.",+ "subject": "Subject line of the campaign.",+ "status": "Lifecycle status (draft, pending, in progress, complete, error, paused, archived, active).",+ "list_ids": "Identifiers of the lists the campaign is sent to.",+ "segment_id": "Identifier of the segment used to filter recipients, if any.",+ "scheduled_for": "Scheduled send time, in seconds since the UNIX epoch.",+ "num_sent": "Number of emails sent.",+ "num_opens": "Number of unique opens.",+ "num_clicks": "Number of unique clicks.",+ "num_hard_bounces": "Number of hard bounces.",+ "num_soft_bounces": "Number of soft bounces.",+ "num_complaints": "Number of complaints.",+ "num_unsubscribes": "Number of unsubscribes.",+ "started": "Time at which the campaign started sending, in seconds since the UNIX epoch.",+ "sent": "Time at which the campaign finished sending, in seconds since the UNIX epoch.",+ "created": "Time at which the campaign was created, in seconds since the UNIX epoch.",+ },+ },+ "transactional_campaigns": {+ "description": "Transactional email campaigns in a brand, triggered per-recipient via the API, with aggregate metrics.",+ "docs_url": "https://docs.bigmailer.io/reference/listtransactionalcampaigns",+ "columns": {+ "id": "Unique identifier of the campaign.",+ "brand_id": "Identifier of the brand the campaign belongs to.",+ "name": "Name of the campaign.",+ "subject": "Subject line of the campaign.",+ "status": "Lifecycle status of the campaign.",+ "list_id": "Identifier of the list contacts are added to when sent.",+ "num_sent": "Number of emails sent.",+ "num_opens": "Number of unique opens.",+ "num_clicks": "Number of unique clicks.",+ "created": "Time at which the campaign was created, in seconds since the UNIX epoch.",+ },+ },+ "rss_campaigns": {+ "description": "RSS-driven email campaigns in a brand, which send on a schedule from a feed URL.",+ "docs_url": "https://docs.bigmailer.io/reference/listrsscampaigns",+ "columns": {+ "id": "Unique identifier of the campaign.",+ "brand_id": "Identifier of the brand the campaign belongs to.",+ "name": "Name of the campaign.",+ "subject": "Subject line of the campaign.",+ "feed_url": "RSS feed URL the campaign content is generated from.",+ "frequency": "How often the campaign checks the feed and sends.",+ "status": "Lifecycle status of the campaign.",+ "created": "Time at which the campaign was created, in seconds since the UNIX epoch.",+ },+ },+ "message_types": {+ "description": "Message types in a brand, the subscription categories contacts can opt out of independently.",+ "docs_url": "https://docs.bigmailer.io/reference/listmessagetypes",+ "columns": {+ "id": "Unique identifier of the message type.",+ "brand_id": "Identifier of the brand the message type belongs to.",+ "name": "Name of the message type.",+ "type": "Kind of message type.",+ "created": "Time at which the message type was created, in seconds since the UNIX epoch.",+ },+ },+ "senders": {+ "description": "Sender identities (from-addresses and bounce domains) configured for a brand.",+ "docs_url": "https://docs.bigmailer.io/reference/listsenders",+ "columns": {+ "id": "Unique identifier of the sender.",+ "brand_id": "Identifier of the brand the sender belongs to.",+ "identity_type": "Whether the sender identity is an email address or a domain.",+ "created": "Time at which the sender was created, in seconds since the UNIX epoch.",+ },+ },+ "templates": {+ "description": "Reusable email templates in a brand.",+ "docs_url": "https://docs.bigmailer.io/reference/listtemplates",+ "columns": {+ "id": "Unique identifier of the template.",+ "brand_id": "Identifier of the brand the template belongs to.",+ "name": "Name of the template.",+ "type": "Kind of template.",+ "shared_with_account": "Whether the template is shared across the account.",+ "created": "Time at which the template was created, in seconds since the UNIX epoch.",+ },+ },+ "suppression_lists": {+ "description": "Campaign suppression lists uploaded to a brand, used to exclude addresses from sends.",+ "docs_url": "https://docs.bigmailer.io/reference/listsuppressionlists",+ "columns": {+ "id": "Unique identifier of the suppression list.",+ "brand_id": "Identifier of the brand the suppression list belongs to.",+ "file_name": "Name of the uploaded suppression file.",+ "file_size": "Size of the uploaded suppression file in bytes.",+ "created": "Time at which the suppression list was created, in seconds since the UNIX epoch.",+ },+ },+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/bigmailer/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/bigmailer/settings.pynew file mode 100644index 000000000000..a90dd30b9227--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/bigmailer/settings.py@@ -0,0 +1,107 @@+from dataclasses import dataclass, field+++@dataclass+class BigMailerEndpointConfig:+ name: str+ # Path under the v1 base URL. Brand-scoped endpoints carry a `{brand_id}` placeholder that the+ # transport fills in per brand while fanning out.+ path: str+ # Brand-scoped endpoints live under /brands/{brand_id}/... and must be iterated once per brand.+ # Top-level endpoints (brands, users) are account-wide and queried directly.+ brand_scoped: bool = False+ # Stable creation timestamp used for datetime partitioning. Every BigMailer object exposes+ # `created` as UNIX epoch seconds, which never changes after creation.+ partition_key: str = "created"+ primary_keys: list[str] = field(default_factory=lambda: ["id"])+ # Whether the table is selected for sync by default in the connection wizard.+ should_sync_default: bool = True+++# BigMailer is brand-scoped: an account holds many brands and most resources hang off a brand. The+# transport lists brands once, then fans out the brand-scoped endpoints per brand, injecting+# `brand_id` into every row so the composite ["brand_id", "id"] key stays unique across the table.+#+# The API has no server-side timestamp filter on any list endpoint and cursor pagination doesn't+# accept a sort param, so every endpoint is full-refresh only (see source.py get_schemas).+_BRAND_COMPOSITE_KEY = ["brand_id", "id"]++BIGMAILER_ENDPOINTS: dict[str, BigMailerEndpointConfig] = {+ "brands": BigMailerEndpointConfig(+ name="brands",+ path="/brands",+ ),+ "users": BigMailerEndpointConfig(+ name="users",+ path="/users",+ should_sync_default=False,+ ),+ "contacts": BigMailerEndpointConfig(+ name="contacts",+ path="/brands/{brand_id}/contacts",+ brand_scoped=True,+ primary_keys=_BRAND_COMPOSITE_KEY,+ ),+ "lists": BigMailerEndpointConfig(+ name="lists",+ path="/brands/{brand_id}/lists",+ brand_scoped=True,+ primary_keys=_BRAND_COMPOSITE_KEY,+ ),+ "segments": BigMailerEndpointConfig(+ name="segments",+ path="/brands/{brand_id}/segments",+ brand_scoped=True,+ primary_keys=_BRAND_COMPOSITE_KEY,+ ),+ "fields": BigMailerEndpointConfig(+ name="fields",+ path="/brands/{brand_id}/fields",+ brand_scoped=True,+ primary_keys=_BRAND_COMPOSITE_KEY,+ ),+ "bulk_campaigns": BigMailerEndpointConfig(+ name="bulk_campaigns",+ path="/brands/{brand_id}/bulk-campaigns",+ brand_scoped=True,+ primary_keys=_BRAND_COMPOSITE_KEY,+ ),+ "transactional_campaigns": BigMailerEndpointConfig(+ name="transactional_campaigns",+ path="/brands/{brand_id}/transactional-campaigns",+ brand_scoped=True,+ primary_keys=_BRAND_COMPOSITE_KEY,+ ),+ "rss_campaigns": BigMailerEndpointConfig(+ name="rss_campaigns",+ path="/brands/{brand_id}/rss-campaigns",+ brand_scoped=True,+ primary_keys=_BRAND_COMPOSITE_KEY,+ ),+ "message_types": BigMailerEndpointConfig(+ name="message_types",+ path="/brands/{brand_id}/message-types",+ brand_scoped=True,+ primary_keys=_BRAND_COMPOSITE_KEY,+ ),+ "senders": BigMailerEndpointConfig(+ name="senders",+ path="/brands/{brand_id}/senders",+ brand_scoped=True,+ primary_keys=_BRAND_COMPOSITE_KEY,+ ),+ "templates": BigMailerEndpointConfig(+ name="templates",+ path="/brands/{brand_id}/templates",+ brand_scoped=True,+ primary_keys=_BRAND_COMPOSITE_KEY,+ ),+ "suppression_lists": BigMailerEndpointConfig(+ name="suppression_lists",+ path="/brands/{brand_id}/suppression-lists",+ brand_scoped=True,+ primary_keys=_BRAND_COMPOSITE_KEY,+ ),+}++ENDPOINTS = tuple(BIGMAILER_ENDPOINTS.keys())diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/bigmailer/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/bigmailer/source.pyindex faafc8ecf1fa..b00230f827f6 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/bigmailer/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/bigmailer/source.py@@ -1,19 +1,45 @@-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.bigmailer.bigmailer import (+ AUTH_ERROR_MESSAGE,+ BigMailerResumeConfig,+ bigmailer_source,+ validate_credentials as validate_bigmailer_credentials,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.bigmailer.settings import (+ BIGMAILER_ENDPOINTS,+ ENDPOINTS,+)+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 SourceSchemafrom products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs import BigMailerSourceConfigfrom products.warehouse_sources.backend.types import ExternalDataSourceType@SourceRegistry.register-class BigMailerSource(SimpleSource[BigMailerSourceConfig]):+class BigMailerSource(ResumableSource[BigMailerSourceConfig, BigMailerResumeConfig]):+ # `get_schemas` iterates a static endpoint catalog with no I/O, so the table list is safe to+ # render in public docs without credentials.+ lists_tables_without_credentials = True+@propertydef source_type(self) -> ExternalDataSourceType:return ExternalDataSourceType.BIGMAILER@@ -24,7 +50,89 @@ class BigMailerSource(SimpleSource[BigMailerSourceConfig]):name=SchemaExternalDataSourceType.BIG_MAILER,category=DataWarehouseSourceCategory.MARKETING___EMAIL,label="BigMailer",- iconPath="/static/services/bigmailer.png",- fields=cast(list[FieldType], []),+ releaseStatus=ReleaseStatus.ALPHA,+ # Kept hidden from the connector catalog while the source is validated end-to-end; flip this+ # off (delete the line) to make it connectable.unreleasedSource=True,+ caption="""Enter your BigMailer API key to sync your BigMailer data into the PostHog Data warehouse.++Create an API key in your BigMailer console under **Account Settings → API Keys**. The key has account-wide access, so no extra scopes need to be granted.""",+ iconPath="/static/services/bigmailer.png",+ docsUrl="https://posthog.com/docs/cdp/sources/bigmailer",+ fields=cast(+ list[FieldType],+ [+ 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.bigmailer.canonical_descriptions import (+ CANONICAL_DESCRIPTIONS,+ )++ return CANONICAL_DESCRIPTIONS++ def get_non_retryable_errors(self) -> dict[str, str | None]:+ return {+ AUTH_ERROR_MESSAGE: "Your BigMailer API key is invalid or lacks the required permissions. Create a new key in your BigMailer console, then reconnect.",+ }++ def get_schemas(+ self,+ config: BigMailerSourceConfig,+ team_id: int,+ with_counts: bool = False,+ names: list[str] | None = None,+ force_refresh: bool = False,+ ) -> list[SourceSchema]:+ # BigMailer has no server-side timestamp filter on any list endpoint, and cursor pagination+ # doesn't accept a sort param — an "incremental" sync would still page through everything, so+ # every table is full refresh only.+ def _build_schema(endpoint: str) -> SourceSchema:+ endpoint_config = BIGMAILER_ENDPOINTS[endpoint]+ return SourceSchema(+ name=endpoint,+ supports_incremental=False,+ supports_append=False,+ incremental_fields=[],+ should_sync_default=endpoint_config.should_sync_default,+ )++ schemas = [_build_schema(endpoint) 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: BigMailerSourceConfig, team_id: int, schema_name: Optional[str] = None+ ) -> tuple[bool, str | None]:+ if validate_bigmailer_credentials(config.api_key):+ return True, None++ return False, "Could not connect to BigMailer. Check your API key and try again."++ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[BigMailerResumeConfig]:+ return ResumableSourceManager[BigMailerResumeConfig](inputs, BigMailerResumeConfig)++ def source_for_pipeline(+ self,+ config: BigMailerSourceConfig,+ resumable_source_manager: ResumableSourceManager[BigMailerResumeConfig],+ inputs: SourceInputs,+ ) -> SourceResponse:+ return bigmailer_source(+ api_key=config.api_key,+ endpoint=inputs.schema_name,+ logger=inputs.logger,+ manager=resumable_source_manager,)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/bigmailer/tests/test_bigmailer.py b/products/warehouse_sources/backend/temporal/data_imports/sources/bigmailer/tests/test_bigmailer.pynew file mode 100644index 000000000000..cb7d97007651--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/bigmailer/tests/test_bigmailer.py@@ -0,0 +1,232 @@+import pytest+from unittest.mock import MagicMock, patch++import requests+from parameterized import parameterized++from products.warehouse_sources.backend.temporal.data_imports.sources.bigmailer import bigmailer+from products.warehouse_sources.backend.temporal.data_imports.sources.bigmailer.bigmailer import (+ AUTH_ERROR_MESSAGE,+ BigMailerAuthError,+ BigMailerResumeConfig,+ _build_url,+ _fetch_page,+ bigmailer_source,+ get_rows,+ validate_credentials,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager+++def _resp(status: int = 200, body: dict | None = None, text: str = "") -> MagicMock:+ response = MagicMock(spec=requests.Response)+ response.status_code = status+ response.ok = 200 <= status < 400+ response.json.return_value = body if body is not None else {}+ response.text = text++ def raise_for_status() -> None:+ if not response.ok:+ raise requests.HTTPError(f"{status} error", response=response)++ response.raise_for_status.side_effect = raise_for_status+ return response+++class FakeManager(ResumableSourceManager[BigMailerResumeConfig]):+ """Stand-in for ResumableSourceManager: records saved state and replays a seeded resume state.++ Overrides every method `get_rows` touches, so the Redis-bound base `__init__` is skipped.+ """++ def __init__(self, state: BigMailerResumeConfig | None = None) -> None:+ self._state = state+ self.saved: list[BigMailerResumeConfig] = []++ def can_resume(self) -> bool:+ return self._state is not None++ def load_state(self) -> BigMailerResumeConfig | None:+ return self._state++ def save_state(self, data: BigMailerResumeConfig) -> None:+ self.saved.append(data)+++def _session_returning(*responses: MagicMock) -> MagicMock:+ session = MagicMock()+ session.get.side_effect = list(responses)+ return session+++def _requested_urls(session: MagicMock) -> list[str]:+ return [call.args[0] for call in session.get.call_args_list]+++class TestBuildUrl:+ def test_includes_limit_and_no_cursor(self) -> None:+ assert _build_url("/brands", None) == "https://api.bigmailer.io/v1/brands?limit=100"++ def test_cursor_is_percent_encoded(self) -> None:+ # BigMailer cursors are base64 and contain `==`; leaving them raw would corrupt the query string.+ url = _build_url("/brands/b1/contacts", "K5pwIGH3hgYrhytbDUY5eQ==")+ assert "cursor=K5pwIGH3hgYrhytbDUY5eQ%3D%3D" in url+++class TestFetchPage:+ @parameterized.expand(+ [+ ("invalid_key_400", 400, '{"message":"Invalid api key"}'),+ ("unauthorized_401", 401, ""),+ ("forbidden_403", 403, ""),+ ]+ )+ def test_auth_failures_raise_non_retryable(self, _name: str, status: int, text: str) -> None:+ session = _session_returning(_resp(status=status, text=text))+ with pytest.raises(BigMailerAuthError) as exc:+ _fetch_page(session, "https://api.bigmailer.io/v1/brands?limit=100", MagicMock())+ assert str(exc.value) == AUTH_ERROR_MESSAGE++ def test_non_auth_400_raises_http_error_not_auth_error(self) -> None:+ # A 400 that isn't about the api key (e.g. a malformed param) must not be misreported as a+ # credential problem — otherwise a transient request bug would permanently disable the source.+ session = _session_returning(_resp(status=400, text='{"message":"bad cursor"}'))+ with pytest.raises(requests.HTTPError):+ _fetch_page(session, "https://api.bigmailer.io/v1/brands?limit=100", MagicMock())++ def test_404_raises_http_error(self) -> None:+ session = _session_returning(_resp(status=404, text="not found"))+ with pytest.raises(requests.HTTPError):+ _fetch_page(session, "https://api.bigmailer.io/v1/brands?limit=100", MagicMock())++ def test_200_returns_parsed_body(self) -> None:+ session = _session_returning(_resp(status=200, body={"data": [{"id": "x"}], "has_more": False}))+ assert _fetch_page(session, "https://api.bigmailer.io/v1/brands?limit=100", MagicMock()) == {+ "data": [{"id": "x"}],+ "has_more": False,+ }+++def _run(endpoint: str, session: MagicMock, manager: FakeManager) -> list[dict]:+ with patch.object(bigmailer, "make_tracked_session", return_value=session):+ rows: list[dict] = []+ for page in get_rows(api_key="key", endpoint=endpoint, logger=MagicMock(), manager=manager):+ rows.extend(page)+ return rows+++class TestTopLevelPagination:+ def test_follows_cursor_until_has_more_false(self) -> None:+ session = _session_returning(+ _resp(body={"data": [{"id": "b1", "created": 1}], "has_more": True, "cursor": "C2=="}),+ _resp(body={"data": [{"id": "b2", "created": 2}], "has_more": False, "cursor": "ignored"}),+ )+ rows = _run("brands", session, FakeManager())+ assert [r["id"] for r in rows] == ["b1", "b2"]+ # second request must carry the encoded cursor from page one+ assert "cursor=C2%3D%3D" in _requested_urls(session)[1]++ def test_does_not_inject_brand_id_for_top_level(self) -> None:+ session = _session_returning(_resp(body={"data": [{"id": "b1", "created": 1}], "has_more": False}))+ rows = _run("brands", session, FakeManager())+ assert "brand_id" not in rows[0]++ def test_saves_next_cursor_after_yielding_each_page(self) -> None:+ manager = FakeManager()+ session = _session_returning(+ _resp(body={"data": [{"id": "b1"}], "has_more": True, "cursor": "C2=="}),+ _resp(body={"data": [{"id": "b2"}], "has_more": False}),+ )+ _run("brands", session, manager)+ # one save (for the single page boundary that had a next page); none after the terminal page+ assert [(s.cursor, s.brand_id) for s in manager.saved] == [("C2==", None)]++ def test_resumes_from_saved_cursor(self) -> None:+ manager = FakeManager(BigMailerResumeConfig(cursor="RESUME==", brand_id=None))+ session = _session_returning(_resp(body={"data": [{"id": "b2"}], "has_more": False}))+ _run("brands", session, manager)+ assert "cursor=RESUME%3D%3D" in _requested_urls(session)[0]+++class TestBrandFanOut:+ def test_iterates_every_brand_and_injects_brand_id(self) -> None:+ session = _session_returning(+ _resp(body={"data": [{"id": "b1"}, {"id": "b2"}], "has_more": False}), # /brands+ _resp(body={"data": [{"id": "c1", "created": 1}], "has_more": False}), # b1 contacts+ _resp(body={"data": [{"id": "c2", "created": 2}], "has_more": False}), # b2 contacts+ )+ rows = _run("contacts", session, FakeManager())+ assert [(r["id"], r["brand_id"]) for r in rows] == [("c1", "b1"), ("c2", "b2")]++ def test_paginates_within_a_brand(self) -> None:+ session = _session_returning(+ _resp(body={"data": [{"id": "b1"}], "has_more": False}), # /brands+ _resp(body={"data": [{"id": "c1"}], "has_more": True, "cursor": "P2=="}), # b1 contacts page 1+ _resp(body={"data": [{"id": "c2"}], "has_more": False}), # b1 contacts page 2+ )+ rows = _run("contacts", session, FakeManager())+ assert [r["id"] for r in rows] == ["c1", "c2"]+ assert "cursor=P2%3D%3D" in _requested_urls(session)[2]++ def test_resume_skips_already_processed_brands(self) -> None:+ # Resuming mid-fan-out must not re-request brands processed before the crash, and must start the+ # bookmarked brand from its saved cursor.+ manager = FakeManager(BigMailerResumeConfig(cursor="MID==", brand_id="b2"))+ session = _session_returning(+ _resp(body={"data": [{"id": "b1"}, {"id": "b2"}, {"id": "b3"}], "has_more": False}), # /brands+ _resp(body={"data": [{"id": "c2"}], "has_more": False}), # b2 contacts (resumed)+ _resp(body={"data": [{"id": "c3"}], "has_more": False}), # b3 contacts (fresh)+ )+ rows = _run("contacts", session, manager)+ urls = _requested_urls(session)+ assert not any("/brands/b1/contacts" in u for u in urls)+ assert "/brands/b2/contacts" in urls[1] and "cursor=MID%3D%3D" in urls[1]+ assert "/brands/b3/contacts" in urls[2] and "cursor=" not in urls[2]+ assert [r["id"] for r in rows] == ["c2", "c3"]++ def test_advances_bookmark_between_brands(self) -> None:+ manager = FakeManager()+ session = _session_returning(+ _resp(body={"data": [{"id": "b1"}, {"id": "b2"}], "has_more": False}),+ _resp(body={"data": [{"id": "c1"}], "has_more": False}),+ _resp(body={"data": [{"id": "c2"}], "has_more": False}),+ )+ _run("contacts", session, manager)+ # after finishing b1 we bookmark b2 at its first page so a crash resumes on b2, not b1+ assert BigMailerResumeConfig(cursor=None, brand_id="b2") in manager.saved+++class TestValidateCredentials:+ @parameterized.expand([("ok", 200, True), ("invalid", 400, False), ("forbidden", 403, False)])+ def test_status_maps_to_bool(self, _name: str, status: int, expected: bool) -> None:+ session = _session_returning(_resp(status=status))+ with patch.object(bigmailer, "make_tracked_session", return_value=session):+ assert validate_credentials("key") is expected++ def test_network_error_is_false(self) -> None:+ session = MagicMock()+ session.get.side_effect = requests.ConnectionError("boom")+ with patch.object(bigmailer, "make_tracked_session", return_value=session):+ assert validate_credentials("key") is False+++class TestSourceResponse:+ @parameterized.expand(+ [+ ("brands", ["id"]),+ ("users", ["id"]),+ ("contacts", ["brand_id", "id"]),+ ("bulk_campaigns", ["brand_id", "id"]),+ ("suppression_lists", ["brand_id", "id"]),+ ]+ )+ def test_primary_keys_per_endpoint(self, endpoint: str, expected_keys: list[str]) -> None:+ response = bigmailer_source(api_key="key", endpoint=endpoint, logger=MagicMock(), manager=MagicMock())+ assert response.name == endpoint+ assert response.primary_keys == expected_keys++ def test_partitions_on_created_by_month(self) -> None:+ response = bigmailer_source(api_key="key", endpoint="contacts", logger=MagicMock(), manager=MagicMock())+ assert response.partition_mode == "datetime"+ assert response.partition_format == "month"+ assert response.partition_keys == ["created"]diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/bigmailer/tests/test_bigmailer_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/bigmailer/tests/test_bigmailer_source.pynew file mode 100644index 000000000000..5832130fd8f3--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/bigmailer/tests/test_bigmailer_source.py@@ -0,0 +1,125 @@+from typing import cast++from unittest.mock import MagicMock, patch++from parameterized import parameterized++from posthog.schema import (+ DataWarehouseSourceCategory,+ ExternalDataSourceType as SchemaExternalDataSourceType,+ ReleaseStatus,+ SourceFieldInputConfig,+ SourceFieldInputConfigType,+)++from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import SourceInputs+from products.warehouse_sources.backend.temporal.data_imports.sources.bigmailer import source as source_module+from products.warehouse_sources.backend.temporal.data_imports.sources.bigmailer.bigmailer import (+ AUTH_ERROR_MESSAGE,+ BigMailerResumeConfig,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.bigmailer.settings import ENDPOINTS+from products.warehouse_sources.backend.temporal.data_imports.sources.bigmailer.source import BigMailerSource+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs import BigMailerSourceConfig+from products.warehouse_sources.backend.types import ExternalDataSourceType+++def _config(api_key: str = "key") -> BigMailerSourceConfig:+ return cast(BigMailerSourceConfig, BigMailerSource()._config_class(api_key=api_key))+++def _inputs(schema_name: str) -> SourceInputs:+ return SourceInputs(+ schema_name=schema_name,+ schema_id="schema-1",+ source_id="source-1",+ team_id=1,+ should_use_incremental_field=False,+ db_incremental_field_last_value=None,+ db_incremental_field_earliest_value=None,+ incremental_field=None,+ incremental_field_type=None,+ job_id="job-1",+ logger=MagicMock(),+ reset_pipeline=False,+ )+++class TestSourceConfig:+ def test_source_type(self) -> None:+ assert BigMailerSource().source_type == ExternalDataSourceType.BIGMAILER++ def test_config_identity_and_release(self) -> None:+ config = BigMailerSource().get_source_config+ assert config.name == SchemaExternalDataSourceType.BIG_MAILER+ assert config.category == DataWarehouseSourceCategory.MARKETING___EMAIL+ # shipped as a hidden alpha: unreleasedSource keeps it out of the catalog until it's validated+ assert config.releaseStatus == ReleaseStatus.ALPHA+ assert config.unreleasedSource is True+ assert config.docsUrl == "https://posthog.com/docs/cdp/sources/bigmailer"++ def test_single_password_api_key_field(self) -> None:+ fields = cast(list[SourceFieldInputConfig], BigMailerSource().get_source_config.fields)+ assert [f.name for f in fields] == ["api_key"]+ assert fields[0].type == SourceFieldInputConfigType.PASSWORD+ assert fields[0].required is True+++class TestGetSchemas:+ def test_returns_every_endpoint_as_full_refresh(self) -> None:+ schemas = BigMailerSource().get_schemas(_config(), team_id=1)+ assert {s.name for s in schemas} == set(ENDPOINTS)+ # BigMailer has no server-side time filter, so no table may advertise incremental or append+ assert all(not s.supports_incremental and not s.supports_append for s in schemas)+ assert all(s.incremental_fields == [] for s in schemas)++ def test_users_is_not_synced_by_default(self) -> None:+ # account-level admin data shouldn't be pulled unless the user opts in; the marketing tables should+ by_name = {s.name: s for s in BigMailerSource().get_schemas(_config(), team_id=1)}+ assert by_name["users"].should_sync_default is False+ assert by_name["contacts"].should_sync_default is True++ def test_names_filter(self) -> None:+ schemas = BigMailerSource().get_schemas(_config(), team_id=1, names=["contacts", "lists"])+ assert {s.name for s in schemas} == {"contacts", "lists"}+++class TestDocumentedTables:+ def test_renders_table_catalog_without_credentials(self) -> None:+ # lists_tables_without_credentials must stay on so posthog.com renders the Supported tables section+ assert BigMailerSource().lists_tables_without_credentials is True+ tables = BigMailerSource().get_documented_tables()+ assert {t["name"] for t in tables} == set(ENDPOINTS)+ brands = next(t for t in tables if t["name"] == "brands")+ assert brands["sync_methods"] == ["Full refresh"]+ assert brands["description"] # canonical description is wired up+++class TestCredentials:+ @parameterized.expand([("valid", True, True), ("invalid", False, False)])+ def test_validate_credentials_plumbing(self, _name: str, probe_result: bool, expected_ok: bool) -> None:+ with patch.object(source_module, "validate_bigmailer_credentials", return_value=probe_result):+ ok, error = BigMailerSource().validate_credentials(_config(), team_id=1)+ assert ok is expected_ok+ assert (error is None) is expected_ok++ def test_non_retryable_errors_cover_auth_failure(self) -> None:+ errors = BigMailerSource().get_non_retryable_errors()+ assert AUTH_ERROR_MESSAGE in errors+ assert errors[AUTH_ERROR_MESSAGE] # has a user-facing message+++class TestPipelineHandoff:+ def test_resumable_manager_bound_to_resume_config(self) -> None:+ manager = BigMailerSource().get_resumable_source_manager(_inputs("contacts"))+ assert isinstance(manager, ResumableSourceManager)+ assert manager._data_class is BigMailerResumeConfig++ @parameterized.expand([("contacts", ["brand_id", "id"]), ("brands", ["id"])])+ def test_source_for_pipeline_builds_response(self, endpoint: str, expected_keys: list[str]) -> None:+ src = BigMailerSource()+ inputs = _inputs(endpoint)+ response = src.source_for_pipeline(_config(), src.get_resumable_source_manager(inputs), inputs)+ assert response.name == endpoint+ assert response.primary_keys == expected_keysdiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.py b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.pyindex 5bfb024c2ee0..fc948e0752aa 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@@ -409,7 +409,7 @@ class BigCommerceSourceConfig(config.Config):@config.configclass BigMailerSourceConfig(config.Config):- pass+ api_key: str@config.config