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 sparkpost import source (#65648)

Tom Owers93ee8e009f81
diff --git a/posthog/temporal/data_imports/sources/SOURCES.md b/posthog/temporal/data_imports/sources/SOURCES.md
index 793618312aef..42772178b309 100644
--- a/posthog/temporal/data_imports/sources/SOURCES.md
+++ b/posthog/temporal/data_imports/sources/SOURCES.md
@@ -182,6 +182,7 @@ the row lists both.
| smartsheet | HTTP | requests | ✅ |
| snapchat_ads | HTTP | requests + `rest_source.RESTClient` | ✅ |
| snowflake | DB protocol | snowflake-connector-python | ➖ |
+| sparkpost | HTTP | requests | ✅ |
| square | HTTP | requests | ✅ |
| statuspage | HTTP | requests | ✅ |
| stripe | HTTP (vendor SDK) + Webhook | stripe (StripeClient + RequestsClient) + `WebhookSourceManager` | ✅ (pull) / ➖ (webhook) |
@@ -631,7 +632,6 @@ doesn't conflict with concurrent PRs.
- smartwaiver
- solarwinds_service_desk
- sonar_cloud
-- sparkpost
- split_io
- spotify_ads
- spotlercrm
diff --git a/posthog/temporal/data_imports/sources/generated_configs.py b/posthog/temporal/data_imports/sources/generated_configs.py
index a6cbda9c47df..2562ce5a77fa 100644
--- a/posthog/temporal/data_imports/sources/generated_configs.py
+++ b/posthog/temporal/data_imports/sources/generated_configs.py
@@ -2915,7 +2915,8 @@ class SonarCloudSourceConfig(config.Config):
@config.config
class SparkPostSourceConfig(config.Config):
- pass
+ api_key: str
+ region: Literal["us", "eu"] = config.value(default="us")
@config.config
diff --git a/posthog/temporal/data_imports/sources/sparkpost/api_inventory.md b/posthog/temporal/data_imports/sources/sparkpost/api_inventory.md
new file mode 100644
index 000000000000..78fa9081f620
--- /dev/null
+++ b/posthog/temporal/data_imports/sources/sparkpost/api_inventory.md
@@ -0,0 +1,39 @@
+# SparkPost API inventory
+
+SparkPost (now part of Bird) — transactional & marketing email delivery. REST/JSON.
+
+- **Hosts (independent stacks, no shared data):** US `https://api.sparkpost.com`, EU `https://api.eu.sparkpost.com`. User picks the region.
+- **Auth:** API key passed verbatim in the `Authorization` header (no `Bearer` prefix).
+- **Rate limiting:** dynamic; `429` with a 1–5s back-off hint. Pagination requests count against the limit. Handled with bounded `tenacity` retries on `429`/`5xx`.
+- **Credential probe:** `GET /api/v1/account`.
+
+## Endpoints
+
+| Schema | Path | Pagination | Primary key | Partition key | Incremental |
+| ------------------ | -------------------------- | ---------- | ------------------- | ------------- | ---------------------------------- |
+| `events` | `/api/v1/events/message` | cursor | `event_id` | `timestamp` | yes — `from` filter on `timestamp` |
+| `suppression_list` | `/api/v1/suppression-list` | cursor | `recipient`, `type` | `created` | no (full refresh) |
+| `recipient_lists` | `/api/v1/recipient-lists` | none | `id` | — | no (full refresh) |
+| `templates` | `/api/v1/templates` | none | `id` | — | no (full refresh) |
+| `sending_domains` | `/api/v1/sending-domains` | none | `domain` | — | no (full refresh) |
+| `subaccounts` | `/api/v1/subaccounts` | none | `id` | — | no (full refresh) |
+| `webhooks` | `/api/v1/webhooks` | none | `id` | — | no (full refresh) |
+
+## Notes / gotchas
+
+- **Response shape:** every list endpoint wraps records in `{"results": [...]}`.
+- **Cursor pagination:** opt in by sending `cursor=initial` + `per_page` on the first request, then follow the
+ `links` array entry with `rel: next` (the `href` is a path relative to the API host). The management list
+ endpoints return a single page.
+- **Event retention is 10 days**, so the first sync of `events` is bounded to that window
+ (`default_lookback_days=10`).
+- **`from` is inclusive, `to` exclusive.** We send only `from` (open upper bound) and map it from the stored
+ watermark; the boundary event is re-fetched and deduped on `event_id` by the merge.
+- **Verification caveat:** endpoint hosts and `401` error shape were confirmed with unauthenticated curl. The
+ server-side behaviour of `from`/`to` filtering, the exact cursor-link format, and event sort order could not
+ be exercised end-to-end without a live API key, so they follow the public SparkPost docs. Only `events` is
+ marked incremental (the one endpoint with a documented server-side timestamp filter); everything else ships
+ full refresh and dedupes on its primary key.
+- **Webhooks:** SparkPost exposes a programmatic Event Webhooks API (`/api/v1/webhooks`). This source pulls the
+ webhook _configuration_ as a table but does not (yet) register PostHog as a push destination — a future
+ `WebhookSource` enhancement.
diff --git a/posthog/temporal/data_imports/sources/sparkpost/canonical_descriptions.py b/posthog/temporal/data_imports/sources/sparkpost/canonical_descriptions.py
new file mode 100644
index 000000000000..bc97dcc7345e
--- /dev/null
+++ b/posthog/temporal/data_imports/sources/sparkpost/canonical_descriptions.py
@@ -0,0 +1,91 @@
+from posthog.temporal.data_imports.sources.common.canonical_descriptions import CanonicalDescriptions
+
+# Descriptions sourced from the public SparkPost API documentation. Keyed by the endpoint/schema
+# name returned by `get_schemas`. Partial coverage is fine — anything omitted falls back to LLM
+# enrichment with the table's `docs_url` and column types.
+CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
+ "events": {
+ "description": "Message events (deliveries, bounces, opens, clicks, etc.) from the SparkPost Events Search API. Retained for 10 days.",
+ "docs_url": "https://developers.sparkpost.com/api/events/",
+ "columns": {
+ "event_id": "Unique identifier for the event.",
+ "type": "Event type (e.g. delivery, bounce, open, click, injection, spam_complaint).",
+ "timestamp": "ISO 8601 UTC time the event occurred.",
+ "message_id": "Unique identifier for the message that generated the event.",
+ "transmission_id": "Identifier of the transmission that sent the message.",
+ "campaign_id": "Campaign the message was associated with.",
+ "rcpt_to": "Recipient email address the message was sent to.",
+ "subaccount_id": "Subaccount the message was sent from, if any.",
+ "bounce_class": "Numeric classification of a bounce event.",
+ "reason": "Human-readable reason returned by the receiving mailbox provider.",
+ "ip_address": "Sending IP address used for the message.",
+ "sending_ip": "Sending IP address used for the message.",
+ "template_id": "Stored template used to generate the message, if any.",
+ },
+ },
+ "suppression_list": {
+ "description": "Recipients on the account's suppression list, who are excluded from sends.",
+ "docs_url": "https://developers.sparkpost.com/api/suppression-list/",
+ "columns": {
+ "recipient": "Suppressed recipient email address.",
+ "type": "Suppression type: transactional or non_transactional.",
+ "source": "How the entry was added (e.g. Bounce Rule, Spam Complaint, Manually Added).",
+ "description": "Free-text description of why the recipient was suppressed.",
+ "transactional": "Whether the recipient is suppressed for transactional messages.",
+ "non_transactional": "Whether the recipient is suppressed for non-transactional messages.",
+ "created": "ISO 8601 UTC time the suppression entry was created.",
+ "updated": "ISO 8601 UTC time the suppression entry was last updated.",
+ },
+ },
+ "recipient_lists": {
+ "description": "Stored recipient lists used to address transmissions.",
+ "docs_url": "https://developers.sparkpost.com/api/recipient-lists/",
+ "columns": {
+ "id": "Unique identifier for the recipient list.",
+ "name": "Human-readable name of the recipient list.",
+ "description": "Description of the recipient list.",
+ "total_accepted_recipients": "Number of recipients in the list.",
+ },
+ },
+ "templates": {
+ "description": "Stored message templates.",
+ "docs_url": "https://developers.sparkpost.com/api/templates/",
+ "columns": {
+ "id": "Unique identifier for the template.",
+ "name": "Human-readable name of the template.",
+ "description": "Description of the template.",
+ "published": "Whether the template is published (vs draft).",
+ "last_update_time": "ISO 8601 UTC time the template was last updated.",
+ },
+ },
+ "sending_domains": {
+ "description": "Domains configured for sending mail through SparkPost.",
+ "docs_url": "https://developers.sparkpost.com/api/sending-domains/",
+ "columns": {
+ "domain": "The sending domain.",
+ "status": "DKIM, SPF, ownership, and compliance verification status for the domain.",
+ "shared_with_subaccounts": "Whether the domain is shared with subaccounts.",
+ },
+ },
+ "subaccounts": {
+ "description": "Subaccounts under the primary account.",
+ "docs_url": "https://developers.sparkpost.com/api/subaccounts/",
+ "columns": {
+ "id": "Unique identifier for the subaccount.",
+ "name": "Human-readable name of the subaccount.",
+ "status": "Subaccount status (active, suspended, terminated).",
+ "compliance_status": "Compliance status of the subaccount.",
+ },
+ },
+ "webhooks": {
+ "description": "Configured event webhooks that push message events to external endpoints.",
+ "docs_url": "https://developers.sparkpost.com/api/webhooks/",
+ "columns": {
+ "id": "Unique identifier for the webhook.",
+ "name": "Human-readable name of the webhook.",
+ "target": "Destination URL the webhook posts events to.",
+ "events": "Event types the webhook is subscribed to.",
+ "active": "Whether the webhook is currently active.",
+ },
+ },
+}
diff --git a/posthog/temporal/data_imports/sources/sparkpost/settings.py b/posthog/temporal/data_imports/sources/sparkpost/settings.py
new file mode 100644
index 000000000000..dfaec219b691
--- /dev/null
+++ b/posthog/temporal/data_imports/sources/sparkpost/settings.py
@@ -0,0 +1,120 @@
+from dataclasses import dataclass, field
+from typing import Literal, Optional
+
+from products.data_warehouse.backend.types import IncrementalField, IncrementalFieldType
+
+PaginationStyle = Literal["cursor", "none"]
+
+
+@dataclass
+class SparkPostEndpointConfig:
+ name: str
+ path: str
+ # Key in the response body holding the list of records. SparkPost wraps every list endpoint in
+ # ``{"results": [...]}``.
+ data_path: str = "results"
+ primary_keys: list[str] = field(default_factory=lambda: ["id"])
+ pagination: PaginationStyle = "none"
+ per_page: int = 10000
+ # Stable, immutable datetime field used for partitioning (never ``updated``/``last_update_time``).
+ partition_key: Optional[str] = None
+ incremental_fields: list[IncrementalField] = field(default_factory=list)
+ default_incremental_field: Optional[str] = None
+ # Server-side timestamp filter param (e.g. ``from``). Only set when the API genuinely filters
+ # server-side — leaving it ``None`` keeps the endpoint full-refresh only.
+ timestamp_filter_param: Optional[str] = None
+ # First-sync lookback window for endpoints with a server-side timestamp filter. SparkPost only
+ # retains message events for 10 days, so a "full" backfill of events is bounded to that window.
+ default_lookback_days: Optional[int] = None
+ should_sync_default: bool = True
+
+ @property
+ def supports_incremental(self) -> bool:
+ return self.timestamp_filter_param is not None
+
+
+def _timestamp_incremental_fields(field_name: str) -> list[IncrementalField]:
+ return [
+ {
+ "label": field_name,
+ "type": IncrementalFieldType.DateTime,
+ "field": field_name,
+ "field_type": IncrementalFieldType.DateTime,
+ }
+ ]
+
+
+# Endpoint catalog. SparkPost (now part of Bird) ships no dedicated Airbyte/Fivetran connector, so
+# coverage is drawn from the public SparkPost API: the Events Search API plus the management list
+# endpoints a user typically wants in the warehouse (suppression list, recipient lists, templates,
+# sending domains, subaccounts, webhooks).
+#
+# Incremental vs full refresh: only the Events Search API exposes a genuine server-side timestamp
+# filter (``from``/``to``), so only ``events`` is marked incremental. The management list endpoints
+# have no server-side time filter, so they ship as full refresh and dedupe on their primary key.
+SPARKPOST_ENDPOINTS: dict[str, SparkPostEndpointConfig] = {
+ # --- Append-only, server-side timestamp filter (incremental) ---
+ "events": SparkPostEndpointConfig(
+ name="events",
+ path="/api/v1/events/message",
+ primary_keys=["event_id"],
+ pagination="cursor",
+ per_page=10000,
+ partition_key="timestamp",
+ incremental_fields=_timestamp_incremental_fields("timestamp"),
+ default_incremental_field="timestamp",
+ timestamp_filter_param="from",
+ default_lookback_days=10,
+ ),
+ # --- Full refresh ---
+ "suppression_list": SparkPostEndpointConfig(
+ name="suppression_list",
+ path="/api/v1/suppression-list",
+ # A recipient can be suppressed independently for transactional and non-transactional mail,
+ # surfacing as two rows that share a ``recipient`` — so the type is part of the key.
+ primary_keys=["recipient", "type"],
+ pagination="cursor",
+ per_page=10000,
+ partition_key="created",
+ ),
+ "recipient_lists": SparkPostEndpointConfig(
+ name="recipient_lists",
+ path="/api/v1/recipient-lists",
+ primary_keys=["id"],
+ pagination="none",
+ ),
+ "templates": SparkPostEndpointConfig(
+ name="templates",
+ path="/api/v1/templates",
+ primary_keys=["id"],
+ pagination="none",
+ ),
+ "sending_domains": SparkPostEndpointConfig(
+ name="sending_domains",
+ path="/api/v1/sending-domains",
+ primary_keys=["domain"],
+ pagination="none",
+ ),
+ "subaccounts": SparkPostEndpointConfig(
+ name="subaccounts",
+ path="/api/v1/subaccounts",
+ primary_keys=["id"],
+ pagination="none",
+ ),
+ "webhooks": SparkPostEndpointConfig(
+ name="webhooks",
+ path="/api/v1/webhooks",
+ primary_keys=["id"],
+ pagination="none",
+ ),
+}
+
+ENDPOINTS = tuple(SPARKPOST_ENDPOINTS.keys())
+
+INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {
+ name: config.incremental_fields for name, config in SPARKPOST_ENDPOINTS.items()
+}
+
+# SparkPost retains message events for only 10 days, so the first sync of ``events`` can reach back
+# at most that far.
+LIMITED_RETENTION_ENDPOINTS = {"events"}
diff --git a/posthog/temporal/data_imports/sources/sparkpost/source.py b/posthog/temporal/data_imports/sources/sparkpost/source.py
index 198a0eab130a..3d62af343b24 100644
--- a/posthog/temporal/data_imports/sources/sparkpost/source.py
+++ b/posthog/temporal/data_imports/sources/sparkpost/source.py
@@ -1,31 +1,160 @@
-from typing import cast
+from typing import Optional, cast
from posthog.schema import (
DataWarehouseSourceCategory,
ExternalDataSourceType as SchemaExternalDataSourceType,
+ ReleaseStatus,
SourceConfig,
+ SourceFieldInputConfig,
+ SourceFieldInputConfigType,
+ SourceFieldSelectConfig,
+ SourceFieldSelectConfigOption,
)
-from posthog.temporal.data_imports.sources.common.base import FieldType, SimpleSource
+from posthog.temporal.data_imports.pipelines.pipeline.typings import SourceInputs, SourceResponse
+from posthog.temporal.data_imports.sources.common.base import FieldType, ResumableSource
+from posthog.temporal.data_imports.sources.common.canonical_descriptions import CanonicalDescriptions
from posthog.temporal.data_imports.sources.common.registry import SourceRegistry
+from posthog.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from posthog.temporal.data_imports.sources.common.schema import SourceSchema
from posthog.temporal.data_imports.sources.generated_configs import SparkPostSourceConfig
+from posthog.temporal.data_imports.sources.sparkpost.settings import (
+ ENDPOINTS,
+ INCREMENTAL_FIELDS,
+ LIMITED_RETENTION_ENDPOINTS,
+ SPARKPOST_ENDPOINTS,
+)
+from posthog.temporal.data_imports.sources.sparkpost.sparkpost import (
+ SparkPostResumeConfig,
+ sparkpost_source,
+ validate_credentials as validate_sparkpost_credentials,
+)
from products.data_warehouse.backend.types import ExternalDataSourceType
@SourceRegistry.register
-class SparkPostSource(SimpleSource[SparkPostSourceConfig]):
+class SparkPostSource(ResumableSource[SparkPostSourceConfig, SparkPostResumeConfig]):
@property
def source_type(self) -> ExternalDataSourceType:
return ExternalDataSourceType.SPARKPOST
+ @property
+ def connection_host_fields(self) -> list[str]:
+ # The API key is sent to the host derived from `region`, so changing the region must
+ # re-require the key rather than reusing it against a different host.
+ return ["region"]
+
@property
def get_source_config(self) -> SourceConfig:
return SourceConfig(
name=SchemaExternalDataSourceType.SPARK_POST,
category=DataWarehouseSourceCategory.MARKETING___EMAIL,
label="SparkPost",
- iconPath="/static/services/sparkpost.png",
- fields=cast(list[FieldType], []),
+ releaseStatus=ReleaseStatus.ALPHA,
+ # Kept hidden for now: the implementation follows the public SparkPost docs but its
+ # end-to-end sync behaviour hasn't been exercised against a live account yet.
unreleasedSource=True,
+ caption="""Connect your SparkPost account to sync message events, suppression lists, recipient lists, templates, sending domains, subaccounts, and webhooks into the PostHog Data warehouse.
+
+Create an API key in your [SparkPost account settings](https://app.sparkpost.com/account/api-keys) (or the EU console at app.eu.sparkpost.com). Grant the read permissions for the data you want to sync, for example:
+- `Events: Read-only`
+- `Suppression Lists: Read-only`
+- `Recipient Lists: Read-only`
+- `Templates: Read-only`
+- `Sending Domains: Read-only`
+- `Subaccounts: Read-only`
+- `Webhooks: Read-only`
+
+SparkPost runs independent US and EU stacks that do not share data — pick the region your account is on. Message events are retained for 10 days, so the initial sync of events can only reach back that far.""",
+ iconPath="/static/services/sparkpost.png",
+ docsUrl="https://posthog.com/docs/cdp/sources/sparkpost",
+ fields=cast(
+ list[FieldType],
+ [
+ SourceFieldSelectConfig(
+ name="region",
+ label="Region",
+ required=True,
+ defaultValue="us",
+ options=[
+ SourceFieldSelectConfigOption(label="US (api.sparkpost.com)", value="us"),
+ SourceFieldSelectConfigOption(label="EU (api.eu.sparkpost.com)", value="eu"),
+ ],
+ ),
+ SourceFieldInputConfig(
+ name="api_key",
+ label="API key",
+ type=SourceFieldInputConfigType.PASSWORD,
+ required=True,
+ placeholder="SparkPost API key",
+ secret=True,
+ ),
+ ],
+ ),
+ )
+
+ def get_canonical_descriptions(self) -> CanonicalDescriptions:
+ from posthog.temporal.data_imports.sources.sparkpost.canonical_descriptions import CANONICAL_DESCRIPTIONS
+
+ return CANONICAL_DESCRIPTIONS
+
+ def get_non_retryable_errors(self) -> dict[str, str | None]:
+ return {
+ "401 Client Error": "Invalid SparkPost API key. Generate a valid key and reconnect.",
+ "403 Client Error": "Your SparkPost API key is missing the read permissions for this data. Grant the required permissions and reconnect.",
+ }
+
+ def get_schemas(
+ self,
+ config: SparkPostSourceConfig,
+ team_id: int,
+ with_counts: bool = False,
+ names: list[str] | None = None,
+ force_refresh: bool = False,
+ ) -> list[SourceSchema]:
+ schemas = [
+ SourceSchema(
+ name=endpoint,
+ supports_incremental=SPARKPOST_ENDPOINTS[endpoint].supports_incremental,
+ supports_append=SPARKPOST_ENDPOINTS[endpoint].supports_incremental,
+ incremental_fields=INCREMENTAL_FIELDS.get(endpoint, []),
+ should_sync_default=SPARKPOST_ENDPOINTS[endpoint].should_sync_default,
+ description=(
+ "Only the last 10 days are available on initial sync (SparkPost event retention)"
+ if endpoint in LIMITED_RETENTION_ENDPOINTS
+ else None
+ ),
+ )
+ 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: SparkPostSourceConfig, team_id: int, schema_name: Optional[str] = None
+ ) -> tuple[bool, str | None]:
+ return validate_sparkpost_credentials(config.region, config.api_key)
+
+ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[SparkPostResumeConfig]:
+ return ResumableSourceManager[SparkPostResumeConfig](inputs, SparkPostResumeConfig)
+
+ def source_for_pipeline(
+ self,
+ config: SparkPostSourceConfig,
+ resumable_source_manager: ResumableSourceManager[SparkPostResumeConfig],
+ inputs: SourceInputs,
+ ) -> SourceResponse:
+ return sparkpost_source(
+ region=config.region,
+ api_key=config.api_key,
+ endpoint=inputs.schema_name,
+ logger=inputs.logger,
+ resumable_source_manager=resumable_source_manager,
+ should_use_incremental_field=inputs.should_use_incremental_field,
+ db_incremental_field_last_value=inputs.db_incremental_field_last_value
+ if inputs.should_use_incremental_field
+ else None,
)
diff --git a/posthog/temporal/data_imports/sources/sparkpost/sparkpost.py b/posthog/temporal/data_imports/sources/sparkpost/sparkpost.py
new file mode 100644
index 000000000000..9779efa40ff3
--- /dev/null
+++ b/posthog/temporal/data_imports/sources/sparkpost/sparkpost.py
@@ -0,0 +1,267 @@
+import dataclasses
+from collections.abc import Iterator
+from datetime import UTC, date, datetime, timedelta
+from typing import Any, Optional
+from urllib.parse import urlencode, urljoin, urlparse
+
+import requests
+from structlog.types import FilteringBoundLogger
+from tenacity import retry, retry_if_exception_type, stop_after_attempt, wait_exponential_jitter
+
+from posthog.temporal.data_imports.pipelines.pipeline.typings import SourceResponse
+from posthog.temporal.data_imports.sources.common.http import make_tracked_session
+from posthog.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from posthog.temporal.data_imports.sources.sparkpost.settings import SPARKPOST_ENDPOINTS, SparkPostEndpointConfig
+
+# SparkPost runs fully independent US and EU stacks that do not share data; the user picks which one
+# their account lives on. The set is a fixed allow-list, so the host can't be retargeted at an
+# arbitrary server.
+SPARKPOST_HOSTS = {
+ "us": "https://api.sparkpost.com",
+ "eu": "https://api.eu.sparkpost.com",
+}
+DEFAULT_REGION = "us"
+
+REQUEST_TIMEOUT_SECONDS = 60
+
+
+class SparkPostRetryableError(Exception):
+ pass
+
+
+class SparkPostResumeConfig:
+ next_url: str
+
+
+def base_url(region: Optional[str]) -> str:
+ resolved = (region or DEFAULT_REGION).lower()
+ return SPARKPOST_HOSTS.get(resolved, SPARKPOST_HOSTS[DEFAULT_REGION])
+
+
+def _get_headers(api_key: str) -> dict[str, str]:
+ # SparkPost authenticates with the API key passed verbatim in the Authorization header (no
+ # "Bearer" prefix).
+ return {
+ "Authorization": api_key,
+ "Accept": "application/json",
+ }
+
+
+def _format_from(value: Any) -> str:
+ """Format an incremental cursor value for SparkPost's ``from`` filter.
+
+ SparkPost's Events Search API expects ``YYYY-MM-DDTHH:MM`` and treats it as UTC by default. We
+ truncate to the minute (the finest granularity the filter accepts); ``from`` is inclusive, so
+ the boundary event is re-fetched and deduped on ``event_id`` by the merge.
+ """
+ if isinstance(value, datetime):
+ dt = value
+ elif isinstance(value, date):
+ dt = datetime.combine(value, datetime.min.time())
+ elif isinstance(value, str):
+ # The stored watermark can come back as an ISO 8601 string; parse it so we still emit the
+ # ``YYYY-MM-DDTHH:MM`` SparkPost wants rather than passing e.g. ``2026-01-01T00:00:00Z``
+ # through verbatim (which the API rejects). Normalize a trailing ``Z`` for fromisoformat.
+ try:
+ dt = datetime.fromisoformat(value.replace("Z", "+00:00"))
+ except ValueError:
+ return value
+ else:
+ return str(value)
+ dt = dt.replace(tzinfo=UTC) if dt.tzinfo is None else dt.astimezone(UTC)
+ return dt.strftime("%Y-%m-%dT%H:%M")
+
+
+def validate_credentials(region: Optional[str], api_key: str) -> tuple[bool, str | None]:
+ """Validate SparkPost credentials with a single cheap probe against ``/api/v1/account``."""
+ url = f"{base_url(region)}/api/v1/account"
+ try:
+ session = make_tracked_session(redact_values=(api_key,))
+ response = session.get(url, headers=_get_headers(api_key), timeout=10)
+ if response.status_code == 200:
+ return True, None
+ # 403 means the key authenticated but lacks the ``Account`` scope this probe uses. The key
+ # is genuine, and a user who only grants the per-data-type read scopes (as our caption
+ # suggests) shouldn't be blocked from connecting — real per-endpoint scope gaps surface at
+ # sync time via get_non_retryable_errors. Only 401 is a definitively bad key.
+ if response.status_code == 403:
+ return True, None
+ if response.status_code == 401:
+ return False, "Invalid SparkPost API key. Check the API key and selected region, then try again."
+ return False, f"SparkPost credential validation failed (status {response.status_code})."
+ except requests.exceptions.RequestException as e:
+ return False, str(e)
+
+
+def _build_initial_params(
+ config: SparkPostEndpointConfig,
+ should_use_incremental_field: bool,
+ db_incremental_field_last_value: Any,
+) -> dict[str, Any]:
+ params: dict[str, Any] = {}
+
+ if config.pagination == "cursor":
+ # ``cursor=initial`` opts the request into SparkPost's cursor-based pagination; we then walk
+ # the ``rel: next`` links it returns.
+ params["cursor"] = "initial"
+ params["per_page"] = config.per_page
+
+ if config.timestamp_filter_param:
+ # Continue from the stored watermark on incremental runs; otherwise seed the first sync with
+ # the lookback window (bounded by SparkPost's 10-day event retention).
+ if should_use_incremental_field and db_incremental_field_last_value:
+ cutoff: Any = db_incremental_field_last_value
+ elif config.default_lookback_days:
+ cutoff = datetime.now(UTC) - timedelta(days=config.default_lookback_days)
+ else:
+ cutoff = None
+
+ if cutoff is not None:
+ params[config.timestamp_filter_param] = _format_from(cutoff)
+
+ return params
+
+
+def _build_initial_url(host: str, config: SparkPostEndpointConfig, params: dict[str, Any]) -> str:
+ url = f"{host}{config.path}"
+ if not params:
+ return url
+ return f"{url}?{urlencode(params)}"
+
+
+def _extract_items(response_json: Any, config: SparkPostEndpointConfig) -> list[dict[str, Any]]:
+ if isinstance(response_json, dict):
+ items = response_json.get(config.data_path, [])
+ return items if isinstance(items, list) else []
+ return []
+
+
+def _is_same_host(url: str, host: str) -> bool:
+ """True only for ``https`` URLs whose netloc matches the resolved SparkPost API host."""
+ parsed = urlparse(url)
+ return parsed.scheme == "https" and parsed.netloc == urlparse(host).netloc
+
+
+def _compute_next_url(config: SparkPostEndpointConfig, response_json: Any, host: str) -> str | None:
+ if config.pagination != "cursor":
+ return None
+
+ # SparkPost returns pagination links as a list of ``{"href": ..., "rel": ...}`` objects; the
+ # ``next`` href is a path relative to the API host (e.g. ``/api/v1/events/message?cursor=...``).
+ links = response_json.get("links") if isinstance(response_json, dict) else None
+ if not isinstance(links, list):
+ return None
+
+ for link in links:
+ if isinstance(link, dict) and link.get("rel") == "next":
+ href = link.get("href")
+ if not isinstance(href, str) or not href:
+ return None
+ # ``urljoin`` resolves a relative path against the host and leaves an absolute URL as-is.
+ # Either way we re-pin it to the resolved host so a tampered response can't redirect our
+ # authenticated request at an internal address (SSRF) and leak the API key.
+ resolved = urljoin(f"{host}/", href)
+ return resolved if _is_same_host(resolved, host) else None
+ return None
+
+
+def get_rows(
+ region: Optional[str],
+ api_key: str,
+ endpoint: str,
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[SparkPostResumeConfig],
+ should_use_incremental_field: bool = False,
+ db_incremental_field_last_value: Any = None,
+) -> Iterator[list[dict[str, Any]]]:
+ config = SPARKPOST_ENDPOINTS[endpoint]
+ headers = _get_headers(api_key)
+ host = base_url(region)
+ # One tracked session reused across pages and retries; the API key is redacted from logged URLs
+ # and captured samples.
+ session = make_tracked_session(headers=headers, redact_values=(api_key,))
+
+ params = _build_initial_params(config, should_use_incremental_field, db_incremental_field_last_value)
+
+ resume_config = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None
+ if resume_config is not None:
+ url = resume_config.next_url
+ # Guard the persisted resume URL too — only ever saved from _compute_next_url (host-pinned),
+ # but re-check so a tampered Redis state can't redirect our authenticated request.
+ if not _is_same_host(url, host):
+ raise ValueError(f"SparkPost resume state contains an unexpected URL: {url!r}")
+ logger.debug(f"SparkPost: resuming from URL: {url}")
+ else:
+ url = _build_initial_url(host, config, params)
+
+ @retry(
+ retry=retry_if_exception_type((SparkPostRetryableError, requests.ReadTimeout, requests.ConnectionError)),
+ stop=stop_after_attempt(5),
+ wait=wait_exponential_jitter(initial=1, max=30),
+ reraise=True,
+ )
+ def fetch_page(page_url: str) -> Any:
+ response = session.get(page_url, timeout=REQUEST_TIMEOUT_SECONDS)
+
+ # SparkPost applies dynamic rate limiting, returning 429 with guidance to back off 1-5s.
+ if response.status_code == 429 or response.status_code >= 500:
+ raise SparkPostRetryableError(
+ f"SparkPost API error (retryable): status={response.status_code}, url={page_url}"
+ )
+
+ if not response.ok:
+ logger.error(f"SparkPost API error: status={response.status_code}, body={response.text}, url={page_url}")
+ response.raise_for_status()
+
+ return response.json()
+
+ while True:
+ data = fetch_page(url)
+
+ items = _extract_items(data, config)
+ if not items:
+ break
+
+ yield items
+
+ next_url = _compute_next_url(config, data, host)
+ if not next_url:
+ break
+
+ # Save state AFTER yielding the batch — a crash re-yields the last batch (merge dedupes on
+ # primary key) instead of skipping it.
+ resumable_source_manager.save_state(SparkPostResumeConfig(next_url=next_url))
+ url = next_url
+
+
+def sparkpost_source(
+ region: Optional[str],
+ api_key: str,
+ endpoint: str,
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[SparkPostResumeConfig],
+ should_use_incremental_field: bool = False,
+ db_incremental_field_last_value: Optional[Any] = None,
+) -> SourceResponse:
+ config = SPARKPOST_ENDPOINTS[endpoint]
+
+ return SourceResponse(
+ name=endpoint,
+ items=lambda: get_rows(
+ region=region,
+ api_key=api_key,
+ endpoint=endpoint,
+ logger=logger,
+ resumable_source_manager=resumable_source_manager,
+ should_use_incremental_field=should_use_incremental_field,
+ db_incremental_field_last_value=db_incremental_field_last_value,
+ ),
+ primary_keys=config.primary_keys,
+ sort_mode="asc",
+ partition_count=1,
+ partition_size=1,
+ partition_mode="datetime" if config.partition_key else None,
+ partition_format="week" if config.partition_key else None,
+ partition_keys=[config.partition_key] if config.partition_key else None,
+ )
diff --git a/posthog/temporal/data_imports/sources/sparkpost/tests/test_sparkpost.py b/posthog/temporal/data_imports/sources/sparkpost/tests/test_sparkpost.py
new file mode 100644
index 000000000000..e1047afcb35f
--- /dev/null
+++ b/posthog/temporal/data_imports/sources/sparkpost/tests/test_sparkpost.py
@@ -0,0 +1,345 @@
+from datetime import UTC, date, datetime
+from typing import Any
+from urllib.parse import parse_qs, urlparse
+
+import pytest
+from unittest import mock
+
+import requests
+
+from posthog.temporal.data_imports.sources.sparkpost import sparkpost as sp
+from posthog.temporal.data_imports.sources.sparkpost.settings import SPARKPOST_ENDPOINTS
+from posthog.temporal.data_imports.sources.sparkpost.sparkpost import (
+ DEFAULT_REGION,
+ SparkPostResumeConfig,
+ _build_initial_params,
+ _build_initial_url,
+ _compute_next_url,
+ _extract_items,
+ _format_from,
+ base_url,
+ sparkpost_source,
+ validate_credentials,
+)
+
+
+class TestBaseUrl:
+ @pytest.mark.parametrize(
+ ("region", "expected"),
+ [
+ ("us", "https://api.sparkpost.com"),
+ ("eu", "https://api.eu.sparkpost.com"),
+ ("US", "https://api.sparkpost.com"),
+ # Unknown / spoofed regions fall back to the default US host.
+ ("evil", "https://api.sparkpost.com"),
+ (None, "https://api.sparkpost.com"),
+ ],
+ )
+ def test_base_url(self, region: Any, expected: str) -> None:
+ assert base_url(region) == expected
+
+ def test_default_region_is_us(self) -> None:
+ assert DEFAULT_REGION == "us"
+
+
+class TestFormatFrom:
+ @pytest.mark.parametrize(
+ ("value", "expected"),
+ [
+ (datetime(2026, 3, 4, 2, 58, 14, tzinfo=UTC), "2026-03-04T02:58"),
+ # Truncated to the minute; seconds dropped.
+ (datetime(2026, 1, 15, 10, 30, 45, 123456, tzinfo=UTC), "2026-01-15T10:30"),
+ # Naive datetimes are treated as UTC.
+ (datetime(2026, 3, 4, 2, 58, 14), "2026-03-04T02:58"),
+ (date(2026, 3, 4), "2026-03-04T00:00"),
+ # ISO 8601 strings (how the stored watermark can come back) are parsed, not passed
+ # through — SparkPost rejects a raw ``...T00:00:00Z`` value.
+ ("2026-01-01T00:00:00Z", "2026-01-01T00:00"),
+ ("2026-01-15T10:30:45.123456Z", "2026-01-15T10:30"),
+ ("2026-03-04T02:58:14+00:00", "2026-03-04T02:58"),
+ # A genuinely unparseable string still falls through unchanged.
+ ("already-a-string", "already-a-string"),
+ ],
+ )
+ def test_format_from(self, value: Any, expected: str) -> None:
+ assert _format_from(value) == expected
+
+ def test_no_timezone_offset_in_output(self) -> None:
+ assert "+00:00" not in _format_from(datetime(2026, 3, 4, tzinfo=UTC))
+
+
+class TestExtractItems:
+ def test_wrapped_results(self) -> None:
+ config = SPARKPOST_ENDPOINTS["events"]
+ assert _extract_items({"results": [{"event_id": "1"}]}, config) == [{"event_id": "1"}]
+
+ def test_missing_results_returns_empty(self) -> None:
+ config = SPARKPOST_ENDPOINTS["events"]
+ assert _extract_items({"total_count": 0}, config) == []
+
+ def test_non_dict_returns_empty(self) -> None:
+ config = SPARKPOST_ENDPOINTS["events"]
+ assert _extract_items([{"event_id": "1"}], config) == []
+
+ def test_results_not_a_list_returns_empty(self) -> None:
+ config = SPARKPOST_ENDPOINTS["events"]
+ assert _extract_items({"results": {"unexpected": "shape"}}, config) == []
+
+
+class TestBuildInitialParams:
+ def test_cursor_endpoint_seeds_cursor_and_per_page(self) -> None:
+ config = SPARKPOST_ENDPOINTS["events"]
+ params = _build_initial_params(config, should_use_incremental_field=False, db_incremental_field_last_value=None)
+ assert params["cursor"] == "initial"
+ assert params["per_page"] == config.per_page
+
+ def test_non_cursor_endpoint_has_no_pagination_params(self) -> None:
+ config = SPARKPOST_ENDPOINTS["templates"]
+ params = _build_initial_params(config, should_use_incremental_field=False, db_incremental_field_last_value=None)
+ assert "cursor" not in params
+ assert "per_page" not in params
+ assert "from" not in params
+
+ def test_events_incremental_uses_stored_watermark(self) -> None:
+ config = SPARKPOST_ENDPOINTS["events"]
+ params = _build_initial_params(
+ config,
+ should_use_incremental_field=True,
+ db_incremental_field_last_value=datetime(2026, 1, 1, 12, 30, tzinfo=UTC),
+ )
+ assert params["from"] == "2026-01-01T12:30"
+
+ def test_events_first_sync_seeds_lookback_window(self) -> None:
+ # No stored watermark: ``from`` is seeded from the 10-day retention lookback so the first
+ # sync doesn't fall back to SparkPost's default short window.
+ config = SPARKPOST_ENDPOINTS["events"]
+ params = _build_initial_params(config, should_use_incremental_field=True, db_incremental_field_last_value=None)
+ assert "from" in params
+
+ def test_full_refresh_endpoint_never_sends_time_filter(self) -> None:
+ # Even with incremental on, a full-refresh endpoint must not send a ``from`` filter.
+ config = SPARKPOST_ENDPOINTS["suppression_list"]
+ params = _build_initial_params(
+ config,
+ should_use_incremental_field=True,
+ db_incremental_field_last_value=datetime(2026, 1, 1, tzinfo=UTC),
+ )
+ assert "from" not in params
+
+
+class TestBuildInitialUrl:
+ def test_events_url_with_params(self) -> None:
+ config = SPARKPOST_ENDPOINTS["events"]
+ url = _build_initial_url("https://api.sparkpost.com", config, {"cursor": "initial", "per_page": 1000})
+ parsed = urlparse(url)
+ assert parsed.path == "/api/v1/events/message"
+ query = parse_qs(parsed.query)
+ assert query["cursor"] == ["initial"]
+ assert query["per_page"] == ["1000"]
+
+ def test_no_params(self) -> None:
+ config = SPARKPOST_ENDPOINTS["templates"]
+ assert (
+ _build_initial_url("https://api.sparkpost.com", config, {}) == "https://api.sparkpost.com/api/v1/templates"
+ )
+
+
+class TestComputeNextUrl:
+ HOST = "https://api.sparkpost.com"
+
+ def test_cursor_follows_relative_next_href(self) -> None:
+ config = SPARKPOST_ENDPOINTS["events"]
+ nxt = _compute_next_url(
+ config,
+ {"links": [{"href": "/api/v1/events/message?cursor=abc&per_page=1000", "rel": "next"}]},
+ self.HOST,
+ )
+ assert nxt == "https://api.sparkpost.com/api/v1/events/message?cursor=abc&per_page=1000"
+
+ def test_cursor_follows_absolute_next_href(self) -> None:
+ config = SPARKPOST_ENDPOINTS["events"]
+ nxt = _compute_next_url(
+ config,
+ {"links": [{"href": "https://api.sparkpost.com/api/v1/events/message?cursor=abc", "rel": "next"}]},
+ self.HOST,
+ )
+ assert nxt == "https://api.sparkpost.com/api/v1/events/message?cursor=abc"
+
+ def test_cursor_no_next_rel_terminates(self) -> None:
+ config = SPARKPOST_ENDPOINTS["events"]
+ assert (
+ _compute_next_url(
+ config, {"links": [{"href": "/api/v1/events/message?cursor=x", "rel": "previous"}]}, self.HOST
+ )
+ is None
+ )
+
+ def test_cursor_no_links_terminates(self) -> None:
+ config = SPARKPOST_ENDPOINTS["events"]
+ assert _compute_next_url(config, {"total_count": 0}, self.HOST) is None
+
+ def test_non_cursor_endpoint_never_paginates(self) -> None:
+ config = SPARKPOST_ENDPOINTS["templates"]
+ assert (
+ _compute_next_url(config, {"links": [{"href": "/api/v1/templates?page=2", "rel": "next"}]}, self.HOST)
+ is None
+ )
+
+ @pytest.mark.parametrize(
+ "next_href",
+ [
+ "https://evil.example.com/steal", # off-host
+ "http://api.sparkpost.com/api/v1/events/message", # non-https
+ "https://api.sparkpost.com.evil.com/api/v1/events/message", # look-alike host
+ ],
+ )
+ def test_cursor_rejects_offhost_next(self, next_href: str) -> None:
+ config = SPARKPOST_ENDPOINTS["events"]
+ assert _compute_next_url(config, {"links": [{"href": next_href, "rel": "next"}]}, self.HOST) is None
+
+
+class TestValidateCredentials:
+ @pytest.mark.parametrize(
+ ("status_code", "expected_valid"),
+ [
+ (200, True),
+ (401, False),
+ # 403 = genuine key without the Account scope used by the probe; don't block connecting.
+ (403, True),
+ (500, False),
+ ],
+ )
+ @mock.patch("posthog.temporal.data_imports.sources.sparkpost.sparkpost.make_tracked_session")
+ def test_status_mapping(self, mock_session: mock.MagicMock, status_code: int, expected_valid: bool) -> None:
+ response = mock.MagicMock()
+ response.status_code = status_code
+ mock_session.return_value.get.return_value = response
+
+ is_valid, error = validate_credentials("us", "key")
+
+ assert is_valid is expected_valid
+ if expected_valid:
+ assert error is None
+ else:
+ assert error is not None
+
+ @mock.patch("posthog.temporal.data_imports.sources.sparkpost.sparkpost.make_tracked_session")
+ def test_request_exception_is_caught(self, mock_session: mock.MagicMock) -> None:
+ mock_session.return_value.get.side_effect = requests.exceptions.ConnectionError("boom")
+ is_valid, error = validate_credentials("us", "key")
+ assert is_valid is False
+ assert error is not None
+
+
+class TestSparkPostSourceResponse:
+ @pytest.mark.parametrize(
+ ("endpoint", "expected_pk", "expect_partition"),
+ [
+ ("events", ["event_id"], True),
+ ("suppression_list", ["recipient", "type"], True),
+ ("recipient_lists", ["id"], False),
+ ("sending_domains", ["domain"], False),
+ ],
+ )
+ def test_source_response_shape(self, endpoint: str, expected_pk: list[str], expect_partition: bool) -> None:
+ manager = mock.MagicMock()
+ response = sparkpost_source(
+ region="us",
+ api_key="key",
+ endpoint=endpoint,
+ logger=mock.MagicMock(),
+ resumable_source_manager=manager,
+ )
+ assert response.name == endpoint
+ assert response.primary_keys == expected_pk
+ assert response.sort_mode == "asc"
+ if expect_partition:
+ assert response.partition_mode == "datetime"
+ assert response.partition_keys == [SPARKPOST_ENDPOINTS[endpoint].partition_key]
+ else:
+ assert response.partition_mode is None
+ assert response.partition_keys is None
+
+
+class TestGetRowsResume:
+ def _run(
+ self, endpoint: str, pages: list[Any], can_resume: bool, resume_url: str | None
+ ) -> tuple[list[Any], list[str], list[str]]:
+ manager = mock.MagicMock()
+ manager.can_resume.return_value = can_resume
+ manager.load_state.return_value = SparkPostResumeConfig(next_url=resume_url) if resume_url else None
+ saved: list[str] = []
+ manager.save_state.side_effect = lambda state: saved.append(state.next_url)
+
+ fetched_urls: list[str] = []
+
+ def fake_get(url: str, timeout: Any = None) -> Any:
+ fetched_urls.append(url)
+ resp = mock.MagicMock()
+ resp.status_code = 200
+ resp.ok = True
+ resp.json.return_value = pages[len(fetched_urls) - 1]
+ return resp
+
+ with mock.patch.object(sp, "make_tracked_session") as mock_session:
+ mock_session.return_value.get.side_effect = fake_get
+ rows = list(
+ sp.get_rows(
+ region="us",
+ api_key="key",
+ endpoint=endpoint,
+ logger=mock.MagicMock(),
+ resumable_source_manager=manager,
+ )
+ )
+ return rows, saved, fetched_urls
+
+ def test_cursor_pagination_yields_and_saves_state(self) -> None:
+ pages = [
+ {
+ "results": [{"event_id": "1", "timestamp": "2026-01-01T00:00:00.000Z"}],
+ "links": [{"href": "/api/v1/events/message?cursor=p2", "rel": "next"}],
+ },
+ {"results": [{"event_id": "2", "timestamp": "2026-01-01T00:01:00.000Z"}], "links": []},
+ ]
+ rows, saved, fetched = self._run("events", pages, can_resume=False, resume_url=None)
+
+ assert rows[0][0]["event_id"] == "1"
+ assert rows[1][0]["event_id"] == "2"
+ # State saved after the first batch (before fetching page 2), pointing at the next page.
+ assert saved == ["https://api.sparkpost.com/api/v1/events/message?cursor=p2"]
+ assert fetched[1] == "https://api.sparkpost.com/api/v1/events/message?cursor=p2"
+
+ def test_empty_results_terminates_without_saving(self) -> None:
+ pages = [{"results": [], "links": [{"href": "/api/v1/events/message?cursor=p2", "rel": "next"}]}]
+ rows, saved, fetched = self._run("events", pages, can_resume=False, resume_url=None)
+ assert rows == []
+ assert saved == []
+ assert len(fetched) == 1
+
+ def test_non_paginated_endpoint_fetches_once(self) -> None:
+ pages = [{"results": [{"id": "t1"}, {"id": "t2"}]}]
+ rows, saved, fetched = self._run("templates", pages, can_resume=False, resume_url=None)
+ assert rows == [[{"id": "t1"}, {"id": "t2"}]]
+ assert saved == []
+ assert len(fetched) == 1
+
+ def test_resumes_from_saved_url(self) -> None:
+ pages = [{"results": [{"event_id": "9"}], "links": []}]
+ _rows, _saved, fetched = self._run(
+ "events", pages, can_resume=True, resume_url="https://api.sparkpost.com/resume-here"
+ )
+ assert fetched[0] == "https://api.sparkpost.com/resume-here"
+
+ @pytest.mark.parametrize(
+ "resume_url",
+ [
+ "https://evil.example.com/steal",
+ "http://api.sparkpost.com/resume-here",
+ "https://api.sparkpost.com.evil.com/resume-here",
+ ],
+ )
+ def test_tampered_resume_url_is_rejected(self, resume_url: str) -> None:
+ pages = [{"results": [{"event_id": "9"}], "links": []}]
+ with pytest.raises(ValueError, match="unexpected URL"):
+ self._run("events", pages, can_resume=True, resume_url=resume_url)
diff --git a/posthog/temporal/data_imports/sources/sparkpost/tests/test_sparkpost_source.py b/posthog/temporal/data_imports/sources/sparkpost/tests/test_sparkpost_source.py
new file mode 100644
index 000000000000..42cab0e6f94b
--- /dev/null
+++ b/posthog/temporal/data_imports/sources/sparkpost/tests/test_sparkpost_source.py
@@ -0,0 +1,198 @@
+from typing import Any
+
+import pytest
+from unittest import mock
+
+from posthog.schema import ReleaseStatus, SourceFieldInputConfig, SourceFieldInputConfigType, SourceFieldSelectConfig
+
+from posthog.temporal.data_imports.pipelines.pipeline.typings import SourceInputs
+from posthog.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from posthog.temporal.data_imports.sources.generated_configs import SparkPostSourceConfig
+from posthog.temporal.data_imports.sources.sparkpost.settings import ENDPOINTS, LIMITED_RETENTION_ENDPOINTS
+from posthog.temporal.data_imports.sources.sparkpost.source import SparkPostSource
+from posthog.temporal.data_imports.sources.sparkpost.sparkpost import SparkPostResumeConfig
+
+from products.data_warehouse.backend.types import ExternalDataSourceType
+
+INCREMENTAL_ENDPOINTS = {"events"}
+
+
+def _make_inputs(**overrides: Any) -> SourceInputs:
+ defaults: dict[str, Any] = {
+ "schema_name": "events",
+ "schema_id": "schema-1",
+ "source_id": "source-1",
+ "team_id": 123,
+ "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": mock.MagicMock(),
+ "reset_pipeline": False,
+ }
+ defaults.update(overrides)
+ return SourceInputs(**defaults)
+
+
+class TestSparkPostSource:
+ def setup_method(self) -> None:
+ self.source = SparkPostSource()
+ self.team_id = 123
+ self.config = SparkPostSourceConfig(api_key="sp-key", region="us")
+
+ def test_source_type(self) -> None:
+ assert self.source.source_type == ExternalDataSourceType.SPARKPOST
+
+ def test_region_is_a_connection_host_field(self) -> None:
+ # Changing the region must force the API key to be re-entered so it's never sent to a
+ # freshly-specified host.
+ assert self.source.connection_host_fields == ["region"]
+
+ def test_get_source_config(self) -> None:
+ config = self.source.get_source_config
+
+ assert config.name.value == "SparkPost"
+ assert config.label == "SparkPost"
+ # Shipped hidden for now (not yet exercised against a live account).
+ assert config.unreleasedSource is True
+ assert config.releaseStatus == ReleaseStatus.ALPHA
+ assert config.iconPath == "/static/services/sparkpost.png"
+
+ region_field, api_key_field = config.fields
+
+ assert isinstance(region_field, SourceFieldSelectConfig)
+ assert region_field.name == "region"
+ assert region_field.required is True
+ assert region_field.defaultValue == "us"
+ assert {o.value for o in region_field.options} == {"us", "eu"}
+
+ assert isinstance(api_key_field, SourceFieldInputConfig)
+ assert api_key_field.name == "api_key"
+ assert api_key_field.type == SourceFieldInputConfigType.PASSWORD
+ assert api_key_field.required is True
+ assert api_key_field.secret is True
+
+ @pytest.mark.parametrize("expected_key", ["401 Client Error", "403 Client Error"])
+ def test_non_retryable_errors(self, expected_key: str) -> None:
+ assert expected_key in self.source.get_non_retryable_errors()
+
+ def test_get_schemas_returns_all_endpoints(self) -> None:
+ schemas = self.source.get_schemas(self.config, self.team_id)
+ assert {s.name for s in schemas} == set(ENDPOINTS)
+
+ def test_get_schemas_incremental_flags(self) -> None:
+ schemas = {s.name: s for s in self.source.get_schemas(self.config, self.team_id)}
+
+ for name in INCREMENTAL_ENDPOINTS:
+ assert schemas[name].supports_incremental is True
+ assert schemas[name].supports_append is True
+ assert schemas[name].incremental_fields == [
+ {
+ "label": "timestamp",
+ "type": "datetime",
+ "field": "timestamp",
+ "field_type": "datetime",
+ }
+ ]
+
+ for name in set(ENDPOINTS) - INCREMENTAL_ENDPOINTS:
+ assert schemas[name].supports_incremental is False
+ assert schemas[name].supports_append is False
+ assert schemas[name].incremental_fields == []
+
+ def test_get_schemas_retention_description(self) -> None:
+ schemas = {s.name: s for s in self.source.get_schemas(self.config, self.team_id)}
+ for name in LIMITED_RETENTION_ENDPOINTS:
+ assert schemas[name].description is not None
+ assert schemas["templates"].description is None
+
+ def test_get_schemas_filtered_by_names(self) -> None:
+ schemas = self.source.get_schemas(self.config, self.team_id, names=["templates"])
+ assert len(schemas) == 1
+ assert schemas[0].name == "templates"
+
+ def test_get_schemas_unknown_name_returns_empty(self) -> None:
+ assert self.source.get_schemas(self.config, self.team_id, names=["nonexistent"]) == []
+
+ def test_canonical_descriptions_cover_every_endpoint(self) -> None:
+ descriptions = self.source.get_canonical_descriptions()
+ assert set(descriptions.keys()) == set(ENDPOINTS)
+
+ @pytest.mark.parametrize(
+ ("mock_return", "expected_valid", "expected_message"),
+ [
+ ((True, None), True, None),
+ ((False, "Invalid SparkPost API key."), False, "Invalid SparkPost API key."),
+ ],
+ )
+ @mock.patch("posthog.temporal.data_imports.sources.sparkpost.source.validate_sparkpost_credentials")
+ def test_validate_credentials(
+ self,
+ mock_validate: mock.MagicMock,
+ mock_return: tuple[bool, str | None],
+ expected_valid: bool,
+ expected_message: str | None,
+ ) -> None:
+ mock_validate.return_value = mock_return
+
+ is_valid, error_message = self.source.validate_credentials(self.config, self.team_id)
+
+ assert is_valid is expected_valid
+ assert error_message == expected_message
+ mock_validate.assert_called_once_with("us", "sp-key")
+
+ def test_get_resumable_source_manager_bound_to_resume_config(self) -> None:
+ manager = self.source.get_resumable_source_manager(_make_inputs())
+ assert isinstance(manager, ResumableSourceManager)
+ assert manager._data_class is SparkPostResumeConfig
+
+ @mock.patch("posthog.temporal.data_imports.sources.sparkpost.source.sparkpost_source")
+ def test_source_for_pipeline_plumbs_arguments(self, mock_source: mock.MagicMock) -> None:
+ inputs = _make_inputs(schema_name="templates", team_id=99, job_id="job-xyz")
+ manager = mock.MagicMock(spec=ResumableSourceManager)
+
+ self.source.source_for_pipeline(self.config, manager, inputs)
+
+ mock_source.assert_called_once_with(
+ region="us",
+ api_key="sp-key",
+ endpoint="templates",
+ logger=inputs.logger,
+ resumable_source_manager=manager,
+ should_use_incremental_field=False,
+ db_incremental_field_last_value=None,
+ )
+
+ @mock.patch("posthog.temporal.data_imports.sources.sparkpost.source.sparkpost_source")
+ def test_source_for_pipeline_passes_incremental_value_when_enabled(self, mock_source: mock.MagicMock) -> None:
+ inputs = _make_inputs(
+ schema_name="events",
+ should_use_incremental_field=True,
+ db_incremental_field_last_value="2026-01-01T00:00:00Z",
+ incremental_field="timestamp",
+ )
+ manager = mock.MagicMock(spec=ResumableSourceManager)
+
+ self.source.source_for_pipeline(self.config, manager, inputs)
+
+ _, kwargs = mock_source.call_args
+ assert kwargs["should_use_incremental_field"] is True
+ assert kwargs["db_incremental_field_last_value"] == "2026-01-01T00:00:00Z"
+
+ @mock.patch("posthog.temporal.data_imports.sources.sparkpost.source.sparkpost_source")
+ def test_source_for_pipeline_omits_incremental_value_when_disabled(self, mock_source: mock.MagicMock) -> None:
+ # When incremental is off the stored watermark must not leak through as a server-side filter.
+ inputs = _make_inputs(
+ schema_name="events",
+ should_use_incremental_field=False,
+ db_incremental_field_last_value="2026-01-01T00:00:00Z",
+ )
+ manager = mock.MagicMock(spec=ResumableSourceManager)
+
+ self.source.source_for_pipeline(self.config, manager, inputs)
+
+ _, kwargs = mock_source.call_args
+ assert kwargs["should_use_incremental_field"] is False
+ assert kwargs["db_incremental_field_last_value"] is None