: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 sendgrid import source (#61591)
Tom Owers8eb70d52afa1
diff --git a/posthog/temporal/data_imports/sources/SOURCES.md b/posthog/temporal/data_imports/sources/SOURCES.mdindex 17a8f5a8cf7d..810ee94bd51d 100644--- a/posthog/temporal/data_imports/sources/SOURCES.md+++ b/posthog/temporal/data_imports/sources/SOURCES.md@@ -103,6 +103,7 @@ the row lists both.| resend | HTTP | requests | ✅ || revenuecat | HTTP + Webhook | requests + `WebhookSourceManager` | ✅ (pull) / ➖ (webhook) || salesforce | HTTP | requests + `rest_source.RESTClient` | ✅ |+| sendgrid | HTTP | requests | ✅ || sentry | HTTP | requests + `rest_source.RESTClient` | ✅ || servicenow | HTTP | requests | ✅ || shopify | HTTP | requests | ✅ |@@ -210,7 +211,6 @@ doesn't conflict with concurrent PRs.- quickbooks- ringcentral- salesloft-- sendgrid- sftp- sharepoint- smartsheetdiff --git a/posthog/temporal/data_imports/sources/generated_configs.py b/posthog/temporal/data_imports/sources/generated_configs.pyindex 5e68fcca5cb8..5a4ec0028ea0 100644--- a/posthog/temporal/data_imports/sources/generated_configs.py+++ b/posthog/temporal/data_imports/sources/generated_configs.py@@ -753,7 +753,7 @@ class SalesforceSourceConfig(config.Config):@config.configclass SendGridSourceConfig(config.Config):- pass+ api_key: str@config.configdiff --git a/posthog/temporal/data_imports/sources/sendgrid/api_inventory.md b/posthog/temporal/data_imports/sources/sendgrid/api_inventory.mdnew file mode 100644index 000000000000..54c4bec2262f--- /dev/null+++ b/posthog/temporal/data_imports/sources/sendgrid/api_inventory.md@@ -0,0 +1,41 @@+# SendGrid (Twilio) — endpoint inventory++SendGrid v3 REST API. Base URL `https://api.sendgrid.com/v3`. Auth: `Authorization: Bearer <API key>`.++Docs: <https://www.twilio.com/docs/sendgrid/api-reference>++## Verification status++Endpoint existence and the 401/403 auth contract were confirmed with `curl` against the live API+(every endpoint below returns `401 {"errors":[{"message":"unauthorized"}]}` without a key). Behaviour+that needs a **valid** key — that `start_time` actually filters server-side, exact response ordering,+and `_metadata.next` shape — was taken from the public docs and the Airbyte/Fivetran SendGrid+connectors; it was **not** re-confirmed with live credentials (none available in this environment). The+conservative failure mode if `start_time` were silently ignored is a full re-fetch that merge-dedupes+on the primary key — wasted API calls, not corrupted data.++## Endpoints++| Schema | Path | Pagination | Data shape | Primary key | Incremental |+| --------------------- | ----------------------------- | ------------- | ------------------- | ----------- | ---------------------------------- |+| `bounces` | `/suppression/bounces` | limit/offset | bare array | `email` | `created` (epoch) via `start_time` |+| `blocks` | `/suppression/blocks` | limit/offset | bare array | `email` | `created` (epoch) via `start_time` |+| `invalid_emails` | `/suppression/invalid_emails` | limit/offset | bare array | `email` | `created` (epoch) via `start_time` |+| `spam_reports` | `/suppression/spam_reports` | limit/offset | bare array | `email` | `created` (epoch) via `start_time` |+| `global_unsubscribes` | `/suppression/unsubscribes` | limit/offset | bare array | `email` | `created` (epoch) via `start_time` |+| `unsubscribe_groups` | `/asm/groups` | none (single) | bare array | `id` | full refresh |+| `marketing_lists` | `/marketing/lists` | `_metadata` | `{"result": [...]}` | `id` | full refresh |+| `templates` | `/templates` | `_metadata` | `{"result": [...]}` | `id` | full refresh |++Notes:++- The suppression endpoints return a bare JSON array of records (`{created, email, reason, status}`,+ shape varies slightly per endpoint) and accept `limit` (max 500), `offset`, `start_time`, `end_time`+ (Unix epoch seconds). `created` is immutable, so it doubles as the datetime partition key.+- The marketing/template endpoints wrap rows in `{"result": [...], "_metadata": {"next": "<absolute url>"}}`+ and paginate by following `_metadata.next`. `/templates` requires `generations=legacy,dynamic` to return+ both template types. Neither exposes a server-side timestamp filter, so both are full-refresh only.+- `/asm/groups` returns the full set of unsubscribe groups in a single response with no pagination params.+- Rate limits: most v3 endpoints are generous, but the Email Activity API (`/messages`, deliberately not+ synced here) is capped at ~6 req/min — webhook ingestion is the recommended path for per-event data and+ is left as a follow-up.diff --git a/posthog/temporal/data_imports/sources/sendgrid/sendgrid.py b/posthog/temporal/data_imports/sources/sendgrid/sendgrid.pynew file mode 100644index 000000000000..192c78d60d36--- /dev/null+++ b/posthog/temporal/data_imports/sources/sendgrid/sendgrid.py@@ -0,0 +1,252 @@+import dataclasses+from collections.abc import Iterator+from datetime import UTC, date, datetime+from typing import Any, Optional+from urllib.parse import parse_qs, urlencode, urlparse++import requests+from structlog.types import FilteringBoundLogger+from tenacity import retry, retry_if_exception_type, stop_after_attempt, wait_exponential_jitter+from urllib3.util.retry import Retry++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.sendgrid.settings import SENDGRID_ENDPOINTS, SendGridEndpointConfig++SENDGRID_BASE_URL = "https://api.sendgrid.com/v3"+REQUEST_TIMEOUT_SECONDS = 60+MAX_RETRIES = 5+++class SendGridRetryableError(Exception):+ pass+++class SendGridResumeConfig:+ # Absolute URL of the next page to fetch within the current sync. Works for both offset+ # pagination (we build the URL with the incremented offset) and metadata pagination (the+ # API hands us the full next URL).+ next_url: str+++def _get_headers(api_key: str) -> dict[str, str]:+ return {+ "Authorization": f"Bearer {api_key}",+ "Accept": "application/json",+ }+++def _to_epoch_seconds(value: Any) -> int:+ """Coerce an incremental cursor value to Unix epoch seconds for the `start_time` filter.++ SendGrid's suppression `created` field is already epoch seconds, but the pipeline may hand+ the cursor back as a datetime/date depending on how it round-tripped through storage.+ """+ if isinstance(value, datetime):+ dt = value.replace(tzinfo=UTC) if value.tzinfo is None else value.astimezone(UTC)+ return int(dt.timestamp())+ if isinstance(value, date):+ return int(datetime.combine(value, datetime.min.time(), tzinfo=UTC).timestamp())+ return int(value)+++def _url(base_url: str, params: dict[str, Any]) -> str:+ return f"{base_url}?{urlencode(params)}" if params else base_url+++def _offset_from_url(url: str) -> int:+ """Recover the `offset` query param so a resumed offset-paginated sync keeps advancing."""+ values = parse_qs(urlparse(url).query).get("offset", ["0"])+ try:+ return int(values[0])+ except (ValueError, IndexError):+ return 0+++def _build_base_params(+ config: SendGridEndpointConfig,+ should_use_incremental_field: bool,+ db_incremental_field_last_value: Any,+ incremental_field: Optional[str],+) -> dict[str, Any]:+ params: dict[str, Any] = dict(config.extra_params)++ if (+ should_use_incremental_field+ and config.incremental_param+ and incremental_field+ and db_incremental_field_last_value is not None+ ):+ # start_time is inclusive (created >= start_time); the boundary row re-appears but+ # merge dedupes it on the primary key.+ params[config.incremental_param] = _to_epoch_seconds(db_incremental_field_last_value)++ return params+++def _select_items(config: SendGridEndpointConfig, data: Any) -> list[dict[str, Any]]:+ # Fail loudly on an API-shape change rather than silently syncing zero rows.+ if config.data_key is None:+ if not isinstance(data, list):+ raise ValueError(f"SendGrid {config.name}: expected a list response, got {type(data).__name__}")+ return data+ return data[config.data_key]+++def _next_url(+ config: SendGridEndpointConfig,+ base_url: str,+ base_params: dict[str, Any],+ offset: int,+ data: Any,+ logger: FilteringBoundLogger,+) -> Optional[str]:+ if config.pagination == "offset":+ return _url(base_url, {**base_params, "limit": config.page_size, "offset": offset + config.page_size})+ if config.pagination == "metadata":+ metadata = data.get("_metadata") if isinstance(data, dict) else None+ next_url = metadata.get("next") if isinstance(metadata, dict) else None+ if next_url is None:+ return None+ # Only follow pagination URLs that stay on the canonical SendGrid host, so a tampered or+ # compromised API response can't point our authenticated request at an internal address+ # (SSRF) and leak the API key carried in the Authorization header.+ if not isinstance(next_url, str) or not next_url.startswith(SENDGRID_BASE_URL):+ logger.warning(f"SendGrid: ignoring off-host pagination URL: {next_url!r}")+ return None+ return next_url+ return None+++def get_rows(+ api_key: str,+ endpoint: str,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[SendGridResumeConfig],+ should_use_incremental_field: bool = False,+ db_incremental_field_last_value: Any = None,+ incremental_field: Optional[str] = None,+) -> Iterator[list[dict[str, Any]]]:+ config = SENDGRID_ENDPOINTS[endpoint]+ base_url = f"{SENDGRID_BASE_URL}{config.path}"+ base_params = _build_base_params(+ config, should_use_incremental_field, db_incremental_field_last_value, incremental_field+ )++ 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 a host-pinned next URL, but+ # re-check so a tampered Redis state can't redirect our authenticated request (SSRF).+ if not url.startswith(SENDGRID_BASE_URL):+ raise ValueError(f"SendGrid resume state contains an unexpected URL: {url!r}")+ offset = _offset_from_url(url)+ logger.debug(f"SendGrid: resuming {endpoint} from URL {url}")+ else:+ offset = 0+ if config.pagination == "offset":+ url = _url(base_url, {**base_params, "limit": config.page_size, "offset": offset})+ elif config.pagination == "metadata":+ url = _url(base_url, {**base_params, "page_size": config.page_size})+ else:+ url = _url(base_url, base_params)++ # One session reused across all pages (connection reuse). `tenacity` below is the sole retry+ # mechanism, so disable urllib3's built-in retries to avoid nested backoff. `redact_values`+ # masks the bearer token in logs and sample capture.+ session = make_tracked_session(headers=_get_headers(api_key), retry=Retry(total=0), redact_values=(api_key,))++ @retry(+ retry=retry_if_exception_type((SendGridRetryableError, requests.ReadTimeout, requests.ConnectionError)),+ stop=stop_after_attempt(MAX_RETRIES),+ wait=wait_exponential_jitter(initial=1, max=60),+ reraise=True,+ )+ def fetch_page(page_url: str) -> Any:+ response = session.get(page_url, timeout=REQUEST_TIMEOUT_SECONDS)++ if response.status_code == 429 or response.status_code >= 500:+ raise SendGridRetryableError(+ f"SendGrid API error (retryable): status={response.status_code}, url={page_url}"+ )++ if not response.ok:+ logger.error(f"SendGrid API error: status={response.status_code}, body={response.text}, url={page_url}")+ response.raise_for_status()++ return response.json()++ try:+ while True:+ data = fetch_page(url)+ items = _select_items(config, data)++ if items:+ yield items++ # Offset pagination terminates once a short page comes back.+ if config.pagination == "offset" and len(items) < config.page_size:+ break++ next_url = _next_url(config, base_url, base_params, offset, data, logger)+ if not next_url:+ break++ # Save AFTER yielding so a crash re-yields the last page (merge dedupes on the primary+ # key) rather than skipping it.+ resumable_source_manager.save_state(SendGridResumeConfig(next_url=next_url))+ if config.pagination == "offset":+ offset += config.page_size+ url = next_url+ finally:+ session.close()+++def sendgrid_source(+ api_key: str,+ endpoint: str,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[SendGridResumeConfig],+ should_use_incremental_field: bool = False,+ db_incremental_field_last_value: Optional[Any] = None,+ incremental_field: Optional[str] = None,+) -> SourceResponse:+ config = SENDGRID_ENDPOINTS[endpoint]++ return SourceResponse(+ name=endpoint,+ items=lambda: get_rows(+ 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,+ incremental_field=incremental_field,+ ),+ primary_keys=config.primary_keys,+ 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,+ sort_mode="asc",+ )+++def get_status_code(api_key: str, path: str) -> Optional[int]:+ """Probe an endpoint to classify the credentials. Returns the HTTP status, or None on a+ transport error."""+ try:+ session = make_tracked_session(headers=_get_headers(api_key), redact_values=(api_key,))+ except Exception:+ return None+ try:+ response = session.get(f"{SENDGRID_BASE_URL}{path}", params={"limit": 1}, timeout=10)+ return response.status_code+ except Exception:+ return None+ finally:+ session.close()diff --git a/posthog/temporal/data_imports/sources/sendgrid/settings.py b/posthog/temporal/data_imports/sources/sendgrid/settings.pynew file mode 100644index 000000000000..8912d2be97e0--- /dev/null+++ b/posthog/temporal/data_imports/sources/sendgrid/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++# How a list endpoint is walked:+# - "offset": `limit`/`offset` query params over a bare JSON array (suppression endpoints).+# - "metadata": follow the absolute `_metadata.next` URL the API returns (marketing endpoints).+# - "single": one request returns the whole list, no pagination params.+PaginationMode = Literal["offset", "metadata", "single"]+++@dataclass+class SendGridEndpointConfig:+ name: str+ path: str+ primary_keys: list[str]+ pagination: PaginationMode+ # Key wrapping the array in the JSON response (e.g. {"result": [...]}). None when the+ # response body is the array itself (the suppression endpoints).+ data_key: Optional[str] = None+ # Stable creation field used for datetime partitioning. Never use a "modified" field here.+ partition_key: Optional[str] = None+ page_size: int = 500+ incremental_fields: list[IncrementalField] = field(default_factory=list)+ # Server-side query param that filters by the incremental field (Unix epoch seconds).+ incremental_param: Optional[str] = None+ # Static query params always sent (e.g. templates' `generations`).+ extra_params: dict[str, str] = field(default_factory=dict)+++def _epoch_field(name: str) -> IncrementalField:+ return {+ "label": name,+ "type": IncrementalFieldType.Integer,+ "field": name,+ "field_type": IncrementalFieldType.Integer,+ }+++# SendGrid (v3) endpoint catalog. The suppression endpoints expose a genuine server-side+# `start_time` filter (Unix epoch seconds) over their immutable `created` field, so they sync+# incrementally. Marketing/asm metadata endpoints offer no timestamp filter and ship as full+# refresh. See api_inventory.md for the per-endpoint research notes.+SENDGRID_ENDPOINTS: dict[str, SendGridEndpointConfig] = {+ "bounces": SendGridEndpointConfig(+ name="bounces",+ path="/suppression/bounces",+ primary_keys=["email"],+ pagination="offset",+ partition_key="created",+ incremental_fields=[_epoch_field("created")],+ incremental_param="start_time",+ ),+ "blocks": SendGridEndpointConfig(+ name="blocks",+ path="/suppression/blocks",+ primary_keys=["email"],+ pagination="offset",+ partition_key="created",+ incremental_fields=[_epoch_field("created")],+ incremental_param="start_time",+ ),+ "invalid_emails": SendGridEndpointConfig(+ name="invalid_emails",+ path="/suppression/invalid_emails",+ primary_keys=["email"],+ pagination="offset",+ partition_key="created",+ incremental_fields=[_epoch_field("created")],+ incremental_param="start_time",+ ),+ "spam_reports": SendGridEndpointConfig(+ name="spam_reports",+ path="/suppression/spam_reports",+ primary_keys=["email"],+ pagination="offset",+ partition_key="created",+ incremental_fields=[_epoch_field("created")],+ incremental_param="start_time",+ ),+ "global_unsubscribes": SendGridEndpointConfig(+ name="global_unsubscribes",+ path="/suppression/unsubscribes",+ primary_keys=["email"],+ pagination="offset",+ partition_key="created",+ incremental_fields=[_epoch_field("created")],+ incremental_param="start_time",+ ),+ "unsubscribe_groups": SendGridEndpointConfig(+ name="unsubscribe_groups",+ path="/asm/groups",+ primary_keys=["id"],+ pagination="single",+ ),+ "marketing_lists": SendGridEndpointConfig(+ name="marketing_lists",+ path="/marketing/lists",+ primary_keys=["id"],+ pagination="metadata",+ data_key="result",+ page_size=100,+ ),+ "templates": SendGridEndpointConfig(+ name="templates",+ path="/templates",+ primary_keys=["id"],+ pagination="metadata",+ data_key="result",+ page_size=100,+ extra_params={"generations": "legacy,dynamic"},+ ),+}++ENDPOINTS = tuple(SENDGRID_ENDPOINTS.keys())++INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {+ name: config.incremental_fields for name, config in SENDGRID_ENDPOINTS.items() if config.incremental_fields+}diff --git a/posthog/temporal/data_imports/sources/sendgrid/source.py b/posthog/temporal/data_imports/sources/sendgrid/source.pyindex 37fe77a9bd53..af7adb5e7dc7 100644--- a/posthog/temporal/data_imports/sources/sendgrid/source.py+++ b/posthog/temporal/data_imports/sources/sendgrid/source.py@@ -1,29 +1,138 @@-from typing import cast+from typing import Optional, castfrom posthog.schema import (ExternalDataSourceType as SchemaExternalDataSourceType,+ ReleaseStatus,SourceConfig,+ SourceFieldInputConfig,+ SourceFieldInputConfigType,)-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, ResumableSourcefrom 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 SourceSchemafrom posthog.temporal.data_imports.sources.generated_configs import SendGridSourceConfig+from posthog.temporal.data_imports.sources.sendgrid.sendgrid import (+ SendGridResumeConfig,+ get_status_code,+ sendgrid_source,+)+from posthog.temporal.data_imports.sources.sendgrid.settings import ENDPOINTS, INCREMENTAL_FIELDS, SENDGRID_ENDPOINTSfrom products.data_warehouse.backend.types import ExternalDataSourceType@SourceRegistry.register-class SendGridSource(SimpleSource[SendGridSourceConfig]):+class SendGridSource(ResumableSource[SendGridSourceConfig, SendGridResumeConfig]):@propertydef source_type(self) -> ExternalDataSourceType:return ExternalDataSourceType.SENDGRID+ def get_non_retryable_errors(self) -> dict[str, str | None]:+ return {+ "401 Client Error: Unauthorized for url: https://api.sendgrid.com": "Your SendGrid API key is invalid or expired. Please generate a new key and reconnect.",+ "403 Client Error: Forbidden for url: https://api.sendgrid.com": "Your SendGrid API key is missing a scope required to sync this data. Please grant the required read scopes and reconnect.",+ }++ def get_schemas(+ self,+ config: SendGridSourceConfig,+ team_id: int,+ with_counts: bool = False,+ names: list[str] | None = None,+ force_refresh: bool = False,+ ) -> list[SourceSchema]:+ schemas = [+ SourceSchema(+ name=endpoint,+ supports_incremental=INCREMENTAL_FIELDS.get(endpoint, None) is not None,+ supports_append=INCREMENTAL_FIELDS.get(endpoint, None) is not None,+ incremental_fields=INCREMENTAL_FIELDS.get(endpoint, []),+ )+ for endpoint in list(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: SendGridSourceConfig, team_id: int, schema_name: Optional[str] = None+ ) -> tuple[bool, str | None]:+ # `/scopes` is readable by any genuine key, so it's the cheapest probe at source-create.+ # For a specific schema we probe its own endpoint to confirm the key has that read scope.+ path = SENDGRID_ENDPOINTS[schema_name].path if schema_name in SENDGRID_ENDPOINTS else "/scopes"+ status = get_status_code(config.api_key, path)++ if status == 200:+ return True, None++ if status == 403:+ # Valid token, missing scope. Accept at source-create (users may grant scopes only for+ # the endpoints they want); reject when validating a specific schema.+ if schema_name is None:+ return True, None+ return False, "Your SendGrid API key is missing the scope required to sync this data."++ if status == 401:+ return False, "Invalid SendGrid API key"++ return False, "Could not validate SendGrid API key"++ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[SendGridResumeConfig]:+ return ResumableSourceManager[SendGridResumeConfig](inputs, SendGridResumeConfig)++ def source_for_pipeline(+ self,+ config: SendGridSourceConfig,+ resumable_source_manager: ResumableSourceManager[SendGridResumeConfig],+ inputs: SourceInputs,+ ) -> SourceResponse:+ return sendgrid_source(+ 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,+ incremental_field=inputs.incremental_field,+ )+@propertydef get_source_config(self) -> SourceConfig:return SourceConfig(name=SchemaExternalDataSourceType.SEND_GRID,label="SendGrid",- iconPath="/static/services/sendgrid.png",- fields=cast(list[FieldType], []),+ releaseStatus=ReleaseStatus.ALPHA,unreleasedSource=True,+ caption="""Enter your SendGrid API key to pull your SendGrid data into the PostHog Data warehouse.++You can create an API key in your [SendGrid account settings](https://app.sendgrid.com/settings/api_keys).++Grant the following read access (Restricted Access) so the key can reach the data you want to sync:+- **Suppressions** — bounces, blocks, invalid emails, spam reports, global unsubscribes, unsubscribe groups+- **Marketing** — marketing lists+- **Template Engine** — templates+""",+ iconPath="/static/services/sendgrid.png",+ docsUrl="https://posthog.com/docs/cdp/sources/sendgrid",+ fields=cast(+ list[FieldType],+ [+ SourceFieldInputConfig(+ name="api_key",+ label="API key",+ type=SourceFieldInputConfigType.PASSWORD,+ required=True,+ placeholder="SG....",+ secret=True,+ ),+ ],+ ),)diff --git a/posthog/temporal/data_imports/sources/sendgrid/tests/test_sendgrid.py b/posthog/temporal/data_imports/sources/sendgrid/tests/test_sendgrid.pynew file mode 100644index 000000000000..74d0e164ea14--- /dev/null+++ b/posthog/temporal/data_imports/sources/sendgrid/tests/test_sendgrid.py@@ -0,0 +1,274 @@+from datetime import UTC, date, datetime+from typing import Any+from urllib.parse import parse_qs, urlparse++import pytest+from unittest.mock import MagicMock, patch++from posthog.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from posthog.temporal.data_imports.sources.sendgrid.sendgrid import (+ SendGridResumeConfig,+ _build_base_params,+ _offset_from_url,+ _select_items,+ _to_epoch_seconds,+ get_rows,+ get_status_code,+ sendgrid_source,+)+from posthog.temporal.data_imports.sources.sendgrid.settings import SENDGRID_ENDPOINTS++MODULE = "posthog.temporal.data_imports.sources.sendgrid.sendgrid"+++class _FakeResponse:+ def __init__(self, status_code: int, body: Any) -> None:+ self.status_code = status_code+ self._body = body+ self.text = str(body)++ @property+ def ok(self) -> bool:+ return self.status_code < 400++ def json(self) -> Any:+ return self._body++ def raise_for_status(self) -> None:+ if not self.ok:+ raise AssertionError(f"HTTP {self.status_code}")+++def _session_returning(*responses: _FakeResponse) -> MagicMock:+ session = MagicMock()+ session.get.side_effect = list(responses)+ return session+++def _manager(can_resume: bool = False, resume_state: SendGridResumeConfig | None = None) -> MagicMock:+ manager = MagicMock(spec=ResumableSourceManager)+ manager.can_resume.return_value = can_resume+ manager.load_state.return_value = resume_state+ return manager+++class TestToEpochSeconds:+ @pytest.mark.parametrize(+ ("value", "expected"),+ [+ (1700000000, 1700000000),+ ("1700000000", 1700000000),+ (datetime(2023, 11, 14, 22, 13, 20, tzinfo=UTC), 1700000000),+ (date(1970, 1, 2), 86400),+ ],+ )+ def test_to_epoch_seconds(self, value: Any, expected: int) -> None:+ assert _to_epoch_seconds(value) == expected++ def test_naive_datetime_treated_as_utc(self) -> None:+ assert _to_epoch_seconds(datetime(2023, 11, 14, 22, 13, 20)) == 1700000000+++class TestBuildBaseParams:+ def test_incremental_sets_start_time(self) -> None:+ params = _build_base_params(+ SENDGRID_ENDPOINTS["bounces"],+ should_use_incremental_field=True,+ db_incremental_field_last_value=1700000000,+ incremental_field="created",+ )+ assert params == {"start_time": 1700000000}++ def test_no_start_time_without_incremental(self) -> None:+ params = _build_base_params(+ SENDGRID_ENDPOINTS["bounces"],+ should_use_incremental_field=False,+ db_incremental_field_last_value=1700000000,+ incremental_field="created",+ )+ assert params == {}++ def test_full_refresh_endpoint_keeps_extra_params(self) -> None:+ params = _build_base_params(+ SENDGRID_ENDPOINTS["templates"],+ should_use_incremental_field=True,+ db_incremental_field_last_value=1700000000,+ incremental_field="created",+ )+ # templates has no incremental_param, so the cursor is ignored but static params remain.+ assert params == {"generations": "legacy,dynamic"}+++class TestSelectItems:+ def test_bare_array(self) -> None:+ config = SENDGRID_ENDPOINTS["bounces"]+ assert _select_items(config, [{"email": "[email protected]"}]) == [{"email": "[email protected]"}]++ def test_result_key(self) -> None:+ config = SENDGRID_ENDPOINTS["marketing_lists"]+ assert _select_items(config, {"result": [{"id": 1}], "_metadata": {}}) == [{"id": 1}]++ def test_bare_array_raises_on_shape_change(self) -> None:+ with pytest.raises(ValueError):+ _select_items(SENDGRID_ENDPOINTS["bounces"], {"unexpected": "dict"})++ def test_result_key_raises_on_missing_key(self) -> None:+ with pytest.raises(KeyError):+ _select_items(SENDGRID_ENDPOINTS["marketing_lists"], {"_metadata": {}})+++class TestOffsetFromUrl:+ @pytest.mark.parametrize(+ ("url", "expected"),+ [+ ("https://api.sendgrid.com/v3/suppression/bounces?limit=500&offset=500", 500),+ ("https://api.sendgrid.com/v3/suppression/bounces?limit=500", 0),+ ("https://api.sendgrid.com/v3/suppression/bounces", 0),+ ],+ )+ def test_offset_from_url(self, url: str, expected: int) -> None:+ assert _offset_from_url(url) == expected+++class TestGetRowsOffsetPagination:+ def test_paginates_until_short_page_and_saves_state(self) -> None:+ page_size = SENDGRID_ENDPOINTS["bounces"].page_size+ page1 = [{"email": f"a{i}@x.com", "created": i} for i in range(page_size)]+ page2 = [{"email": "[email protected]", "created": 1}]+ session = _session_returning(_FakeResponse(200, page1), _FakeResponse(200, page2))+ manager = _manager()++ with patch(f"{MODULE}.make_tracked_session", return_value=session):+ batches = list(get_rows("k", "bounces", MagicMock(), manager))++ assert batches == [page1, page2]+ # State saved once (after the full first page); not after the terminal short page.+ assert manager.save_state.call_count == 1+ saved_url = manager.save_state.call_args[0][0].next_url+ assert _offset_from_url(saved_url) == page_size+ session.close.assert_called_once()++ def test_resumes_from_saved_url(self) -> None:+ resume_url = "https://api.sendgrid.com/v3/suppression/bounces?limit=500&offset=500"+ session = _session_returning(_FakeResponse(200, [{"email": "[email protected]", "created": 1}]))+ manager = _manager(can_resume=True, resume_state=SendGridResumeConfig(next_url=resume_url))++ with patch(f"{MODULE}.make_tracked_session", return_value=session):+ batches = list(get_rows("k", "bounces", MagicMock(), manager))++ assert len(batches) == 1+ assert session.get.call_args_list[0][0][0] == resume_url++ def test_incremental_start_time_in_initial_url(self) -> None:+ session = _session_returning(_FakeResponse(200, [{"email": "[email protected]", "created": 1}]))+ with patch(f"{MODULE}.make_tracked_session", return_value=session):+ list(+ get_rows(+ "k",+ "bounces",+ MagicMock(),+ _manager(),+ should_use_incremental_field=True,+ db_incremental_field_last_value=1700000000,+ incremental_field="created",+ )+ )++ query = parse_qs(urlparse(session.get.call_args_list[0][0][0]).query)+ assert query["start_time"] == ["1700000000"]+ assert query["offset"] == ["0"]+++class TestGetRowsMetadataPagination:+ def test_follows_metadata_next(self) -> None:+ next_url = "https://api.sendgrid.com/v3/marketing/lists?page_token=tok&page_size=100"+ page1 = {"result": [{"id": 1}], "_metadata": {"next": next_url}}+ page2 = {"result": [{"id": 2}], "_metadata": {}}+ session = _session_returning(_FakeResponse(200, page1), _FakeResponse(200, page2))+ manager = _manager()++ with patch(f"{MODULE}.make_tracked_session", return_value=session):+ batches = list(get_rows("k", "marketing_lists", MagicMock(), manager))++ assert batches == [[{"id": 1}], [{"id": 2}]]+ assert session.get.call_args_list[1][0][0] == next_url+ assert manager.save_state.call_args[0][0].next_url == next_url+++class TestGetRowsOffHostGuard:+ @pytest.mark.parametrize(+ "off_host_url",+ [+ "http://169.254.169.254/latest/meta-data/",+ "https://evil.example.com/v3/marketing/lists",+ "https://api.sendgrid.com.evil.com/v3/marketing/lists",+ ],+ )+ def test_off_host_metadata_next_is_ignored(self, off_host_url: str) -> None:+ page1 = {"result": [{"id": 1}], "_metadata": {"next": off_host_url}}+ session = _session_returning(_FakeResponse(200, page1))+ manager = _manager()++ with patch(f"{MODULE}.make_tracked_session", return_value=session):+ batches = list(get_rows("k", "marketing_lists", MagicMock(), manager))++ # The tampered next URL is dropped: we yield the first page and stop without following it.+ assert batches == [[{"id": 1}]]+ assert session.get.call_count == 1+ manager.save_state.assert_not_called()++ def test_off_host_resume_url_raises(self) -> None:+ manager = _manager(+ can_resume=True,+ resume_state=SendGridResumeConfig(next_url="http://169.254.169.254/latest/meta-data/"),+ )+ session = _session_returning()++ with patch(f"{MODULE}.make_tracked_session", return_value=session):+ with pytest.raises(ValueError, match="unexpected URL"):+ list(get_rows("k", "marketing_lists", MagicMock(), manager))+++class TestGetRowsSingle:+ def test_single_request_no_pagination(self) -> None:+ groups = [{"id": 1}, {"id": 2}]+ session = _session_returning(_FakeResponse(200, groups))+ manager = _manager()++ with patch(f"{MODULE}.make_tracked_session", return_value=session):+ batches = list(get_rows("k", "unsubscribe_groups", MagicMock(), manager))++ assert batches == [groups]+ assert session.get.call_count == 1+ manager.save_state.assert_not_called()+++class TestSendGridSourceResponse:+ def test_suppression_endpoint_partitioning_and_keys(self) -> None:+ response = sendgrid_source("k", "bounces", MagicMock(), _manager())+ assert response.name == "bounces"+ assert response.primary_keys == ["email"]+ assert response.partition_mode == "datetime"+ assert response.partition_keys == ["created"]+ assert response.sort_mode == "asc"++ def test_full_refresh_endpoint_has_no_partitioning(self) -> None:+ response = sendgrid_source("k", "marketing_lists", MagicMock(), _manager())+ assert response.primary_keys == ["id"]+ assert response.partition_mode is None+ assert response.partition_keys is None+++class TestGetStatusCode:+ @pytest.mark.parametrize("status", [200, 401, 403, 404])+ def test_returns_status(self, status: int) -> None:+ session = MagicMock()+ session.get.return_value = _FakeResponse(status, {})+ with patch(f"{MODULE}.make_tracked_session", return_value=session):+ assert get_status_code("k", "/scopes") == status++ def test_returns_none_on_transport_error(self) -> None:+ session = MagicMock()+ session.get.side_effect = Exception("boom")+ with patch(f"{MODULE}.make_tracked_session", return_value=session):+ assert get_status_code("k", "/scopes") is Nonediff --git a/posthog/temporal/data_imports/sources/sendgrid/tests/test_sendgrid_source.py b/posthog/temporal/data_imports/sources/sendgrid/tests/test_sendgrid_source.pynew file mode 100644index 000000000000..2ba6fbfd5335--- /dev/null+++ b/posthog/temporal/data_imports/sources/sendgrid/tests/test_sendgrid_source.py@@ -0,0 +1,152 @@+from typing import Any++import pytest+from unittest.mock import MagicMock, patch++from posthog.schema import SourceFieldInputConfig, SourceFieldInputConfigType++from posthog.temporal.data_imports.pipelines.pipeline.typings import SourceInputs, SourceResponse+from posthog.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from posthog.temporal.data_imports.sources.generated_configs import SendGridSourceConfig+from posthog.temporal.data_imports.sources.sendgrid.sendgrid import SendGridResumeConfig+from posthog.temporal.data_imports.sources.sendgrid.source import SendGridSource++from products.data_warehouse.backend.types import ExternalDataSourceType++ALL_ENDPOINTS = {+ "bounces",+ "blocks",+ "invalid_emails",+ "spam_reports",+ "global_unsubscribes",+ "unsubscribe_groups",+ "marketing_lists",+ "templates",+}+INCREMENTAL_ENDPOINTS = {"bounces", "blocks", "invalid_emails", "spam_reports", "global_unsubscribes"}+++def _config() -> SendGridSourceConfig:+ return SendGridSourceConfig(api_key="SG.test-key")+++def _source_inputs(schema_name: str = "bounces", **overrides: Any) -> SourceInputs:+ defaults: dict[str, Any] = {+ "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,+ }+ defaults.update(overrides)+ return SourceInputs(**defaults)+++class TestSendGridSource:+ def test_source_type(self) -> None:+ assert SendGridSource().source_type == ExternalDataSourceType.SENDGRID++ def test_source_config_basics(self) -> None:+ config = SendGridSource().get_source_config+ assert config.label == "SendGrid"+ assert config.releaseStatus == "alpha"+ assert config.unreleasedSource is True+ assert config.iconPath == "/static/services/sendgrid.png"++ def test_source_config_has_api_key_password_field(self) -> None:+ fields = SendGridSource().get_source_config.fields+ assert len(fields) == 1+ field = fields[0]+ assert isinstance(field, SourceFieldInputConfig)+ assert field.name == "api_key"+ assert field.type == SourceFieldInputConfigType.PASSWORD+ assert field.required is True+ assert field.secret is True++ def test_get_schemas_returns_all_endpoints(self) -> None:+ schemas = SendGridSource().get_schemas(_config(), team_id=1)+ assert {s.name for s in schemas} == ALL_ENDPOINTS++ def test_only_suppression_endpoints_support_incremental(self) -> None:+ schemas = {s.name: s for s in SendGridSource().get_schemas(_config(), team_id=1)}+ for name in INCREMENTAL_ENDPOINTS:+ assert schemas[name].supports_incremental is True+ assert {f["field"] for f in schemas[name].incremental_fields} == {"created"}+ for name in ALL_ENDPOINTS - INCREMENTAL_ENDPOINTS:+ assert schemas[name].supports_incremental is False+ assert schemas[name].incremental_fields == []++ def test_get_schemas_filters_by_names(self) -> None:+ schemas = SendGridSource().get_schemas(_config(), team_id=1, names=["bounces", "templates"])+ assert {s.name for s in schemas} == {"bounces", "templates"}++ @pytest.mark.parametrize(+ ("status", "schema_name", "expected_ok", "expected_has_msg"),+ [+ (200, None, True, False),+ (200, "bounces", True, False),+ (401, None, False, True),+ (401, "bounces", False, True),+ # 403 = valid token, missing scope: accepted at source-create, rejected per-schema.+ (403, None, True, False),+ (403, "bounces", False, True),+ (None, None, False, True),+ ],+ )+ def test_validate_credentials(+ self, status: int | None, schema_name: str | None, expected_ok: bool, expected_has_msg: bool+ ) -> None:+ with patch("posthog.temporal.data_imports.sources.sendgrid.source.get_status_code", return_value=status):+ ok, msg = SendGridSource().validate_credentials(_config(), team_id=1, schema_name=schema_name)+ assert ok is expected_ok+ assert (msg is not None) is expected_has_msg++ def test_get_resumable_source_manager_is_bound_to_resume_config(self) -> None:+ manager = SendGridSource().get_resumable_source_manager(_source_inputs())+ assert isinstance(manager, ResumableSourceManager)+ assert manager._data_class is SendGridResumeConfig++ def test_get_non_retryable_errors_covers_auth(self) -> None:+ errors = SendGridSource().get_non_retryable_errors()+ assert any("401" in key for key in errors)+ assert any("403" in key for key in errors)++ def test_source_for_pipeline_plumbs_arguments(self) -> None:+ manager = MagicMock(spec=ResumableSourceManager)+ inputs = _source_inputs(+ schema_name="bounces",+ should_use_incremental_field=True,+ db_incremental_field_last_value=1700000000,+ incremental_field="created",+ )+ with patch("posthog.temporal.data_imports.sources.sendgrid.source.sendgrid_source") as mock_source:+ mock_source.return_value = MagicMock(spec=SourceResponse)+ SendGridSource().source_for_pipeline(_config(), manager, inputs)++ _, kwargs = mock_source.call_args+ assert kwargs["api_key"] == "SG.test-key"+ assert kwargs["endpoint"] == "bounces"+ assert kwargs["should_use_incremental_field"] is True+ assert kwargs["db_incremental_field_last_value"] == 1700000000+ assert kwargs["incremental_field"] == "created"++ def test_source_for_pipeline_drops_cursor_when_not_incremental(self) -> None:+ manager = MagicMock(spec=ResumableSourceManager)+ inputs = _source_inputs(+ schema_name="bounces",+ should_use_incremental_field=False,+ db_incremental_field_last_value=1700000000,+ )+ with patch("posthog.temporal.data_imports.sources.sendgrid.source.sendgrid_source") as mock_source:+ mock_source.return_value = MagicMock(spec=SourceResponse)+ SendGridSource().source_for_pipeline(_config(), manager, inputs)++ _, kwargs = mock_source.call_args+ assert kwargs["db_incremental_field_last_value"] is None