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): add 4 missing tables to the SendGrid source (#117384)

Tom Owersf41a8e084f96
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.md b/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.md
index 80bb7e8af97e..eb4cc4f72834 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.md
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.md
@@ -10697,11 +10697,11 @@ Today (10): `blocks`, `bounces`, `global_unsubscribes`, `invalid_emails`, `marke
Diffed against: <https://github.com/twilio/sendgrid-oai/tree/main/spec/json (official Twilio SendGrid OpenAPI specs; read tsg_stats_v3.json, tsg_mc_stats_v3.json, tsg_mc_contacts_v3.json, tsg_mc_singlesends_v3.json, tsg_suppressions_v3.json, tsg_email_activity_v3.json, tsg_subusers_v3.json and others)>
- [x] `GET /v3/stats (global email statistics)` — SendGrid's headline metric — daily requests, delivered, opens, clicks, bounces, spam reports; the whole reason to sync SendGrid (high)
-- [ ] `GET /v3/marketing/stats/singlesends (+ /{id} and /{id}/links)` — Per-campaign send performance including click tracking by link (high)
-- [ ] `GET /v3/marketing/singlesends` — Single Send campaign records — the lookup that resolves the singlesend IDs in the stats endpoints (high)
+- [x] `GET /v3/marketing/stats/singlesends (+ /{id} and /{id}/links)` — Per-campaign send performance including click tracking by link (high)
+- [x] `GET /v3/marketing/singlesends` — Single Send campaign records — the lookup that resolves the singlesend IDs in the stats endpoints (high)
- [x] `GET /v3/messages (Email Activity)` — Per-message event feed (delivered, opened, clicked, bounced) — the row-level fact table behind all aggregate stats (high)
- [ ] `GET /v3/marketing/contacts (+ /contacts/exports)` — Contact records; no recipient dimension exists today so lists and suppressions cannot be joined to people (high)
-- [ ] `GET /v3/asm/groups/{group_id}/suppressions` — Membership rows linking email addresses to the unsubscribe_groups already synced — the join table is missing (high)
+- [x] `GET /v3/asm/groups/{group_id}/suppressions` — Membership rows linking email addresses to the unsubscribe_groups already synced — the join table is missing (high)
- [ ] `GET /v3/categories/stats (and /v3/categories/stats/sums)` — Email stats broken down by category, the main way transactional senders segment performance (medium)
- [ ] `GET /v3/categories` — Category lookup resolving the category tags used on stats and messages (medium)
- [ ] `GET /v3/marketing/stats/automations (+ /{id}/links)` — Automation (journey) performance stats (medium)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/sendgrid/api_inventory.md b/products/warehouse_sources/backend/temporal/data_imports/sources/sendgrid/api_inventory.md
index bec3a2b92c0b..7ef1b0ea7b87 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/sendgrid/api_inventory.md
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/sendgrid/api_inventory.md
@@ -16,18 +16,22 @@ 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` |
-| `stats` | `/stats` | none (single) | nested daily stats | `date` | `date` via `start_date` (YYYY-MM-DD) |
-| `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 |
-| `message_activity` | `/messages` | query window | `{"messages": [...]}` | `msg_id` | `last_event_time` via `query` |
+| 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` |
+| `stats` | `/stats` | none (single) | nested daily stats | `date` | `date` via `start_date` (YYYY-MM-DD) |
+| `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 |
+| `message_activity` | `/messages` | query window | `{"messages": [...]}` | `msg_id` | `last_event_time` via `query` |
+| `unsubscribe_group_suppressions` | `/asm/suppressions` | none (single) | bare array | `group_id`, `email` | full refresh |
+| `singlesends` | `/marketing/singlesends` | `_metadata` | `{"result": [...]}` | `id` | full refresh |
+| `singlesend_stats` | `/marketing/stats/singlesends` | `_metadata` | `{"results": [...]}` | `id`, `ab_variation`, `ab_phase` | full refresh |
+| `singlesend_link_stats` | `/marketing/stats/singlesends/{id}/links` (fan-out over `singlesends`) | `_metadata` | `{"results": [...]}` | `singlesend_id`, `url`, `url_location`, `ab_variation`, `ab_phase` | full refresh |
Notes:
@@ -68,6 +72,20 @@ Notes:
`settings.py` records each endpoint's scope as `/v3/scopes` spells it (`suppression.bounces.read`,
`asm.groups.read`, `marketing.read`, `templates.read`), and `get_endpoint_permissions` probes them so the
schema picker can disable what the key can't reach.
+- `unsubscribe_group_suppressions` reads `/asm/suppressions`, which returns every unsubscribe group
+ membership as `{email, group_id, group_name, created_at}` in one unpaginated response. The per-group
+ `/asm/groups/{group_id}/suppressions` returns only bare email strings, so it would need a fan-out
+ over `/asm/groups` and still lack the creation time. Neither takes a time filter.
+- The Single Send endpoints (`singlesends`, `singlesend_stats`, `singlesend_link_stats`) follow
+ `_metadata.next` like the other marketing endpoints. The stats endpoints cap `page_size` at 50.
+ `singlesend_stats` sends no `singlesend_ids`, so it returns lifetime totals for every Single Send;
+ without `group_by` each row has `ab_variation` and `ab_phase` set to `all`. `singlesend_link_stats`
+ fans out over `singlesends`, and a 404 for a Single Send deleted mid-sync is skipped. No Single Send
+ endpoint takes a time filter, so all three are full refresh. They need `marketing.read` and an
+ account with Marketing Campaigns, like `/marketing/lists`.
+- `/marketing/contacts` is not synced. The GET returns a sample of at most 50 recent contacts. The full
+ set needs an asynchronous export job (`POST /marketing/contacts/exports`, then poll, then download
+ files from S3 links), which creates a job in the customer's account.
- `/marketing/lists` is the outlier: it needs `marketing.read` **and** an account with Marketing Campaigns.
Accounts without it, and accounts still on legacy Marketing Campaigns (a different API, scoped
`marketing_campaigns.read`), return 403 no matter how the key is scoped, so the table can be genuinely
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/sendgrid/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/sendgrid/canonical_descriptions.py
index 9c30c0b9e3b9..6640d3147c8b 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/sendgrid/canonical_descriptions.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/sendgrid/canonical_descriptions.py
@@ -85,6 +85,16 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
"unsubscribes": "Number of unsubscribes recorded against this group.",
},
},
+ "unsubscribe_group_suppressions": {
+ "description": "Membership rows of unsubscribe groups: one row per email address suppressed from a group.",
+ "docs_url": "https://www.twilio.com/docs/sendgrid/api-reference/suppressions-suppressions/retrieve-all-suppressions",
+ "columns": {
+ "email": "The email address that was suppressed.",
+ "group_id": "The id of the unsubscribe group that this email address belongs to.",
+ "group_name": "The name of the unsubscribe group that this email address belongs to.",
+ "created_at": "Time at which the suppression was created, as a Unix timestamp.",
+ },
+ },
"marketing_lists": {
"description": "Marketing contact lists used to segment recipients for campaigns.",
"docs_url": "https://www.twilio.com/docs/sendgrid/api-reference/lists/get-all-lists",
@@ -94,6 +104,44 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
"contact_count": "Number of contacts on the list.",
},
},
+ "singlesends": {
+ "description": "Single Sends: one-time Marketing Campaigns emails sent to lists or segments.",
+ "docs_url": "https://www.twilio.com/docs/sendgrid/api-reference/single-sends/get-all-single-sends",
+ "columns": {
+ "id": "Unique identifier for the Single Send.",
+ "name": "Name of the Single Send.",
+ "status": "Current status of the Single Send: draft, scheduled, or triggered.",
+ "categories": "Categories associated with the Single Send.",
+ "send_at": "Time at which the Single Send is scheduled to send, in ISO 8601 format.",
+ "is_abtest": "Whether the A/B test feature is turned on for the Single Send.",
+ "abtest": "Summary of the A/B test settings of the Single Send.",
+ "created_at": "Time at which the Single Send was created, in ISO 8601 format.",
+ "updated_at": "Time at which the Single Send was last updated, in ISO 8601 format.",
+ },
+ },
+ "singlesend_stats": {
+ "description": "Lifetime engagement statistics for each Single Send, such as requests, deliveries, opens, and clicks.",
+ "docs_url": "https://www.twilio.com/docs/sendgrid/api-reference/marketing-campaign-stats/get-all-single-sends-stats",
+ "columns": {
+ "id": "Unique identifier for the Single Send that the statistics are for.",
+ "ab_variation": "The A/B variation of the statistics, or all when the statistics cover every variation.",
+ "ab_phase": "The A/B phase of the statistics (send, test, or all).",
+ "aggregation": "The time unit that the statistics are rolled up to, total for lifetime totals.",
+ "stats": "The metrics: requests, delivered, opens, unique_opens, clicks, unique_clicks, bounces, bounce_drops, invalid_emails, spam_reports, spam_report_drops, and unsubscribes.",
+ },
+ },
+ "singlesend_link_stats": {
+ "description": "Click counts for each link in each Single Send.",
+ "docs_url": "https://www.twilio.com/docs/sendgrid/api-reference/marketing-campaign-stats/get-single-send-click-tracking-stats-by-id",
+ "columns": {
+ "singlesend_id": "Unique identifier for the Single Send that contains the link.",
+ "url": "The URL of the clicked link, including any custom fields in the URL.",
+ "url_location": "The position of the link in the email, numbered from the top down starting at 0.",
+ "ab_variation": "The A/B variation of the statistics, or all when the statistics cover every variation.",
+ "ab_phase": "The A/B phase of the statistics (send, test, or all).",
+ "clicks": "Number of clicks on this link.",
+ },
+ },
"templates": {
"description": "Email templates (legacy and dynamic) used to compose messages.",
"docs_url": "https://www.twilio.com/docs/sendgrid/api-reference/transactional-templates/retrieve-paged-transactional-templates",
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/sendgrid/sendgrid.py b/products/warehouse_sources/backend/temporal/data_imports/sources/sendgrid/sendgrid.py
index f130e1bb69f4..ebe74ddadd7d 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/sendgrid/sendgrid.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/sendgrid/sendgrid.py
@@ -11,13 +11,19 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common.res
RESTAPIConfig,
rest_api_resource,
)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.fanout import (
+ build_dependent_resource,
+)
from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.paginators import (
BasePaginator,
JSONResponsePaginator,
OffsetPaginator,
SinglePagePaginator,
)
-from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.typing import EndpointResource
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.typing import (
+ ClientConfig,
+ EndpointResource,
+)
from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
from products.warehouse_sources.backend.temporal.data_imports.sources.common.source_helpers import validate_via_probe
from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceResponse
@@ -32,7 +38,7 @@ logger = logging.getLogger(__name__)
SENDGRID_BASE_URL = "https://api.sendgrid.com/v3"
[email protected](frozen=False)
class SendGridResumeConfig:
# Full next-page URL to fetch within the current sync. Set by metadata pagination (the API
# hands us the whole next URL) and by pre-migration saved states (which stored the offset URL
@@ -45,6 +51,9 @@ class SendGridResumeConfig:
# instead of recomputing it from "now" and losing the oldest slice of a first backfill.
activity_window_start: Optional[str] = None
activity_window_end: Optional[str] = None
+ # Fan-out progress in the shape the shared dependent-resource paginator emits
+ # (`{"completed": [...], "current": ..., "child_state": ...}`).
+ fanout_state: Optional[dict[str, Any]] = None
def _get_headers(api_key: str) -> dict[str, str]:
@@ -176,6 +185,13 @@ class SendGridMetadataPaginator(JSONResponsePaginator):
self._next_url = None
self._has_next_page = False
+ def set_resume_state(self, state: dict[str, Any]) -> None:
+ # A fan-out child seeds its page from Redis through this hook, not `_initial_paginator_state`.
+ next_url = state.get("next_url")
+ if next_url is not None:
+ _require_sendgrid_url(next_url)
+ super().set_resume_state(state)
+
class SendGridMessagesPaginator(BasePaginator):
"""Page the Email Activity API by narrowing its query window newest to oldest.
@@ -352,6 +368,76 @@ def _initial_paginator_state(
return None
+def _client_config(api_key: str, paginator: BasePaginator) -> ClientConfig:
+ return {
+ "base_url": SENDGRID_BASE_URL,
+ # Auth (Bearer) goes through the framework auth config so its value is redacted from logs
+ # and raised errors; only the non-secret Accept header is set here.
+ "headers": {"Accept": "application/json"},
+ "auth": {"type": "bearer", "token": api_key},
+ "paginator": paginator,
+ }
+
+
+def _fanout_resource(
+ api_key: str,
+ config: SendGridEndpointConfig,
+ team_id: int,
+ job_id: str,
+ resumable_source_manager: ResumableSourceManager[SendGridResumeConfig],
+) -> Any:
+ assert config.fanout is not None
+ parent_config = SENDGRID_ENDPOINTS[config.fanout.parent_name]
+
+ initial_paginator_state: Optional[dict[str, Any]] = None
+ if resumable_source_manager.can_resume():
+ resume = resumable_source_manager.load_state()
+ if resume is not None and resume.fanout_state:
+ initial_paginator_state = resume.fanout_state
+
+ def save_checkpoint(state: Optional[dict[str, Any]]) -> None:
+ if state is not None:
+ resumable_source_manager.save_state(SendGridResumeConfig(fanout_state=state))
+
+ return build_dependent_resource(
+ endpoint_configs=SENDGRID_ENDPOINTS,
+ child_endpoint=config.name,
+ fanout=config.fanout,
+ client_config=_client_config(api_key, SendGridMetadataPaginator()),
+ path_format_values={},
+ team_id=team_id,
+ job_id=job_id,
+ db_incremental_field_last_value=None,
+ page_size_param="page_size",
+ resume_hook=save_checkpoint,
+ initial_paginator_state=initial_paginator_state,
+ parent_endpoint_extra={
+ "paginator": SendGridMetadataPaginator(),
+ "data_selector": parent_config.data_key,
+ "data_selector_required": True,
+ },
+ child_endpoint_extra={
+ "paginator": SendGridMetadataPaginator(),
+ "data_selector": config.data_key,
+ "data_selector_required": True,
+ },
+ )
+
+
+def _source_response(endpoint: str, config: SendGridEndpointConfig, resource: Any) -> SourceResponse:
+ return SourceResponse(
+ name=endpoint,
+ items=lambda: resource,
+ 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=config.sort_mode,
+ )
+
+
def sendgrid_source(
api_key: str,
endpoint: str,
@@ -364,6 +450,11 @@ def sendgrid_source(
) -> SourceResponse:
config = SENDGRID_ENDPOINTS[endpoint]
+ if config.fanout is not None:
+ return _source_response(
+ endpoint, config, _fanout_resource(api_key, config, team_id, job_id, resumable_source_manager)
+ )
+
params = _build_params(config, should_use_incremental_field, db_incremental_field_last_value, incremental_field)
resource_config: EndpointResource = {
@@ -394,14 +485,7 @@ def sendgrid_source(
)
rest_config: RESTAPIConfig = {
- "client": {
- "base_url": SENDGRID_BASE_URL,
- # Auth (Bearer) goes through the framework auth config so its value is redacted from logs
- # and raised errors; only the non-secret Accept header is set here.
- "headers": {"Accept": "application/json"},
- "auth": {"type": "bearer", "token": api_key},
- "paginator": paginator,
- },
+ "client": _client_config(api_key, paginator),
"resource_defaults": {},
"resources": [resource_config],
}
@@ -434,17 +518,7 @@ def sendgrid_source(
initial_paginator_state=initial_paginator_state,
)
- return SourceResponse(
- name=endpoint,
- items=lambda: resource,
- 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=config.sort_mode,
- )
+ return _source_response(endpoint, config, resource)
def get_status_code(api_key: str, path: str, params: Optional[dict[str, Any]] = None) -> Optional[int]:
@@ -477,7 +551,14 @@ def _probe_params(config: SendGridEndpointConfig) -> dict[str, Any]:
def get_endpoint_status_code(api_key: str, config: SendGridEndpointConfig) -> Optional[int]:
- return get_status_code(api_key, config.path, _probe_params(config))
+ # A fan-out child path needs a parent id, and its parent reads with the same scope, so the
+ # parent listing stands in for it.
+ probe_config = config
+ if config.fanout is not None:
+ probe_config = SENDGRID_ENDPOINTS[config.fanout.parent_name]
+ elif config.probe_endpoint is not None:
+ probe_config = SENDGRID_ENDPOINTS[config.probe_endpoint]
+ return get_status_code(api_key, probe_config.path, _probe_params(probe_config))
def permission_error_for(config: SendGridEndpointConfig) -> str:
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/sendgrid/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/sendgrid/settings.py
index a853871767f7..01394716ccc8 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/sendgrid/settings.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/sendgrid/settings.py
@@ -1,6 +1,9 @@
from dataclasses import dataclass, field
from typing import Literal, Optional
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.fanout import (
+ DependentEndpointConfig,
+)
from products.warehouse_sources.backend.types import IncrementalField, IncrementalFieldType
# How a list endpoint is walked:
@@ -32,7 +35,7 @@ ResponseShape = Literal["array", "daily_stats"]
STATS_DEFAULT_BACKFILL_DAYS = 365
-@dataclass
+@dataclass(frozen=False)
class SendGridEndpointConfig:
name: str
path: str
@@ -70,6 +73,21 @@ class SendGridEndpointConfig:
required_scope: str = ""
# Appended to the missing-scope message where granting the scope may not be enough on its own.
permission_note: Optional[str] = None
+ # Structural requirement of `FanoutEndpointLike` (see common/rest_source/fanout.py); no
+ # fan-out endpoint here syncs incrementally.
+ default_incremental_field: Optional[str] = None
+ # Set on a child endpoint whose path takes one id per row of a parent endpoint.
+ fanout: Optional[DependentEndpointConfig] = None
+ # Endpoint to probe for permissions instead of this one, when this response is too large to
+ # download on every schema-picker load. It must read with the same scope.
+ probe_endpoint: Optional[str] = None
+
+
+# Marketing Campaigns is provisioned per account, and legacy Marketing Campaigns serves a different
+# API entirely, so both deny the `/marketing` endpoints however the key is scoped.
+_MARKETING_CAMPAIGNS_NOTE = (
+ "Accounts without Marketing Campaigns, or on legacy Marketing Campaigns, cannot sync this table."
+)
def _epoch_field(name: str) -> IncrementalField:
@@ -179,6 +197,18 @@ SENDGRID_ENDPOINTS: dict[str, SendGridEndpointConfig] = {
pagination="single",
required_scope="asm.groups.read",
),
+ # Membership rows of every unsubscribe group in one response. This is the same data as a
+ # per-group fan-out over /asm/groups/{group_id}/suppressions, which returns bare email strings
+ # with no creation time.
+ "unsubscribe_group_suppressions": SendGridEndpointConfig(
+ name="unsubscribe_group_suppressions",
+ path="/asm/suppressions",
+ primary_keys=["group_id", "email"],
+ pagination="single",
+ partition_key="created_at",
+ required_scope="asm.groups.read",
+ probe_endpoint="unsubscribe_groups",
+ ),
"marketing_lists": SendGridEndpointConfig(
name="marketing_lists",
path="/marketing/lists",
@@ -187,9 +217,51 @@ SENDGRID_ENDPOINTS: dict[str, SendGridEndpointConfig] = {
data_key="result",
page_size=100,
required_scope="marketing.read",
- # Marketing Campaigns is provisioned per account, and legacy Marketing Campaigns serves a
- # different API entirely, so both deny `/marketing/lists` however the key is scoped.
- permission_note="Accounts without Marketing Campaigns, or on legacy Marketing Campaigns, cannot sync this table.",
+ permission_note=_MARKETING_CAMPAIGNS_NOTE,
+ ),
+ "singlesends": SendGridEndpointConfig(
+ name="singlesends",
+ path="/marketing/singlesends",
+ primary_keys=["id"],
+ pagination="metadata",
+ data_key="result",
+ page_size=100,
+ partition_key="created_at",
+ required_scope="marketing.read",
+ permission_note=_MARKETING_CAMPAIGNS_NOTE,
+ ),
+ "singlesend_stats": SendGridEndpointConfig(
+ name="singlesend_stats",
+ path="/marketing/stats/singlesends",
+ # Without `group_by`, ab_variation and ab_phase are "all", so each single send has one
+ # lifetime-total row. They stay in the key so an A/B breakdown row can never collide.
+ primary_keys=["id", "ab_variation", "ab_phase"],
+ pagination="metadata",
+ data_key="results",
+ # The stats endpoints cap `page_size` at 50.
+ page_size=50,
+ required_scope="marketing.read",
+ permission_note=_MARKETING_CAMPAIGNS_NOTE,
+ ),
+ "singlesend_link_stats": SendGridEndpointConfig(
+ name="singlesend_link_stats",
+ path="/marketing/stats/singlesends/{singlesend_id}/links",
+ primary_keys=["singlesend_id", "url", "url_location", "ab_variation", "ab_phase"],
+ pagination="metadata",
+ data_key="results",
+ page_size=50,
+ required_scope="marketing.read",
+ permission_note=_MARKETING_CAMPAIGNS_NOTE,
+ fanout=DependentEndpointConfig(
+ parent_name="singlesends",
+ resolve_param="singlesend_id",
+ resolve_field="id",
+ include_from_parent=["id"],
+ parent_field_renames={"id": "singlesend_id"},
+ # A single send deleted between the parent listing and its child fetch must not fail
+ # the whole table.
+ child_response_actions=[{"status_code": 404, "action": "ignore"}],
+ ),
),
"templates": SendGridEndpointConfig(
name="templates",
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/sendgrid/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/sendgrid/source.py
index 70b823985ffe..dd975f09708c 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/sendgrid/source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/sendgrid/source.py
@@ -200,9 +200,9 @@ class SendGridSource(ResumableSource[SendGridSourceConfig, SendGridResumeConfig]
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
+- **Suppressions**: bounces, blocks, invalid emails, spam reports, global unsubscribes, unsubscribe groups and their members
- **Stats**: global email statistics (daily requests, delivered, opens, clicks, bounces)
-- **Marketing**: marketing lists. This also needs an account with Marketing Campaigns enabled.
+- **Marketing**: marketing lists, single sends, and single send stats. This also needs an account with Marketing Campaigns enabled.
- **Template Engine**: templates
- **Email Activity**: message activity. This table is off by default and also needs SendGrid's paid additional email activity history add-on.
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/sendgrid/tests/test_sendgrid.py b/products/warehouse_sources/backend/temporal/data_imports/sources/sendgrid/tests/test_sendgrid.py
index 717a0d732374..7918d9f558b2 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/sendgrid/tests/test_sendgrid.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/sendgrid/tests/test_sendgrid.py
@@ -12,6 +12,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common.tes
ScriptedResponse,
SourceDriver,
always,
+ route,
scripted_network,
)
from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.sendgrid import (
@@ -168,16 +169,102 @@ class TestOffHostGuard:
assert len(result.requests) == 1
assert result.saved_states == []
- def test_off_host_resume_url_raises(self) -> None:
+ @pytest.mark.parametrize(
+ ("endpoint", "resume_state"),
+ [
+ ("marketing_lists", SendGridResumeConfig(next_url="http://169.254.169.254/latest/meta-data/")),
+ # The fan-out child seeds its page from the saved child_state, a different path than
+ # the top-level `next_url`, so the host check has to hold there too.
+ (
+ "singlesend_link_stats",
+ SendGridResumeConfig(
+ fanout_state={
+ "completed": [],
+ "current": "/marketing/stats/singlesends/s1/links",
+ "child_state": {"next_url": "http://169.254.169.254/latest/meta-data/"},
+ }
+ ),
+ ),
+ ],
+ )
+ def test_off_host_resume_url_raises(self, endpoint: str, resume_state: SendGridResumeConfig) -> None:
result = _run(
- "marketing_lists",
- [],
- SendGridResumeConfig(next_url="http://169.254.169.254/latest/meta-data/"),
+ endpoint,
+ route({"/marketing/singlesends": [_response({"result": [{"id": "s1"}], "_metadata": {}})]}),
+ resume_state,
)
assert isinstance(result.raised, ValueError)
assert "unexpected URL" in str(result.raised)
- assert result.requests == []
+ assert not any("169.254.169.254" in url for url in result.urls)
+
+
+_SINGLESENDS_PATH = "/marketing/singlesends"
+
+
+def _links_path(singlesend_id: str) -> str:
+ return f"/marketing/stats/singlesends/{singlesend_id}/links"
+
+
+class TestSingleSendLinkStatsFanOut:
+ def test_walks_every_single_send_and_tags_rows_with_its_id(self) -> None:
+ singlesends_next = "https://api.sendgrid.com/v3/marketing/singlesends?page_token=p2&page_size=100"
+ links_next = "https://api.sendgrid.com/v3/marketing/stats/singlesends/s1/links?page_token=l2&page_size=50"
+ link = {"url": "https://example.com/a", "url_location": 0, "ab_variation": "all", "ab_phase": "all"}
+
+ result = _run(
+ "singlesend_link_stats",
+ route(
+ {
+ _SINGLESENDS_PATH: [
+ _response({"result": [{"id": "s1"}, {"id": "gone"}], "_metadata": {"next": singlesends_next}}),
+ _response({"result": [{"id": "s3"}], "_metadata": {}}),
+ ],
+ _links_path("s1"): [
+ _response({"results": [{**link, "clicks": 4}], "_metadata": {"next": links_next}}),
+ _response({"results": [{**link, "url_location": 1, "clicks": 2}], "_metadata": {}}),
+ ],
+ # A single send deleted after the parent listing must not fail the table.
+ _links_path("gone"): [ScriptedResponse(status=404, json={"errors": [{"message": "not found"}]})],
+ _links_path("s3"): [_response({"results": [{**link, "clicks": 9}], "_metadata": {}})],
+ }
+ ),
+ )
+
+ assert result.raised is None
+ # Without the parent id the rows of different single sends collide on the primary key.
+ assert result.rows == [
+ {**link, "clicks": 4, "singlesend_id": "s1"},
+ {**link, "url_location": 1, "clicks": 2, "singlesend_id": "s1"},
+ {**link, "clicks": 9, "singlesend_id": "s3"},
+ ]
+ assert result.urls[2] == links_next
+ assert result.requests[0].param("page_size") == "100"
+ assert result.requests[1].param("page_size") == "50"
+
+ def test_resume_skips_completed_single_sends_and_continues_the_current_one(self) -> None:
+ links_next = "https://api.sendgrid.com/v3/marketing/stats/singlesends/s2/links?page_token=l2&page_size=50"
+
+ result = _run(
+ "singlesend_link_stats",
+ route(
+ {
+ _SINGLESENDS_PATH: [_response({"result": [{"id": "s1"}, {"id": "s2"}], "_metadata": {}})],
+ _links_path("s2"): [_response({"results": [{"url": "https://example.com/b"}], "_metadata": {}})],
+ }
+ ),
+ SendGridResumeConfig(
+ fanout_state={
+ "completed": [_links_path("s1")],
+ "current": _links_path("s2"),
+ "child_state": {"next_url": links_next},
+ }
+ ),
+ )
+
+ assert result.raised is None
+ assert result.urls[1] == links_next
+ assert result.rows == [{"url": "https://example.com/b", "singlesend_id": "s2"}]
def _messages_page(count: int, last_event_time: str) -> list[dict[str, Any]]:
@@ -331,6 +418,21 @@ class TestGetEndpointPermissions:
for fragment in fragments:
assert fragment in reason
+ def test_fanout_endpoint_probes_its_parent_listing(self) -> None:
+ # The child path needs a single send id, so probing it as is would 404 and hide a denial.
+ with scripted_network(always(ScriptedResponse(status=403, json={}))) as network:
+ permissions = get_endpoint_permissions("k", ["singlesend_link_stats"])
+
+ assert network.requests_log[0].path == "/v3/marketing/singlesends"
+ assert permissions["singlesend_link_stats"] is not None
+
+ def test_unbounded_endpoint_probes_a_small_one_with_the_same_scope(self) -> None:
+ with scripted_network(always(ScriptedResponse(status=403, json={}))) as network:
+ permissions = get_endpoint_permissions("k", ["unsubscribe_group_suppressions"])
+
+ assert network.requests_log[0].path == "/v3/asm/groups"
+ assert permissions["unsubscribe_group_suppressions"] is not None
+
def test_unknown_endpoint_is_treated_as_reachable(self) -> None:
assert self._probe(403, ["not_an_endpoint"]) == {"not_an_endpoint": None}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/sendgrid/tests/test_sendgrid_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/sendgrid/tests/test_sendgrid_source.py
index 1825f75ae09b..49cfa58ece30 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/sendgrid/tests/test_sendgrid_source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/sendgrid/tests/test_sendgrid_source.py
@@ -23,6 +23,10 @@ ALL_ENDPOINTS = {
"marketing_lists",
"templates",
"message_activity",
+ "unsubscribe_group_suppressions",
+ "singlesends",
+ "singlesend_stats",
+ "singlesend_link_stats",
}