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 apple_search_ads source (#73758)

Tom Owers68621bddfa8c
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
index 78f18e79cf1f..3a2684b5a6b9 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
@@ -77,6 +77,7 @@ the row lists both.
| appdynamics | HTTP | requests | ✅ |
| appfigures | HTTP | requests | ✅ |
| appfollow | HTTP | requests | ✅ |
+| apple_search_ads | HTTP | requests | ✅ |
| applovin | HTTP | requests | ✅ |
| appsflyer | HTTP (CSV reports) | requests | ✅ |
| appsignal | HTTP (REST + GraphQL) | requests | ✅ |
@@ -842,7 +843,6 @@ doesn't conflict with concurrent PRs.
- appcues
- appdirect
- appfolio
-- apple_search_ads
- apptivo
- appwrite
- arxiv
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/apple_search_ads/apple_search_ads.py b/products/warehouse_sources/backend/temporal/data_imports/sources/apple_search_ads/apple_search_ads.py
new file mode 100644
index 000000000000..97dd0a5fcb22
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/apple_search_ads/apple_search_ads.py
@@ -0,0 +1,612 @@
+import time
+import itertools
+import dataclasses
+from collections.abc import Callable, Iterator
+from datetime import UTC, date, datetime, timedelta
+from typing import Any, Optional
+
+import jwt
+import requests
+import structlog
+from structlog.types import FilteringBoundLogger
+from urllib3.util.retry import Retry
+
+from posthog.dataclasses import frozen
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.apple_search_ads.settings import (
+ APPLE_SEARCH_ADS_ENDPOINTS,
+ DEFAULT_INITIAL_LOOKBACK_DAYS,
+ MAX_INITIAL_LOOKBACK_DAYS,
+ PAGE_SIZE,
+ REPORT_WINDOW_DAYS,
+ AppleSearchAdsEndpointConfig,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.http import make_tracked_session
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceResponse
+
+APPLE_SEARCH_ADS_HOST = "https://api.searchads.apple.com"
+# Apple Search Ads authenticates through Apple ID's OAuth token endpoint, not a Search Ads host.
+APPLE_OAUTH_TOKEN_URL = "https://appleid.apple.com/auth/oauth2/token"
+APPLE_OAUTH_AUDIENCE = "https://appleid.apple.com"
+APPLE_OAUTH_SCOPE = "searchadsorg"
+
+# Lifetime of the ES256 client-secret assertion we sign per token exchange. Apple allows up to
+# 180 days; we mint a fresh short-lived one every time so no long-lived secret is stored.
+CLIENT_SECRET_TTL_SECONDS = 30 * 60
+REQUEST_TIMEOUT_SECONDS = 120
+
+# Cheap org-scoped probe for credential validation: it exercises the access token *and* the
+# `X-AP-Context` org id, which `/acls` would not.
+CREDENTIAL_PROBE_PATH = "/campaigns"
+
+# Apple's documented ceiling is 100 requests/minute per account, surfaced as 429 with
+# `Retry-After`. The transport honors that header; POST is added to the retryable methods
+# because every read path here except `/campaigns` and `/acls` is a side-effect-free POST
+# (`/find`, `/reports/...`) that urllib3 would otherwise refuse to retry.
+APPLE_SEARCH_ADS_RETRY = Retry(
+ total=5,
+ backoff_factor=1.0,
+ status_forcelist=(429, 500, 502, 503, 504),
+ allowed_methods=frozenset(["GET", "HEAD", "OPTIONS", "POST"]),
+ respect_retry_after_header=True,
+ raise_on_status=False,
+)
+
+logger = structlog.get_logger(__name__)
+
+
+class AppleSearchAdsAuthError(Exception):
+ pass
+
+
[email protected](frozen=True)
+class AppleSearchAdsCredentials:
+ org_id: str
+ client_id: str
+ team_id: str
+ key_id: str
+ # repr=False: keep the PEM out of tracebacks, logs, and pytest assertion diffs.
+ private_key: str = dataclasses.field(repr=False)
+
+
[email protected](frozen=True)
+class AppleSearchAdsResumeConfig:
+ # Offset into the current page set. Entity endpoints only ever use this field.
+ offset: int = 0
+ # ISO date of the reporting window in progress, and the campaign it was being fanned out
+ # to. Both are matched by value on resume, so a changed campaign list restarts the run's
+ # window range rather than silently skipping a campaign.
+ window_start: Optional[str] = None
+ campaign_id: Optional[int] = None
+
+
+def _normalize_private_key(private_key: str) -> str:
+ """Accept a PEM pasted with literal ``\\n`` escapes as well as real newlines."""
+ return private_key.replace("\\n", "\n").strip()
+
+
+def build_client_secret(credentials: AppleSearchAdsCredentials, *, issued_at: Optional[int] = None) -> str:
+ """Sign the ES256 client-secret assertion Apple's token endpoint expects.
+
+ Apple Search Ads has no static client secret: the caller signs a JWT with the private key
+ whose public half was uploaded in the Search Ads UI (`kid` = key id, `iss` = team id,
+ `sub` = client id) and presents that as `client_secret`.
+ """
+ now = int(issued_at if issued_at is not None else time.time())
+ try:
+ return jwt.encode(
+ {
+ "sub": credentials.client_id,
+ "aud": APPLE_OAUTH_AUDIENCE,
+ "iat": now,
+ "exp": now + CLIENT_SECRET_TTL_SECONDS,
+ "iss": credentials.team_id,
+ },
+ _normalize_private_key(credentials.private_key),
+ algorithm="ES256",
+ headers={"alg": "ES256", "kid": credentials.key_id},
+ )
+ except (jwt.PyJWTError, ValueError, TypeError) as e:
+ raise AppleSearchAdsAuthError(
+ "Could not sign the Apple Search Ads client secret. The private key must be the "
+ f"unencrypted EC (P-256) PEM generated for your Search Ads API key: {e}"
+ ) from e
+
+
+class AppleSearchAdsClient:
+ """Minimal Campaign Management API client: token minting plus JSON request helpers."""
+
+ def __init__(
+ self,
+ credentials: AppleSearchAdsCredentials,
+ api_version: str,
+ request_logger: Optional[FilteringBoundLogger] = None,
+ ) -> None:
+ self._credentials = credentials
+ self._base_url = f"{APPLE_SEARCH_ADS_HOST}/api/{api_version}"
+ self._logger: FilteringBoundLogger = request_logger or logger
+ self._access_token: Optional[str] = None
+ self._session = make_tracked_session(
+ retry=APPLE_SEARCH_ADS_RETRY,
+ redact_values=(credentials.private_key,),
+ )
+ # The token exchange body carries the signed assertion and the response the bearer
+ # token, neither of which the name-based sample scrubbers would recognise.
+ self._token_session = make_tracked_session(
+ retry=APPLE_SEARCH_ADS_RETRY,
+ redact_values=(credentials.private_key,),
+ capture=False,
+ )
+
+ @property
+ def base_url(self) -> str:
+ return self._base_url
+
+ def authenticate(self) -> str:
+ self._access_token = self._mint_access_token()
+ return self._access_token
+
+ def _mint_access_token(self) -> str:
+ client_secret = build_client_secret(self._credentials)
+ response = self._token_session.post(
+ APPLE_OAUTH_TOKEN_URL,
+ data={
+ "grant_type": "client_credentials",
+ "client_id": self._credentials.client_id,
+ "client_secret": client_secret,
+ "scope": APPLE_OAUTH_SCOPE,
+ },
+ headers={"Content-Type": "application/x-www-form-urlencoded"},
+ timeout=REQUEST_TIMEOUT_SECONDS,
+ )
+ if not response.ok:
+ self._logger.error(
+ f"Apple Search Ads token exchange failed: status={response.status_code}, url={APPLE_OAUTH_TOKEN_URL}"
+ )
+ response.raise_for_status()
+
+ access_token = response.json().get("access_token")
+ if not access_token:
+ raise AppleSearchAdsAuthError("Apple's token response did not contain an access token")
+ return str(access_token)
+
+ def _headers(self, requires_org_context: bool) -> dict[str, str]:
+ headers = {"Authorization": f"Bearer {self._access_token}", "Accept": "application/json"}
+ if requires_org_context:
+ headers["X-AP-Context"] = f"orgId={self._credentials.org_id}"
+ return headers
+
+ def _send(
+ self,
+ method: str,
+ url: str,
+ *,
+ params: Optional[dict[str, Any]],
+ body: Optional[dict[str, Any]],
+ requires_org_context: bool,
+ ) -> requests.Response:
+ headers = self._headers(requires_org_context)
+ if method == "POST":
+ return self._session.post(url, json=body or {}, headers=headers, timeout=REQUEST_TIMEOUT_SECONDS)
+ return self._session.get(url, params=params, headers=headers, timeout=REQUEST_TIMEOUT_SECONDS)
+
+ def _request(
+ self,
+ method: str,
+ path: str,
+ *,
+ params: Optional[dict[str, Any]] = None,
+ body: Optional[dict[str, Any]] = None,
+ requires_org_context: bool = True,
+ ) -> requests.Response:
+ if self._access_token is None:
+ self.authenticate()
+
+ url = f"{self._base_url}{path}"
+ response = self._send(method, url, params=params, body=body, requires_org_context=requires_org_context)
+ # Access tokens live an hour, which a backfill routinely outlives — re-mint once and
+ # replay before treating a 401 as a credential problem.
+ if response.status_code == 401:
+ self.authenticate()
+ response = self._send(method, url, params=params, body=body, requires_org_context=requires_org_context)
+ return response
+
+ def request_json(
+ self,
+ method: str,
+ path: str,
+ *,
+ params: Optional[dict[str, Any]] = None,
+ body: Optional[dict[str, Any]] = None,
+ requires_org_context: bool = True,
+ ) -> dict[str, Any]:
+ response = self._request(method, path, params=params, body=body, requires_org_context=requires_org_context)
+ if not response.ok:
+ self._logger.error(
+ f"Apple Search Ads API error: status={response.status_code}, "
+ f"body={response.text}, url={self._base_url}{path}"
+ )
+ response.raise_for_status()
+
+ payload = response.json()
+ return payload if isinstance(payload, dict) else {}
+
+ def probe_status(self, path: str, *, params: Optional[dict[str, Any]] = None) -> int:
+ return self._request("GET", path, params=params).status_code
+
+
+def validate_credentials(
+ credentials: AppleSearchAdsCredentials,
+ api_version: str,
+ schema_name: Optional[str] = None,
+) -> tuple[bool, str | None]:
+ """Mint a token and probe one org-scoped endpoint.
+
+ A 403 means the credentials are genuine but the role can't read this resource; accepted at
+ source-create (``schema_name is None``) so a user who only granted a subset of access can
+ still connect, and reported per-table otherwise.
+ """
+ client = AppleSearchAdsClient(credentials, api_version)
+ try:
+ client.authenticate()
+ except AppleSearchAdsAuthError as e:
+ return False, str(e)
+ except requests.RequestException as e:
+ return False, f"Could not exchange the Apple Search Ads credentials for an access token: {e}"
+
+ try:
+ status = client.probe_status(CREDENTIAL_PROBE_PATH, params={"limit": 1})
+ except requests.RequestException as e:
+ return False, f"Could not reach the Apple Search Ads API: {e}"
+
+ if status == 200:
+ return True, None
+ if status == 401:
+ return False, "Apple Search Ads rejected the access token. Check the client ID, team ID and key ID."
+ if status == 403:
+ if schema_name is None:
+ return True, None
+ return False, "These Apple Search Ads credentials do not have permission to read this table."
+ return False, f"Apple Search Ads returned an unexpected status code: {status}"
+
+
+def _today() -> date:
+ return datetime.now(UTC).date()
+
+
+def _to_date(value: Any) -> Optional[date]:
+ """Coerce an incremental cursor value (date/datetime/ISO string) to a plain date."""
+ if value is None:
+ return None
+ if isinstance(value, datetime):
+ return value.astimezone(UTC).date() if value.tzinfo is not None else value.date()
+ if isinstance(value, date):
+ return value
+ try:
+ return datetime.fromisoformat(str(value).replace("Z", "+00:00")).date()
+ except ValueError:
+ return None
+
+
+def _report_start_date(
+ should_use_incremental_field: bool,
+ db_incremental_field_last_value: Any,
+ start_date: Optional[str],
+ today: date,
+) -> date:
+ """First reporting day to request.
+
+ The pipeline already shifts the stored watermark back by the schema's lookback, so it is
+ used verbatim. Without a watermark the run starts at the user's configured start date, or
+ a bounded default so a first sync can't walk the whole account history.
+ """
+ if should_use_incremental_field:
+ watermark = _to_date(db_incremental_field_last_value)
+ if watermark is not None:
+ return watermark
+
+ configured = _to_date(start_date) if start_date else None
+ if configured is not None:
+ # Floor the configured date so an implausibly old start can't fan the report out over
+ # thousands of empty windows and exhaust the import worker.
+ return max(configured, today - timedelta(days=MAX_INITIAL_LOOKBACK_DAYS))
+ return today - timedelta(days=DEFAULT_INITIAL_LOOKBACK_DAYS)
+
+
+@frozen
+class ReportWindow:
+ start: date
+ end: date
+
+
+def _report_windows(start: date, end: date) -> list[ReportWindow]:
+ """Split ``start..end`` (inclusive) into ascending windows of at most one week."""
+ windows: list[ReportWindow] = []
+ window_start = start
+ while window_start <= end:
+ window_end = min(window_start + timedelta(days=REPORT_WINDOW_DAYS - 1), end)
+ windows.append(ReportWindow(start=window_start, end=window_end))
+ window_start = window_end + timedelta(days=1)
+ return windows
+
+
+def _report_body(window_start: date, window_end: date, offset: int) -> dict[str, Any]:
+ return {
+ "startTime": window_start.isoformat(),
+ "endTime": window_end.isoformat(),
+ "granularity": "DAILY",
+ # Report in the organization's own time zone so the `date` column matches what the
+ # Search Ads UI shows for the same campaign.
+ "timeZone": "ORTZ",
+ "selector": {
+ "conditions": [],
+ # No `orderBy`: Apple's sortable-field enum differs per report level and rejects
+ # unknown fields, and rows are keyed by entity + date so merge order is irrelevant.
+ "pagination": {"offset": offset, "limit": PAGE_SIZE},
+ },
+ "returnRecordsWithNoMetrics": False,
+ "returnRowTotals": False,
+ "returnGrandTotals": False,
+ }
+
+
+def _report_page_rows(payload: dict[str, Any]) -> list[dict[str, Any]]:
+ reporting_data = payload.get("data") or {}
+ if not isinstance(reporting_data, dict):
+ return []
+ response = reporting_data.get("reportingDataResponse") or {}
+ if not isinstance(response, dict):
+ return []
+ rows = response.get("row") or []
+ return [row for row in rows if isinstance(row, dict)]
+
+
+def flatten_report_rows(payload: dict[str, Any], campaign_id: Optional[int]) -> list[dict[str, Any]]:
+ """Explode one report page into a row per entity per day.
+
+ Apple returns one row per entity carrying a `metadata` block plus a `granularity` array of
+ daily metric buckets; the warehouse wants those flattened so `date` is a real column.
+ """
+ flattened: list[dict[str, Any]] = []
+ for row in _report_page_rows(payload):
+ metadata = dict(row.get("metadata") or {})
+ if campaign_id is not None:
+ # Ad-group and keyword reports are requested per campaign and their metadata does
+ # not repeat the campaign id the primary key needs.
+ metadata.setdefault("campaignId", campaign_id)
+ for daily in row.get("granularity") or []:
+ if isinstance(daily, dict):
+ flattened.append({**metadata, **daily})
+ return flattened
+
+
+def _entity_page(
+ client: AppleSearchAdsClient, config: AppleSearchAdsEndpointConfig, offset: int
+) -> list[dict[str, Any]]:
+ if config.kind == "find":
+ payload = client.request_json(
+ "POST",
+ config.path,
+ body={"conditions": [], "pagination": {"offset": offset, "limit": PAGE_SIZE}},
+ requires_org_context=config.requires_org_context,
+ )
+ elif config.kind == "query_page":
+ payload = client.request_json(
+ "GET",
+ config.path,
+ params={"limit": PAGE_SIZE, "offset": offset},
+ requires_org_context=config.requires_org_context,
+ )
+ else:
+ payload = client.request_json("GET", config.path, requires_org_context=config.requires_org_context)
+
+ rows = payload.get("data")
+ return [row for row in rows if isinstance(row, dict)] if isinstance(rows, list) else []
+
+
+def _iter_entity_rows(
+ client: AppleSearchAdsClient,
+ config: AppleSearchAdsEndpointConfig,
+ resumable_source_manager: ResumableSourceManager[AppleSearchAdsResumeConfig],
+ resume: Optional[AppleSearchAdsResumeConfig],
+) -> Iterator[list[dict[str, Any]]]:
+ offset = resume.offset if resume is not None else 0
+
+ while True:
+ rows = _entity_page(client, config, offset)
+ if rows:
+ yield rows
+
+ if config.kind == "single" or len(rows) < PAGE_SIZE:
+ break
+
+ offset += len(rows)
+ resumable_source_manager.save_state(AppleSearchAdsResumeConfig(offset=offset))
+
+
+def _list_campaign_ids(client: AppleSearchAdsClient) -> list[int]:
+ """Campaign ids to fan the per-campaign report endpoints out over, in a stable order."""
+ campaigns_config = APPLE_SEARCH_ADS_ENDPOINTS["campaigns"]
+ ids: set[int] = set()
+ offset = 0
+ while True:
+ rows = _entity_page(client, campaigns_config, offset)
+ for row in rows:
+ campaign_id = row.get("id")
+ if campaign_id is not None:
+ ids.add(int(campaign_id))
+ if len(rows) < PAGE_SIZE:
+ break
+ offset += len(rows)
+ return sorted(ids)
+
+
+ReportTask = tuple[date, date, Optional[int]]
+
+
+def _report_tasks(start: date, end: date, campaign_ids: list[Optional[int]]) -> Iterator[ReportTask]:
+ """Every (window, campaign) report request this run must make, lazily.
+
+ Yielded rather than listed so a large window range never materialises as millions of
+ tuples up front.
+ """
+ for window in _report_windows(start, end):
+ for campaign_id in campaign_ids:
+ yield window.start, window.end, campaign_id
+
+
+def _advance_to_resume(
+ make_tasks: Callable[[], Iterator[ReportTask]],
+ resume: Optional[AppleSearchAdsResumeConfig],
+ request_logger: FilteringBoundLogger,
+) -> tuple[Iterator[ReportTask], int]:
+ """Fast-forward the lazy task stream to a saved checkpoint, matched by value not position.
+
+ A checkpoint from a different window range (e.g. the start date changed) is never found, so
+ the run restarts from the first task with a fresh stream.
+ """
+ if resume is None or not resume.window_start:
+ return make_tasks(), 0
+
+ key = (resume.window_start, resume.campaign_id)
+ tasks = make_tasks()
+ for task in tasks:
+ window_start, _window_end, campaign_id = task
+ if (window_start.isoformat(), campaign_id) == key:
+ return itertools.chain([task], tasks), resume.offset
+
+ request_logger.debug(
+ f"Apple Search Ads: saved checkpoint {key} is not in this run's window range, starting from the beginning"
+ )
+ return make_tasks(), 0
+
+
+def _iter_report_rows(
+ client: AppleSearchAdsClient,
+ config: AppleSearchAdsEndpointConfig,
+ resumable_source_manager: ResumableSourceManager[AppleSearchAdsResumeConfig],
+ resume: Optional[AppleSearchAdsResumeConfig],
+ request_logger: FilteringBoundLogger,
+ *,
+ should_use_incremental_field: bool,
+ db_incremental_field_last_value: Any,
+ start_date: Optional[str],
+) -> Iterator[list[dict[str, Any]]]:
+ today = _today()
+ start = _report_start_date(should_use_incremental_field, db_incremental_field_last_value, start_date, today)
+ campaign_ids: list[Optional[int]] = [None]
+ if config.fan_out_over_campaigns:
+ campaign_ids = list(_list_campaign_ids(client))
+
+ tasks, start_offset = _advance_to_resume(lambda: _report_tasks(start, today, campaign_ids), resume, request_logger)
+
+ current = next(tasks, None)
+ resume_offset = start_offset
+ while current is not None:
+ window_start, window_end, campaign_id = current
+ # Peek at the next task so a completed window can checkpoint where the run should pick up.
+ upcoming = next(tasks, None)
+ path = config.path.format(campaign_id=campaign_id) if campaign_id is not None else config.path
+ offset = resume_offset
+ resume_offset = 0
+
+ while True:
+ payload = client.request_json(
+ "POST",
+ path,
+ body=_report_body(window_start, window_end, offset),
+ requires_org_context=config.requires_org_context,
+ )
+ rows = flatten_report_rows(payload, campaign_id)
+ if rows:
+ yield rows
+
+ page_size = len(_report_page_rows(payload))
+ if page_size < PAGE_SIZE:
+ break
+
+ offset += page_size
+ resumable_source_manager.save_state(
+ AppleSearchAdsResumeConfig(
+ offset=offset, window_start=window_start.isoformat(), campaign_id=campaign_id
+ )
+ )
+
+ if upcoming is not None:
+ next_window_start, _next_window_end, next_campaign_id = upcoming
+ resumable_source_manager.save_state(
+ AppleSearchAdsResumeConfig(
+ offset=0, window_start=next_window_start.isoformat(), campaign_id=next_campaign_id
+ )
+ )
+ current = upcoming
+
+
+def get_rows(
+ credentials: AppleSearchAdsCredentials,
+ endpoint: str,
+ api_version: str,
+ request_logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[AppleSearchAdsResumeConfig],
+ should_use_incremental_field: bool = False,
+ db_incremental_field_last_value: Any = None,
+ start_date: Optional[str] = None,
+) -> Iterator[list[dict[str, Any]]]:
+ config = APPLE_SEARCH_ADS_ENDPOINTS[endpoint]
+ client = AppleSearchAdsClient(credentials, api_version, request_logger)
+ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None
+
+ if config.kind == "report":
+ yield from _iter_report_rows(
+ client,
+ config,
+ resumable_source_manager,
+ resume,
+ request_logger,
+ should_use_incremental_field=should_use_incremental_field,
+ db_incremental_field_last_value=db_incremental_field_last_value,
+ start_date=start_date,
+ )
+ else:
+ yield from _iter_entity_rows(client, config, resumable_source_manager, resume)
+
+ # The stream ran to completion; leaving the last checkpoint would make a later attempt
+ # resume mid-range instead of restarting cleanly.
+ resumable_source_manager.clear_state()
+
+
+def apple_search_ads_source(
+ credentials: AppleSearchAdsCredentials,
+ endpoint: str,
+ api_version: str,
+ request_logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[AppleSearchAdsResumeConfig],
+ should_use_incremental_field: bool = False,
+ db_incremental_field_last_value: Any = None,
+ start_date: Optional[str] = None,
+) -> SourceResponse:
+ config = APPLE_SEARCH_ADS_ENDPOINTS[endpoint]
+
+ return SourceResponse(
+ name=endpoint,
+ items=lambda: get_rows(
+ credentials=credentials,
+ endpoint=endpoint,
+ api_version=api_version,
+ request_logger=request_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,
+ start_date=start_date,
+ ),
+ primary_keys=list(config.primary_keys),
+ # Reporting windows are walked oldest-first, so `date` only ever moves forward across
+ # batches by at most one window — which the schema's trailing lookback re-reads.
+ sort_mode="asc",
+ partition_count=1,
+ partition_size=1,
+ partition_mode="datetime" if config.partition_key else None,
+ partition_format="month" if config.partition_key else None,
+ partition_keys=[config.partition_key] if config.partition_key else None,
+ )
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/apple_search_ads/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/apple_search_ads/canonical_descriptions.py
new file mode 100644
index 000000000000..77e1b4b22940
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/apple_search_ads/canonical_descriptions.py
@@ -0,0 +1,150 @@
+"""Canonical, documentation-sourced descriptions for Apple Search Ads endpoints and columns.
+
+Sourced from Apple's Search Ads Campaign Management API v5 reference
+(https://developer.apple.com/documentation/apple_search_ads). Keyed by the endpoint names in
+`settings.py` `APPLE_SEARCH_ADS_ENDPOINTS`, which match the `ExternalDataSchema.name` of a synced
+table. Columns absent here fall back to LLM enrichment.
+"""
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (
+ CanonicalDescriptions,
+)
+
+# Metrics shared by every reporting table, so the daily grain reads the same everywhere.
+_REPORT_METRIC_COLUMNS: dict[str, str] = {
+ "date": "Calendar day the metrics cover, in the organization's time zone.",
+ "impressions": "Number of times the ad was shown on that day.",
+ "taps": "Number of taps on the ad.",
+ "installs": "Total conversions attributed to the ad, combining new downloads and redownloads.",
+ "newDownloads": "Conversions from users who had not previously downloaded the app.",
+ "redownloads": "Conversions from users who had previously downloaded the app.",
+ "latOnInstalls": "Conversions from devices with Limit Ad Tracking enabled.",
+ "latOffInstalls": "Conversions from devices with Limit Ad Tracking disabled.",
+ "ttr": "Tap-through rate: taps divided by impressions.",
+ "conversionRate": "Conversion rate: installs divided by taps.",
+ "localSpend": "Amount spent on that day, as an amount plus currency code.",
+ "avgCPA": "Average cost per acquisition, in the organization's currency.",
+ "avgCPT": "Average cost per tap, in the organization's currency.",
+ "avgCPM": "Average cost per thousand impressions, in the organization's currency.",
+}
+
+CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
+ "acls": {
+ "description": "Organizations the API credentials can read, with the role granted to them.",
+ "docs_url": "https://developer.apple.com/documentation/apple_search_ads/get_user_acl",
+ "columns": {
+ "orgId": "Identifier of the organization, used as the `orgId` in the API context header.",
+ "orgName": "Display name of the organization.",
+ "currency": "Three-letter ISO currency code the organization is billed in.",
+ "timeZone": "Time zone the organization's reporting is expressed in.",
+ "paymentModel": "Billing model for the organization: LOC (line of credit), PAYG, or unset.",
+ "roleNames": "Roles the API user holds on the organization, such as API Read Only.",
+ },
+ },
+ "campaigns": {
+ "description": "Campaigns in the organization, each targeting one app in one or more storefronts.",
+ "docs_url": "https://developer.apple.com/documentation/apple_search_ads/campaign",
+ "columns": {
+ "id": "Unique identifier for the campaign.",
+ "orgId": "Identifier of the organization that owns the campaign.",
+ "name": "Name of the campaign.",
+ "adamId": "App Store identifier of the app the campaign promotes.",
+ "budgetAmount": "Total budget for the campaign, as an amount plus currency code.",
+ "dailyBudgetAmount": "Daily budget cap, as an amount plus currency code.",
+ "countriesOrRegions": "Storefronts the campaign runs in, as country or region codes.",
+ "adChannelType": "Channel the campaign advertises on, such as SEARCH or DISPLAY.",
+ "supplySources": "App Store placements the campaign serves in, such as APPSTORE_SEARCH_RESULTS.",
+ "billingEvent": "Event the campaign is billed on — TAPS for Search Ads campaigns.",
+ "paymentModel": "Billing model in effect for the campaign.",
+ "startTime": "When the campaign starts serving.",
+ "endTime": "When the campaign stops serving, if an end is set.",
+ "status": "Status the advertiser set: ENABLED or PAUSED.",
+ "servingStatus": "Whether the campaign is currently RUNNING or NOT_RUNNING.",
+ "servingStateReasons": "Reasons the campaign is not serving, if any.",
+ "displayStatus": "Combined status shown in the Search Ads UI.",
+ "modificationTime": "When the campaign was last changed.",
+ "deleted": "Whether the campaign has been deleted.",
+ },
+ },
+ "ad_groups": {
+ "description": "Ad groups across every campaign in the organization, holding bids and targeting.",
+ "docs_url": "https://developer.apple.com/documentation/apple_search_ads/adgroup",
+ "columns": {
+ "id": "Unique identifier for the ad group.",
+ "campaignId": "Identifier of the campaign the ad group belongs to.",
+ "orgId": "Identifier of the organization that owns the ad group.",
+ "name": "Name of the ad group.",
+ "defaultBidAmount": "Default cost-per-tap bid, as an amount plus currency code.",
+ "cpaGoal": "Optional cost-per-acquisition goal, as an amount plus currency code.",
+ "pricingModel": "Pricing model for the ad group, such as CPC.",
+ "automatedKeywordsOptIn": "Whether Apple may add matching keywords automatically.",
+ "targetingDimensions": "Audience, device, demographic and locality targeting for the ad group.",
+ "startTime": "When the ad group starts serving.",
+ "endTime": "When the ad group stops serving, if an end is set.",
+ "status": "Status the advertiser set: ENABLED or PAUSED.",
+ "servingStatus": "Whether the ad group is currently RUNNING or NOT_RUNNING.",
+ "servingStateReasons": "Reasons the ad group is not serving, if any.",
+ "displayStatus": "Combined status shown in the Search Ads UI.",
+ "modificationTime": "When the ad group was last changed.",
+ "deleted": "Whether the ad group has been deleted.",
+ },
+ },
+ "keywords": {
+ "description": "Targeting keywords across every ad group in the organization.",
+ "docs_url": "https://developer.apple.com/documentation/apple_search_ads/keyword",
+ "columns": {
+ "id": "Unique identifier for the keyword.",
+ "adGroupId": "Identifier of the ad group the keyword targets within.",
+ "campaignId": "Identifier of the campaign the keyword belongs to.",
+ "text": "The keyword text bid on.",
+ "matchType": "How the search term must match the keyword: EXACT or BROAD.",
+ "bidAmount": "Cost-per-tap bid for the keyword, as an amount plus currency code.",
+ "status": "Status the advertiser set: ACTIVE or PAUSED.",
+ "modificationTime": "When the keyword was last changed.",
+ "deleted": "Whether the keyword has been deleted.",
+ },
+ },
+ "campaign_report": {
+ "description": "Daily performance metrics per campaign, one row per campaign per day.",
+ "docs_url": "https://developer.apple.com/documentation/apple_search_ads/get_campaign-level_reports",
+ "columns": {
+ "campaignId": "Identifier of the campaign the metrics belong to.",
+ "campaignName": "Name of the campaign at the time the report was run.",
+ "campaignStatus": "Status of the campaign at the time the report was run.",
+ "app": "App the campaign promotes, with its App Store identifier and name.",
+ "countriesOrRegions": "Storefronts the campaign served in.",
+ "deleted": "Whether the campaign has since been deleted.",
+ **_REPORT_METRIC_COLUMNS,
+ },
+ },
+ "ad_group_report": {
+ "description": "Daily performance metrics per ad group, one row per ad group per day.",
+ "docs_url": "https://developer.apple.com/documentation/apple_search_ads/get_ad_group-level_reports",
+ "columns": {
+ "campaignId": "Identifier of the campaign the ad group belongs to.",
+ "adGroupId": "Identifier of the ad group the metrics belong to.",
+ "adGroupName": "Name of the ad group at the time the report was run.",
+ "adGroupStatus": "Status of the ad group at the time the report was run.",
+ "defaultBidAmount": "Default cost-per-tap bid in effect for the ad group.",
+ "deleted": "Whether the ad group has since been deleted.",
+ **_REPORT_METRIC_COLUMNS,
+ },
+ },
+ "keyword_report": {
+ "description": "Daily performance metrics per targeting keyword, one row per keyword per day.",
+ "docs_url": "https://developer.apple.com/documentation/apple_search_ads/get_keyword-level_reports",
+ "columns": {
+ "campaignId": "Identifier of the campaign the keyword belongs to.",
+ "keywordId": "Identifier of the keyword the metrics belong to.",
+ "keyword": "The keyword text bid on.",
+ "matchType": "How the search term matched the keyword: EXACT or BROAD.",
+ "adGroupId": "Identifier of the ad group the keyword targets within.",
+ "adGroupName": "Name of the ad group at the time the report was run.",
+ "bid": "Cost-per-tap bid in effect for the keyword.",
+ "keywordStatus": "Status of the keyword at the time the report was run.",
+ "keywordDisplayStatus": "Combined keyword status shown in the Search Ads UI.",
+ "deleted": "Whether the keyword has since been deleted.",
+ **_REPORT_METRIC_COLUMNS,
+ },
+ },
+}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/apple_search_ads/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/apple_search_ads/settings.py
new file mode 100644
index 000000000000..246551ea458e
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/apple_search_ads/settings.py
@@ -0,0 +1,129 @@
+from dataclasses import dataclass, field
+from typing import Literal, Optional
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.schema import incremental_field
+from products.warehouse_sources.backend.types import IncrementalField, IncrementalFieldType
+
+# How each endpoint is read:
+# single — one GET, whole result set in `data` (no pagination params).
+# query_page — GET with `limit`/`offset` query params.
+# find — POST whose body *is* a Selector (`conditions`/`pagination`).
+# report — POST a date-bounded report request; rows arrive nested under
+# `data.reportingDataResponse.row`, one per entity with a daily
+# `granularity` array.
+EndpointKind = Literal["single", "query_page", "find", "report"]
+
+# Apple caps `limit` (entity endpoints) and `selector.pagination.limit` (find/report) at 1000.
+PAGE_SIZE = 1000
+
+# Reporting requests are bounded to a short window so that the per-batch incremental
+# watermark can never advance further ahead of the data than the trailing lookback below
+# re-reads. Within one window rows arrive grouped by entity rather than by date, so the
+# window length is the ordering error budget — keep it <= the lookback.
+REPORT_WINDOW_DAYS = 7
+
+# Apple restates recent reporting rows (3-4h ingestion delay plus attribution), so every
+# incremental run re-reads a trailing week rather than trusting the frozen watermark.
+REPORT_LOOKBACK_SECONDS = REPORT_WINDOW_DAYS * 24 * 60 * 60
+
+# How far back the first sync of a report table reaches when the user gives no start date.
+DEFAULT_INITIAL_LOOKBACK_DAYS = 365
+
+# The earliest a configured start date may reach. Apple Search Ads has held no reporting data
+# from before it launched, so a start date older than this is a typo — clamp it rather than fan
+# a report out over thousands of empty windows (one report request per window per campaign).
+MAX_INITIAL_LOOKBACK_DAYS = 11 * 365
+
+
+@dataclass(frozen=True)
+class AppleSearchAdsEndpointConfig:
+ name: str
+ # Path under `https://api.searchads.apple.com/api/{version}`.
+ path: str
+ kind: EndpointKind
+ primary_keys: list[str]
+ # Every Campaign Management endpoint except `/acls` is scoped to one organization via
+ # the `X-AP-Context: orgId=...` header.
+ requires_org_context: bool = True
+ # Apple only exposes ad-group/keyword level reports per campaign, so those tables are
+ # built by fanning out over the org's campaign ids.
+ fan_out_over_campaigns: bool = False
+ incremental_fields: list[IncrementalField] = field(default_factory=list)
+ # Reporting date — set by Apple, never restated to a different day, so it is a stable
+ # partition key.
+ partition_key: Optional[str] = None
+
+
+APPLE_SEARCH_ADS_ENDPOINTS: dict[str, AppleSearchAdsEndpointConfig] = {
+ "acls": AppleSearchAdsEndpointConfig(
+ name="acls",
+ path="/acls",
+ kind="single",
+ primary_keys=["orgId"],
+ requires_org_context=False,
+ ),
+ "campaigns": AppleSearchAdsEndpointConfig(
+ name="campaigns",
+ path="/campaigns",
+ kind="query_page",
+ primary_keys=["id"],
+ ),
+ "ad_groups": AppleSearchAdsEndpointConfig(
+ name="ad_groups",
+ path="/adgroups/find",
+ kind="find",
+ primary_keys=["id"],
+ ),
+ "keywords": AppleSearchAdsEndpointConfig(
+ name="keywords",
+ path="/targetingkeywords/find",
+ kind="find",
+ primary_keys=["id"],
+ ),
+ "campaign_report": AppleSearchAdsEndpointConfig(
+ name="campaign_report",
+ path="/reports/campaigns",
+ kind="report",
+ primary_keys=["campaignId", "date"],
+ partition_key="date",
+ incremental_fields=[incremental_field("date", IncrementalFieldType.Date)],
+ ),
+ "ad_group_report": AppleSearchAdsEndpointConfig(
+ name="ad_group_report",
+ path="/reports/campaigns/{campaign_id}/adgroups",
+ kind="report",
+ fan_out_over_campaigns=True,
+ primary_keys=["campaignId", "adGroupId", "date"],
+ partition_key="date",
+ incremental_fields=[incremental_field("date", IncrementalFieldType.Date)],
+ ),
+ "keyword_report": AppleSearchAdsEndpointConfig(
+ name="keyword_report",
+ path="/reports/campaigns/{campaign_id}/keywords",
+ kind="report",
+ fan_out_over_campaigns=True,
+ # Apple keyword ids are unique across ad groups, so the campaign the row was fanned
+ # out from plus the keyword and date identify a row table-wide.
+ primary_keys=["campaignId", "keywordId", "date"],
+ partition_key="date",
+ incremental_fields=[incremental_field("date", IncrementalFieldType.Date)],
+ ),
+}
+
+ENDPOINTS = tuple(APPLE_SEARCH_ADS_ENDPOINTS.keys())
+
+INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {
+ name: config.incremental_fields for name, config in APPLE_SEARCH_ADS_ENDPOINTS.items()
+}
+
+REPORT_ENDPOINTS = tuple(name for name, config in APPLE_SEARCH_ADS_ENDPOINTS.items() if config.kind == "report")
+
+ENDPOINT_DESCRIPTIONS: dict[str, str] = {
+ "acls": "Organizations the API credentials can read, with currency, time zone and role names.",
+ "campaigns": "Campaigns in the organization, with budget, serving status and countries or regions.",
+ "ad_groups": "Ad groups across every campaign in the organization, with default bid and targeting.",
+ "keywords": "Targeting keywords across every ad group in the organization, with match type and bid.",
+ "campaign_report": "Daily campaign performance: impressions, taps, installs, spend and derived rates.",
+ "ad_group_report": "Daily ad group performance for every campaign in the organization.",
+ "keyword_report": "Daily keyword performance for every campaign in the organization.",
+}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/apple_search_ads/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/apple_search_ads/source.py
index 08adf15b67c6..9a212d2ca74a 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/apple_search_ads/source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/apple_search_ads/source.py
@@ -1,13 +1,39 @@
-from typing import cast
+from typing import Optional, cast
from posthog.schema import (
DataWarehouseSourceCategory,
ExternalDataSourceType as SchemaExternalDataSourceType,
+ ReleaseStatus,
SourceConfig,
+ SourceFieldInputConfig,
+ SourceFieldInputConfigType,
)
-from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, SimpleSource
+from products.warehouse_sources.backend.temporal.data_imports.sources.apple_search_ads.apple_search_ads import (
+ AppleSearchAdsCredentials,
+ AppleSearchAdsResumeConfig,
+ apple_search_ads_source,
+ validate_credentials as validate_apple_search_ads_credentials,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.apple_search_ads.settings import (
+ APPLE_SEARCH_ADS_ENDPOINTS,
+ ENDPOINT_DESCRIPTIONS,
+ ENDPOINTS,
+ INCREMENTAL_FIELDS,
+ REPORT_ENDPOINTS,
+ REPORT_LOOKBACK_SECONDS,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, ResumableSource
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (
+ CanonicalDescriptions,
+)
from products.warehouse_sources.backend.temporal.data_imports.sources.common.registry import SourceRegistry
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.schema import (
+ SourceSchema,
+ build_endpoint_schemas,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceInputs, SourceResponse
from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.applesearchads import (
AppleSearchAdsSourceConfig,
)
@@ -15,18 +41,172 @@ from products.warehouse_sources.backend.types import ExternalDataSourceType
@SourceRegistry.register
-class AppleSearchAdsSource(SimpleSource[AppleSearchAdsSourceConfig]):
+class AppleSearchAdsSource(ResumableSource[AppleSearchAdsSourceConfig, AppleSearchAdsResumeConfig]):
+ lists_tables_without_credentials = True # static endpoint catalog — safe for public docs
+
+ supported_versions = ("v5",)
+ default_version = "v5"
+ api_docs_url = "https://developer.apple.com/documentation/apple_search_ads"
+
@property
def source_type(self) -> ExternalDataSourceType:
return ExternalDataSourceType.APPLESEARCHADS
+ def get_non_retryable_errors(self) -> dict[str, str | None]:
+ return {
+ "400 Client Error: Bad Request for url: https://appleid.apple.com/auth/oauth2/token": "Apple rejected the signed client secret. Check your client ID, team ID, key ID and private key.",
+ "401 Client Error: Unauthorized for url: https://appleid.apple.com/auth/oauth2/token": "Apple rejected the signed client secret. Check your client ID, team ID, key ID and private key.",
+ "401 Client Error: Unauthorized for url: https://api.searchads.apple.com": "Apple Search Ads rejected the access token. Your API key may have been revoked — generate a new one and reconnect.",
+ "403 Client Error: Forbidden for url: https://api.searchads.apple.com": "Apple Search Ads denied access to this organization. Check that the API user has at least read access to the organization ID you entered.",
+ "Could not sign the Apple Search Ads client secret": "The private key isn't a valid unencrypted EC (P-256) PEM. Paste the key you generated for your Search Ads API key and reconnect.",
+ }
+
@property
def get_source_config(self) -> SourceConfig:
return SourceConfig(
name=SchemaExternalDataSourceType.APPLE_SEARCH_ADS,
category=DataWarehouseSourceCategory.ADVERTISING,
label="Apple Search Ads",
+ caption="""Connect your Apple Search Ads account to pull campaigns, ad groups, keywords and daily performance into the PostHog Data warehouse.
+
+In the Search Ads UI, create an API user with at least **Read only** access, generate an API key, and keep the private key it gives you. Then enter the organization ID, client ID, team ID and key ID from the API key page, plus the private key itself. PostHog signs a short-lived token with the key on every sync, so no long-lived secret is stored.""",
iconPath="/static/services/apple_search_ads.png",
- fields=cast(list[FieldType], []),
- unreleasedSource=True,
+ docsUrl="https://posthog.com/docs/cdp/sources/apple-search-ads",
+ releaseStatus=ReleaseStatus.ALPHA,
+ keywords=["asa", "app store ads", "search ads"],
+ fields=cast(
+ list[FieldType],
+ [
+ SourceFieldInputConfig(
+ name="org_id",
+ label="Organization ID",
+ type=SourceFieldInputConfigType.TEXT,
+ required=True,
+ placeholder="123456",
+ secret=False,
+ ),
+ SourceFieldInputConfig(
+ name="client_id",
+ label="Client ID",
+ type=SourceFieldInputConfigType.TEXT,
+ required=True,
+ placeholder="SEARCHADS.27478e17-...",
+ secret=False,
+ ),
+ SourceFieldInputConfig(
+ name="apple_team_id",
+ label="Team ID",
+ type=SourceFieldInputConfigType.TEXT,
+ required=True,
+ placeholder="SEARCHADS.27478e17-...",
+ secret=False,
+ ),
+ SourceFieldInputConfig(
+ name="key_id",
+ label="Key ID",
+ type=SourceFieldInputConfigType.TEXT,
+ required=True,
+ placeholder="a1b2c3d4-...",
+ secret=False,
+ ),
+ SourceFieldInputConfig(
+ name="private_key",
+ label="Private key",
+ type=SourceFieldInputConfigType.TEXTAREA,
+ required=True,
+ placeholder="-----BEGIN EC PRIVATE KEY-----",
+ secret=True,
+ ),
+ SourceFieldInputConfig(
+ name="start_date",
+ label="Report start date",
+ type=SourceFieldInputConfigType.TEXT,
+ required=False,
+ placeholder="2024-01-01",
+ secret=False,
+ ),
+ ],
+ ),
+ )
+
+ def get_canonical_descriptions(self) -> CanonicalDescriptions:
+ from products.warehouse_sources.backend.temporal.data_imports.sources.apple_search_ads.canonical_descriptions import (
+ CANONICAL_DESCRIPTIONS,
+ )
+
+ return CANONICAL_DESCRIPTIONS
+
+ def get_schemas(
+ self,
+ config: AppleSearchAdsSourceConfig,
+ team_id: int,
+ with_counts: bool = False,
+ names: list[str] | None = None,
+ force_refresh: bool = False,
+ api_version: str | None = None,
+ ) -> list[SourceSchema]:
+ schemas = build_endpoint_schemas(
+ ENDPOINTS,
+ INCREMENTAL_FIELDS,
+ names,
+ descriptions=ENDPOINT_DESCRIPTIONS,
+ # Every incremental run re-reads a trailing window of already-imported days, so
+ # these tables have to merge on their primary key; appending would duplicate rows.
+ merge_only=REPORT_ENDPOINTS,
+ )
+
+ for schema in schemas:
+ # Apple keeps revising the last few days of reporting data (ingestion delay plus
+ # attribution), so an incremental run re-reads a trailing window instead of
+ # trusting the frozen watermark.
+ if APPLE_SEARCH_ADS_ENDPOINTS[schema.name].partition_key is not None:
+ schema.default_incremental_lookback_seconds = REPORT_LOOKBACK_SECONDS
+
+ return schemas
+
+ def validate_credentials(
+ self,
+ config: AppleSearchAdsSourceConfig,
+ team_id: int,
+ schema_name: Optional[str] = None,
+ api_version: str | None = None,
+ ) -> tuple[bool, str | None]:
+ return validate_apple_search_ads_credentials(
+ self._credentials(config),
+ self.resolve_api_version(api_version),
+ schema_name,
+ )
+
+ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[AppleSearchAdsResumeConfig]:
+ # Entity and report endpoints store incompatible checkpoint shapes, so keep each
+ # endpoint's state in its own Redis slot.
+ return ResumableSourceManager[AppleSearchAdsResumeConfig](inputs, AppleSearchAdsResumeConfig).with_namespace(
+ inputs.schema_name
+ )
+
+ def source_for_pipeline(
+ self,
+ config: AppleSearchAdsSourceConfig,
+ resumable_source_manager: ResumableSourceManager[AppleSearchAdsResumeConfig],
+ inputs: SourceInputs,
+ ) -> SourceResponse:
+ return apple_search_ads_source(
+ credentials=self._credentials(config),
+ endpoint=inputs.schema_name,
+ api_version=self.resolve_api_version(inputs.api_version),
+ request_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,
+ start_date=config.start_date,
+ )
+
+ @staticmethod
+ def _credentials(config: AppleSearchAdsSourceConfig) -> AppleSearchAdsCredentials:
+ return AppleSearchAdsCredentials(
+ org_id=config.org_id,
+ client_id=config.client_id,
+ team_id=config.apple_team_id,
+ key_id=config.key_id,
+ private_key=config.private_key,
)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/apple_search_ads/tests/test_apple_search_ads.py b/products/warehouse_sources/backend/temporal/data_imports/sources/apple_search_ads/tests/test_apple_search_ads.py
new file mode 100644
index 000000000000..3a75228d5d21
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/apple_search_ads/tests/test_apple_search_ads.py
@@ -0,0 +1,670 @@
+import dataclasses
+from collections.abc import Iterable
+from datetime import date, datetime, timedelta
+from typing import Any, Optional, cast
+
+import pytest
+from unittest import mock
+
+import jwt
+import structlog
+from cryptography.hazmat.primitives import serialization
+from cryptography.hazmat.primitives.asymmetric import ec
+from parameterized import parameterized
+from requests.exceptions import HTTPError
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.apple_search_ads.apple_search_ads import (
+ APPLE_OAUTH_AUDIENCE,
+ APPLE_OAUTH_TOKEN_URL,
+ APPLE_SEARCH_ADS_HOST,
+ AppleSearchAdsAuthError,
+ AppleSearchAdsClient,
+ AppleSearchAdsCredentials,
+ AppleSearchAdsResumeConfig,
+ ReportWindow,
+ _report_start_date,
+ _report_windows,
+ apple_search_ads_source,
+ build_client_secret,
+ flatten_report_rows,
+ get_rows,
+ validate_credentials,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.apple_search_ads.settings import (
+ APPLE_SEARCH_ADS_ENDPOINTS,
+ DEFAULT_INITIAL_LOOKBACK_DAYS,
+ ENDPOINTS,
+ MAX_INITIAL_LOOKBACK_DAYS,
+ PAGE_SIZE,
+ REPORT_WINDOW_DAYS,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+
+SESSION_PATCH = (
+ "products.warehouse_sources.backend.temporal.data_imports.sources.apple_search_ads."
+ "apple_search_ads.make_tracked_session"
+)
+TODAY_PATCH = (
+ "products.warehouse_sources.backend.temporal.data_imports.sources.apple_search_ads.apple_search_ads._today"
+)
+
+API_VERSION = "v5"
+BASE_URL = f"{APPLE_SEARCH_ADS_HOST}/api/{API_VERSION}"
+
+_private_key = ec.generate_private_key(ec.SECP256R1())
+PRIVATE_KEY_PEM = _private_key.private_bytes(
+ encoding=serialization.Encoding.PEM,
+ format=serialization.PrivateFormat.PKCS8,
+ encryption_algorithm=serialization.NoEncryption(),
+).decode()
+PUBLIC_KEY_PEM = (
+ _private_key.public_key()
+ .public_bytes(
+ encoding=serialization.Encoding.PEM,
+ format=serialization.PublicFormat.SubjectPublicKeyInfo,
+ )
+ .decode()
+)
+
+CREDENTIALS = AppleSearchAdsCredentials(
+ org_id="555",
+ client_id="SEARCHADS.client",
+ team_id="SEARCHADS.team",
+ key_id="key-1",
+ private_key=PRIVATE_KEY_PEM,
+)
+
+LOGGER = cast(Any, structlog.get_logger(__name__))
+
+
+def _with_key(private_key: str) -> AppleSearchAdsCredentials:
+ return dataclasses.replace(CREDENTIALS, private_key=private_key)
+
+
+class _FakeResponse:
+ def __init__(self, status_code: int = 200, json_data: Optional[dict[str, Any]] = None, url: str = BASE_URL):
+ self.status_code = status_code
+ self._json_data = json_data if json_data is not None else {}
+ self.url = url
+ self.text = str(self._json_data)
+
+ @property
+ def ok(self) -> bool:
+ return self.status_code < 400
+
+ def json(self) -> dict[str, Any]:
+ return self._json_data
+
+ def raise_for_status(self) -> None:
+ if not self.ok:
+ kind = "Client Error" if self.status_code < 500 else "Server Error"
+ raise HTTPError(f"{self.status_code} {kind}: for url: {self.url}", response=cast(Any, None))
+
+
+def _token_response(token: str = "access-token") -> _FakeResponse:
+ return _FakeResponse(200, {"access_token": token, "expires_in": 3600}, url=APPLE_OAUTH_TOKEN_URL)
+
+
+class _FakeSession:
+ """Replays queued API responses and records every request the client made."""
+
+ def __init__(self, api_responses: list[_FakeResponse], token_responses: Optional[list[_FakeResponse]] = None):
+ self._api_responses = list(api_responses)
+ self._token_responses = list(token_responses) if token_responses is not None else None
+ self.calls: list[dict[str, Any]] = []
+
+ @property
+ def api_calls(self) -> list[dict[str, Any]]:
+ return [call for call in self.calls if call["url"] != APPLE_OAUTH_TOKEN_URL]
+
+ @property
+ def token_calls(self) -> list[dict[str, Any]]:
+ return [call for call in self.calls if call["url"] == APPLE_OAUTH_TOKEN_URL]
+
+ def _next(self, url: str) -> _FakeResponse:
+ if url == APPLE_OAUTH_TOKEN_URL:
+ if self._token_responses is not None:
+ return self._token_responses.pop(0)
+ return _token_response()
+ if not self._api_responses:
+ raise AssertionError(f"unexpected extra request to {url}")
+ return self._api_responses.pop(0)
+
+ def get(
+ self,
+ url: str,
+ params: Optional[dict[str, Any]] = None,
+ headers: Optional[dict[str, str]] = None,
+ timeout: Optional[float] = None,
+ ) -> _FakeResponse:
+ self.calls.append({"method": "GET", "url": url, "params": params, "headers": headers or {}})
+ return self._next(url)
+
+ def post(
+ self,
+ url: str,
+ json: Optional[dict[str, Any]] = None,
+ data: Optional[dict[str, Any]] = None,
+ headers: Optional[dict[str, str]] = None,
+ timeout: Optional[float] = None,
+ ) -> _FakeResponse:
+ self.calls.append({"method": "POST", "url": url, "json": json, "data": data, "headers": headers or {}})
+ return self._next(url)
+
+
+class _FakeResumableManager(ResumableSourceManager[AppleSearchAdsResumeConfig]):
+ """In-memory stand-in for the Redis-backed manager (no `super().__init__`)."""
+
+ def __init__(self, resume_state: Optional[AppleSearchAdsResumeConfig] = None):
+ self._resume_state = resume_state
+ self.saved_states: list[AppleSearchAdsResumeConfig] = []
+ self.cleared = False
+
+ def can_resume(self) -> bool:
+ return self._resume_state is not None
+
+ def load_state(self) -> AppleSearchAdsResumeConfig | None:
+ return self._resume_state
+
+ def save_state(self, data: AppleSearchAdsResumeConfig) -> None:
+ self.saved_states.append(data)
+
+ def clear_state(self) -> None:
+ self.cleared = True
+
+
+def _entity_page(rows: list[dict[str, Any]]) -> _FakeResponse:
+ return _FakeResponse(200, {"data": rows, "pagination": {"totalResults": len(rows)}})
+
+
+def _report_payload(rows: list[dict[str, Any]]) -> dict[str, Any]:
+ return {"data": {"reportingDataResponse": {"row": rows}}}
+
+
+def _report_page(rows: list[dict[str, Any]]) -> _FakeResponse:
+ return _FakeResponse(200, _report_payload(rows))
+
+
+def _report_row(metadata: dict[str, Any], dates: list[str]) -> dict[str, Any]:
+ return {
+ "metadata": metadata,
+ "granularity": [{"date": day, "impressions": 10, "taps": 1} for day in dates],
+ }
+
+
+def _run(
+ endpoint: str,
+ session: _FakeSession,
+ manager: _FakeResumableManager,
+ **kwargs: Any,
+) -> list[list[dict[str, Any]]]:
+ with mock.patch(SESSION_PATCH, return_value=session):
+ return list(
+ get_rows(
+ credentials=CREDENTIALS,
+ endpoint=endpoint,
+ api_version=API_VERSION,
+ request_logger=LOGGER,
+ resumable_source_manager=manager,
+ **kwargs,
+ )
+ )
+
+
+class TestAppleSearchAdsTransport:
+ def test_client_secret_is_a_signed_es256_assertion(self) -> None:
+ token = build_client_secret(CREDENTIALS, issued_at=1_700_000_000)
+
+ header = jwt.get_unverified_header(token)
+ assert header["alg"] == "ES256"
+ assert header["kid"] == "key-1"
+
+ claims = jwt.decode(
+ token,
+ PUBLIC_KEY_PEM,
+ algorithms=["ES256"],
+ audience=APPLE_OAUTH_AUDIENCE,
+ options={"verify_exp": False},
+ )
+ assert claims["sub"] == CREDENTIALS.client_id
+ assert claims["iss"] == CREDENTIALS.team_id
+ assert claims["iat"] == 1_700_000_000
+ assert claims["exp"] > claims["iat"]
+
+ def test_client_secret_accepts_a_pem_with_escaped_newlines(self) -> None:
+ escaped = CREDENTIALS.private_key.replace("\n", "\\n")
+ token = build_client_secret(_with_key(escaped))
+
+ assert jwt.decode(token, PUBLIC_KEY_PEM, algorithms=["ES256"], audience=APPLE_OAUTH_AUDIENCE)
+
+ @parameterized.expand(
+ [
+ ("garbage", "not-a-key"),
+ ("empty", ""),
+ ("truncated_pem", "-----BEGIN PRIVATE KEY-----\nabc\n-----END PRIVATE KEY-----"),
+ ]
+ )
+ def test_client_secret_rejects_an_unusable_private_key(self, _name: str, private_key: str) -> None:
+ with pytest.raises(AppleSearchAdsAuthError):
+ build_client_secret(_with_key(private_key))
+
+ def test_requests_carry_the_bearer_token_and_org_context(self) -> None:
+ session = _FakeSession([_entity_page([{"id": 1}])])
+ manager = _FakeResumableManager()
+
+ _run("campaigns", session, manager)
+
+ assert len(session.token_calls) == 1
+ token_body = session.token_calls[0]["data"]
+ assert token_body["grant_type"] == "client_credentials"
+ assert token_body["client_id"] == CREDENTIALS.client_id
+ assert token_body["scope"] == "searchadsorg"
+
+ headers = session.api_calls[0]["headers"]
+ assert headers["Authorization"] == "Bearer access-token"
+ assert headers["X-AP-Context"] == "orgId=555"
+
+ def test_acls_is_a_single_page_without_org_context(self) -> None:
+ session = _FakeSession([_entity_page([{"orgId": 555}])])
+ manager = _FakeResumableManager()
+
+ batches = _run("acls", session, manager)
+
+ assert batches == [[{"orgId": 555}]]
+ assert len(session.api_calls) == 1
+ assert session.api_calls[0]["url"] == f"{BASE_URL}/acls"
+ assert "X-AP-Context" not in session.api_calls[0]["headers"]
+
+ def test_find_endpoints_page_in_the_request_body(self) -> None:
+ session = _FakeSession([_entity_page([{"id": 7}])])
+ manager = _FakeResumableManager()
+
+ _run("ad_groups", session, manager)
+
+ call = session.api_calls[0]
+ assert call["method"] == "POST"
+ assert call["url"] == f"{BASE_URL}/adgroups/find"
+ assert call["json"]["pagination"] == {"offset": 0, "limit": PAGE_SIZE}
+
+ def test_expired_access_token_is_reminted_once_and_the_request_replayed(self) -> None:
+ session = _FakeSession(
+ [_FakeResponse(401, url=BASE_URL), _entity_page([{"id": 1}])],
+ token_responses=[_token_response("first"), _token_response("second")],
+ )
+ manager = _FakeResumableManager()
+
+ batches = _run("campaigns", session, manager)
+
+ assert batches == [[{"id": 1}]]
+ assert len(session.token_calls) == 2
+ assert session.api_calls[0]["headers"]["Authorization"] == "Bearer first"
+ assert session.api_calls[1]["headers"]["Authorization"] == "Bearer second"
+
+ @parameterized.expand([("unauthorized", 401), ("forbidden", 403), ("server_error", 500)])
+ def test_a_persistent_error_status_raises(self, _name: str, status: int) -> None:
+ # Two identical failures so the single 401 re-mint retry is exhausted too.
+ session = _FakeSession([_FakeResponse(status, url=BASE_URL), _FakeResponse(status, url=BASE_URL)])
+ manager = _FakeResumableManager()
+
+ with pytest.raises(HTTPError):
+ _run("campaigns", session, manager)
+
+ def test_entity_pagination_advances_the_offset_and_checkpoints_between_pages(self) -> None:
+ first_page = [{"id": index} for index in range(PAGE_SIZE)]
+ session = _FakeSession([_entity_page(first_page), _entity_page([{"id": PAGE_SIZE}])])
+ manager = _FakeResumableManager()
+
+ batches = _run("campaigns", session, manager)
+
+ assert [len(batch) for batch in batches] == [PAGE_SIZE, 1]
+ assert [call["params"]["offset"] for call in session.api_calls] == [0, PAGE_SIZE]
+ assert [state.offset for state in manager.saved_states] == [PAGE_SIZE]
+ assert manager.cleared is True
+
+ def test_entity_pagination_resumes_from_the_saved_offset(self) -> None:
+ session = _FakeSession([_entity_page([{"id": 1}])])
+ manager = _FakeResumableManager(AppleSearchAdsResumeConfig(offset=2000))
+
+ _run("campaigns", session, manager)
+
+ assert session.api_calls[0]["params"]["offset"] == 2000
+
+ def test_empty_first_page_yields_nothing_and_terminates(self) -> None:
+ session = _FakeSession([_entity_page([])])
+ manager = _FakeResumableManager()
+
+ assert _run("keywords", session, manager) == []
+ assert len(session.api_calls) == 1
+
+
+class TestReportWindows:
+ @parameterized.expand(
+ [
+ (
+ "single_day",
+ date(2026, 1, 1),
+ date(2026, 1, 1),
+ [ReportWindow(start=date(2026, 1, 1), end=date(2026, 1, 1))],
+ ),
+ (
+ "exactly_one_window",
+ date(2026, 1, 1),
+ date(2026, 1, 7),
+ [ReportWindow(start=date(2026, 1, 1), end=date(2026, 1, 7))],
+ ),
+ (
+ "spills_into_a_second_window",
+ date(2026, 1, 1),
+ date(2026, 1, 9),
+ [
+ ReportWindow(start=date(2026, 1, 1), end=date(2026, 1, 7)),
+ ReportWindow(start=date(2026, 1, 8), end=date(2026, 1, 9)),
+ ],
+ ),
+ ("end_before_start", date(2026, 1, 9), date(2026, 1, 1), []),
+ ]
+ )
+ def test_windows_are_ascending_and_inclusive(
+ self, _name: str, start: date, end: date, expected: list[ReportWindow]
+ ) -> None:
+ assert _report_windows(start, end) == expected
+
+ def test_windows_never_exceed_the_configured_length(self) -> None:
+ windows = _report_windows(date(2026, 1, 1), date(2026, 3, 1))
+
+ assert all((window.end - window.start).days + 1 <= REPORT_WINDOW_DAYS for window in windows)
+ # Contiguous with no gaps or overlaps.
+ assert all(later.start == earlier.end + timedelta(days=1) for earlier, later in zip(windows, windows[1:]))
+
+ @parameterized.expand(
+ [
+ ("watermark_wins", True, date(2026, 5, 1), "2020-01-01", date(2026, 5, 1)),
+ ("iso_string_watermark", True, "2026-05-01", None, date(2026, 5, 1)),
+ ("datetime_watermark", True, datetime(2026, 5, 1, 6, 30), None, date(2026, 5, 1)),
+ ("configured_start_date", False, None, "2026-02-03", date(2026, 2, 3)),
+ ("unparseable_start_date_falls_back", False, None, "not-a-date", None),
+ ("no_watermark_no_start_date", False, None, None, None),
+ ("incremental_without_watermark", True, None, None, None),
+ # An implausibly old configured start is floored so it can't fan out over thousands
+ # of empty windows.
+ ("ancient_start_date_is_floored", False, None, "0001-01-01", None),
+ ]
+ )
+ def test_report_start_date(
+ self,
+ _name: str,
+ should_use_incremental_field: bool,
+ watermark: Any,
+ start_date: Optional[str],
+ expected: Optional[date],
+ ) -> None:
+ today = date(2026, 6, 1)
+ resolved = _report_start_date(should_use_incremental_field, watermark, start_date, today)
+
+ if _name == "ancient_start_date_is_floored":
+ assert resolved == today - timedelta(days=MAX_INITIAL_LOOKBACK_DAYS)
+ else:
+ assert resolved == (expected or today - timedelta(days=DEFAULT_INITIAL_LOOKBACK_DAYS))
+
+
+class TestFlattenReportRows:
+ def test_granularity_buckets_become_one_row_per_day(self) -> None:
+ payload = _report_payload([_report_row({"campaignId": 1, "campaignName": "A"}, ["2026-01-01", "2026-01-02"])])
+
+ rows = flatten_report_rows(payload, None)
+
+ assert rows == [
+ {"campaignId": 1, "campaignName": "A", "date": "2026-01-01", "impressions": 10, "taps": 1},
+ {"campaignId": 1, "campaignName": "A", "date": "2026-01-02", "impressions": 10, "taps": 1},
+ ]
+
+ def test_fan_out_injects_the_campaign_id_the_primary_key_needs(self) -> None:
+ payload = _report_payload([_report_row({"adGroupId": 9}, ["2026-01-01"])])
+
+ rows = flatten_report_rows(payload, 42)
+
+ assert rows[0]["campaignId"] == 42
+ assert rows[0]["adGroupId"] == 9
+
+ def test_fan_out_does_not_clobber_a_campaign_id_apple_supplied(self) -> None:
+ payload = _report_payload([_report_row({"campaignId": 7, "adGroupId": 9}, ["2026-01-01"])])
+
+ assert flatten_report_rows(payload, 42)[0]["campaignId"] == 7
+
+ @parameterized.expand(
+ [
+ ("no_granularity", {"data": {"reportingDataResponse": {"row": [{"metadata": {"campaignId": 1}}]}}}),
+ ("empty_row_list", {"data": {"reportingDataResponse": {"row": []}}}),
+ ("null_reporting_data", {"data": None}),
+ ("missing_data_key", {}),
+ ]
+ )
+ def test_pages_without_daily_metrics_flatten_to_nothing(self, _name: str, payload: dict[str, Any]) -> None:
+ assert flatten_report_rows(payload, None) == []
+
+
+class TestReportSync:
+ def test_campaign_report_requests_one_windowed_page_per_window(self) -> None:
+ session = _FakeSession(
+ [
+ _report_page([_report_row({"campaignId": 1}, ["2026-01-01"])]),
+ _report_page([_report_row({"campaignId": 1}, ["2026-01-08"])]),
+ ]
+ )
+ manager = _FakeResumableManager()
+
+ with mock.patch(TODAY_PATCH, return_value=date(2026, 1, 9)):
+ batches = _run(
+ "campaign_report",
+ session,
+ manager,
+ should_use_incremental_field=True,
+ db_incremental_field_last_value=date(2026, 1, 1),
+ )
+
+ assert [row["date"] for batch in batches for row in batch] == ["2026-01-01", "2026-01-08"]
+ bodies = [call["json"] for call in session.api_calls]
+ assert [(body["startTime"], body["endTime"]) for body in bodies] == [
+ ("2026-01-01", "2026-01-07"),
+ ("2026-01-08", "2026-01-09"),
+ ]
+ assert bodies[0]["granularity"] == "DAILY"
+ assert bodies[0]["selector"]["pagination"] == {"offset": 0, "limit": PAGE_SIZE}
+ # After the first window completes, the checkpoint points at the next window.
+ assert manager.saved_states[0] == AppleSearchAdsResumeConfig(
+ offset=0, window_start="2026-01-08", campaign_id=None
+ )
+
+ def test_fan_out_reports_walk_every_campaign_in_every_window(self) -> None:
+ session = _FakeSession(
+ [
+ _entity_page([{"id": 20}, {"id": 10}]),
+ _report_page([_report_row({"adGroupId": 1}, ["2026-01-01"])]),
+ _report_page([_report_row({"adGroupId": 2}, ["2026-01-01"])]),
+ ]
+ )
+ manager = _FakeResumableManager()
+
+ with mock.patch(TODAY_PATCH, return_value=date(2026, 1, 3)):
+ batches = _run(
+ "ad_group_report",
+ session,
+ manager,
+ should_use_incremental_field=True,
+ db_incremental_field_last_value=date(2026, 1, 1),
+ )
+
+ report_calls = [call for call in session.api_calls if "/reports/" in call["url"]]
+ # Campaign ids are visited in a stable ascending order, not response order.
+ assert [call["url"] for call in report_calls] == [
+ f"{BASE_URL}/reports/campaigns/10/adgroups",
+ f"{BASE_URL}/reports/campaigns/20/adgroups",
+ ]
+ assert [row["campaignId"] for batch in batches for row in batch] == [10, 20]
+ assert manager.saved_states[0] == AppleSearchAdsResumeConfig(
+ offset=0, window_start="2026-01-01", campaign_id=20
+ )
+
+ def test_fan_out_reports_resume_at_the_checkpointed_campaign(self) -> None:
+ session = _FakeSession(
+ [
+ _entity_page([{"id": 10}, {"id": 20}]),
+ _report_page([_report_row({"adGroupId": 2}, ["2026-01-01"])]),
+ ]
+ )
+ manager = _FakeResumableManager(AppleSearchAdsResumeConfig(offset=0, window_start="2026-01-01", campaign_id=20))
+
+ with mock.patch(TODAY_PATCH, return_value=date(2026, 1, 3)):
+ _run(
+ "ad_group_report",
+ session,
+ manager,
+ should_use_incremental_field=True,
+ db_incremental_field_last_value=date(2026, 1, 1),
+ )
+
+ report_calls = [call for call in session.api_calls if "/reports/" in call["url"]]
+ assert [call["url"] for call in report_calls] == [f"{BASE_URL}/reports/campaigns/20/adgroups"]
+
+ def test_a_checkpoint_outside_this_runs_windows_restarts_the_range(self) -> None:
+ session = _FakeSession([_report_page([_report_row({"campaignId": 1}, ["2026-01-01"])])])
+ manager = _FakeResumableManager(
+ AppleSearchAdsResumeConfig(offset=500, window_start="2019-01-01", campaign_id=None)
+ )
+
+ with mock.patch(TODAY_PATCH, return_value=date(2026, 1, 3)):
+ _run(
+ "campaign_report",
+ session,
+ manager,
+ should_use_incremental_field=True,
+ db_incremental_field_last_value=date(2026, 1, 1),
+ )
+
+ body = session.api_calls[0]["json"]
+ assert body["startTime"] == "2026-01-01"
+ assert body["selector"]["pagination"]["offset"] == 0
+
+ def test_report_pagination_continues_while_a_page_is_full(self) -> None:
+ full_page = _report_page([_report_row({"campaignId": index}, ["2026-01-01"]) for index in range(PAGE_SIZE)])
+ session = _FakeSession([full_page, _report_page([_report_row({"campaignId": 9999}, ["2026-01-01"])])])
+ manager = _FakeResumableManager()
+
+ with mock.patch(TODAY_PATCH, return_value=date(2026, 1, 2)):
+ _run(
+ "campaign_report",
+ session,
+ manager,
+ should_use_incremental_field=True,
+ db_incremental_field_last_value=date(2026, 1, 1),
+ )
+
+ offsets = [call["json"]["selector"]["pagination"]["offset"] for call in session.api_calls]
+ assert offsets == [0, PAGE_SIZE]
+ assert manager.saved_states[0] == AppleSearchAdsResumeConfig(
+ offset=PAGE_SIZE, window_start="2026-01-01", campaign_id=None
+ )
+
+
+class TestSourceResponse:
+ @parameterized.expand([(endpoint,) for endpoint in ENDPOINTS])
+ def test_response_matches_the_endpoint_catalog(self, endpoint: str) -> None:
+ config = APPLE_SEARCH_ADS_ENDPOINTS[endpoint]
+
+ response = apple_search_ads_source(
+ credentials=CREDENTIALS,
+ endpoint=endpoint,
+ api_version=API_VERSION,
+ request_logger=LOGGER,
+ resumable_source_manager=_FakeResumableManager(),
+ )
+
+ assert response.name == endpoint
+ assert response.primary_keys == config.primary_keys
+ # Windows are walked oldest-first, so the watermark only ever moves forward.
+ assert response.sort_mode == "asc"
+ if config.partition_key is None:
+ assert response.partition_mode is None
+ assert response.partition_keys is None
+ else:
+ assert response.partition_mode == "datetime"
+ assert response.partition_keys == [config.partition_key]
+
+ def test_items_are_lazy(self) -> None:
+ response = apple_search_ads_source(
+ credentials=CREDENTIALS,
+ endpoint="campaigns",
+ api_version=API_VERSION,
+ request_logger=LOGGER,
+ resumable_source_manager=_FakeResumableManager(),
+ )
+
+ # No HTTP happens until the pipeline iterates, so nothing needed mocking above.
+ assert callable(response.items)
+ assert isinstance(cast("Iterable[Any]", response.items()), Iterable)
+
+
+class TestValidateCredentials:
+ @parameterized.expand(
+ [
+ ("ok", 200, None, True),
+ ("unauthorized", 401, None, False),
+ ("forbidden_at_source_create", 403, None, True),
+ ("forbidden_for_a_schema", 403, "campaigns", False),
+ ("unexpected_status", 500, None, False),
+ ]
+ )
+ def test_probe_status_is_mapped(self, _name: str, status: int, schema_name: Optional[str], expected: bool) -> None:
+ session = _FakeSession([_FakeResponse(status, url=BASE_URL), _FakeResponse(status, url=BASE_URL)])
+
+ with mock.patch(SESSION_PATCH, return_value=session):
+ is_valid, message = validate_credentials(CREDENTIALS, API_VERSION, schema_name)
+
+ assert is_valid is expected
+ assert (message is None) is expected
+
+ def test_probe_targets_an_org_scoped_endpoint(self) -> None:
+ session = _FakeSession([_FakeResponse(200, {"data": []}, url=BASE_URL)])
+
+ with mock.patch(SESSION_PATCH, return_value=session):
+ assert validate_credentials(CREDENTIALS, API_VERSION) == (True, None)
+
+ assert session.api_calls[0]["url"] == f"{BASE_URL}/campaigns"
+ assert session.api_calls[0]["headers"]["X-AP-Context"] == "orgId=555"
+
+ def test_an_unusable_private_key_fails_before_any_request(self) -> None:
+ session = _FakeSession([])
+
+ with mock.patch(SESSION_PATCH, return_value=session):
+ is_valid, message = validate_credentials(_with_key("nope"), API_VERSION)
+
+ assert is_valid is False
+ assert message is not None and "private key" in message
+ assert session.calls == []
+
+ def test_a_token_endpoint_rejection_is_reported(self) -> None:
+ session = _FakeSession([], token_responses=[_FakeResponse(400, url=APPLE_OAUTH_TOKEN_URL)])
+
+ with mock.patch(SESSION_PATCH, return_value=session):
+ is_valid, message = validate_credentials(CREDENTIALS, API_VERSION)
+
+ assert is_valid is False
+ assert message is not None
+
+ def test_a_token_response_without_an_access_token_is_reported(self) -> None:
+ session = _FakeSession([], token_responses=[_FakeResponse(200, {}, url=APPLE_OAUTH_TOKEN_URL)])
+
+ with mock.patch(SESSION_PATCH, return_value=session):
+ is_valid, message = validate_credentials(CREDENTIALS, API_VERSION)
+
+ assert is_valid is False
+ assert message == "Apple's token response did not contain an access token"
+
+
+class TestClientBaseUrl:
+ @parameterized.expand([("v5", "v5"), ("pinned_older", "v4")])
+ def test_base_url_follows_the_resolved_api_version(self, _name: str, api_version: str) -> None:
+ with mock.patch(SESSION_PATCH, return_value=_FakeSession([])):
+ client = AppleSearchAdsClient(CREDENTIALS, api_version)
+
+ assert client.base_url == f"{APPLE_SEARCH_ADS_HOST}/api/{api_version}"
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/apple_search_ads/tests/test_apple_search_ads_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/apple_search_ads/tests/test_apple_search_ads_source.py
new file mode 100644
index 000000000000..26c3bd6788ef
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/apple_search_ads/tests/test_apple_search_ads_source.py
@@ -0,0 +1,201 @@
+from typing import Any, cast
+
+from unittest import mock
+
+from parameterized import parameterized
+
+from posthog.schema import (
+ DataWarehouseSourceCategory,
+ ReleaseStatus,
+ SourceFieldInputConfig,
+ SourceFieldInputConfigType,
+)
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.apple_search_ads.apple_search_ads import (
+ AppleSearchAdsCredentials,
+ AppleSearchAdsResumeConfig,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.apple_search_ads.canonical_descriptions import (
+ CANONICAL_DESCRIPTIONS,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.apple_search_ads.settings import (
+ APPLE_SEARCH_ADS_ENDPOINTS,
+ ENDPOINTS,
+ REPORT_LOOKBACK_SECONDS,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.apple_search_ads.source import (
+ AppleSearchAdsSource,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.applesearchads import (
+ AppleSearchAdsSourceConfig,
+)
+from products.warehouse_sources.backend.types import ExternalDataSourceType
+
+SOURCE_MODULE = "products.warehouse_sources.backend.temporal.data_imports.sources.apple_search_ads.source"
+
+REPORT_ENDPOINTS = tuple(name for name, config in APPLE_SEARCH_ADS_ENDPOINTS.items() if config.partition_key)
+ENTITY_ENDPOINTS = tuple(name for name, config in APPLE_SEARCH_ADS_ENDPOINTS.items() if not config.partition_key)
+
+
+class TestAppleSearchAdsSource:
+ def setup_method(self) -> None:
+ self.source = AppleSearchAdsSource()
+ self.team_id = 123
+ self.config = AppleSearchAdsSourceConfig(
+ org_id="555",
+ client_id="SEARCHADS.client",
+ apple_team_id="SEARCHADS.team",
+ key_id="key-1",
+ private_key="-----BEGIN PRIVATE KEY-----\nabc\n-----END PRIVATE KEY-----",
+ start_date="2026-01-01",
+ )
+
+ def test_source_type(self) -> None:
+ assert self.source.source_type == ExternalDataSourceType.APPLESEARCHADS
+
+ def test_get_source_config(self) -> None:
+ config = self.source.get_source_config
+
+ assert config.name.value == "AppleSearchAds"
+ assert config.label == "Apple Search Ads"
+ assert config.category == DataWarehouseSourceCategory.ADVERTISING
+ assert config.releaseStatus == ReleaseStatus.ALPHA
+ assert not config.unreleasedSource
+ assert config.iconPath == "/static/services/apple_search_ads.png"
+ assert config.docsUrl == "https://posthog.com/docs/cdp/sources/apple-search-ads"
+
+ @parameterized.expand(
+ [
+ ("org_id", SourceFieldInputConfigType.TEXT, True, False),
+ ("client_id", SourceFieldInputConfigType.TEXT, True, False),
+ ("apple_team_id", SourceFieldInputConfigType.TEXT, True, False),
+ ("key_id", SourceFieldInputConfigType.TEXT, True, False),
+ ("private_key", SourceFieldInputConfigType.TEXTAREA, True, True),
+ ("start_date", SourceFieldInputConfigType.TEXT, False, False),
+ ]
+ )
+ def test_source_fields(
+ self, name: str, field_type: SourceFieldInputConfigType, required: bool, secret: bool
+ ) -> None:
+ fields = {
+ field.name: field
+ for field in self.source.get_source_config.fields
+ if isinstance(field, SourceFieldInputConfig)
+ }
+
+ assert set(fields) == {"org_id", "client_id", "apple_team_id", "key_id", "private_key", "start_date"}
+ field = fields[name]
+ assert field.type == field_type
+ assert field.required is required
+ assert field.secret is secret
+
+ def test_api_version_metadata(self) -> None:
+ assert self.source.supported_versions == ("v5",)
+ assert self.source.default_version == "v5"
+ assert self.source.api_docs_url.startswith("https://")
+
+ def test_lists_tables_without_credentials(self) -> None:
+ # `get_schemas` walks a static catalog, so the public docs can render the table list.
+ assert self.source.lists_tables_without_credentials is True
+
+ def test_get_schemas_covers_the_endpoint_catalog(self) -> None:
+ schemas = self.source.get_schemas(self.config, self.team_id)
+
+ assert {schema.name for schema in schemas} == set(ENDPOINTS)
+ assert all(schema.description for schema in schemas)
+
+ def test_get_schemas_filters_by_name(self) -> None:
+ schemas = self.source.get_schemas(self.config, self.team_id, names=["campaigns", "campaign_report"])
+
+ assert {schema.name for schema in schemas} == {"campaigns", "campaign_report"}
+
+ @parameterized.expand([(endpoint,) for endpoint in REPORT_ENDPOINTS])
+ def test_report_tables_are_incremental_on_date_with_a_lookback(self, endpoint: str) -> None:
+ schema = next(s for s in self.source.get_schemas(self.config, self.team_id) if s.name == endpoint)
+
+ assert schema.supports_incremental is True
+ assert [f["field"] for f in schema.incremental_fields] == ["date"]
+ assert schema.default_incremental_lookback_seconds == REPORT_LOOKBACK_SECONDS
+ # The lookback re-reads already-imported days, so appending would duplicate them.
+ assert schema.supports_append is False
+
+ @parameterized.expand([(endpoint,) for endpoint in ENTITY_ENDPOINTS])
+ def test_entity_tables_are_full_refresh_only(self, endpoint: str) -> None:
+ schema = next(s for s in self.source.get_schemas(self.config, self.team_id) if s.name == endpoint)
+
+ # Apple's entity endpoints have no updated-since filter, so there is nothing to track.
+ assert schema.supports_incremental is False
+ assert schema.incremental_fields == []
+ assert schema.default_incremental_lookback_seconds is None
+
+ def test_canonical_descriptions_cover_every_endpoint(self) -> None:
+ descriptions = self.source.get_canonical_descriptions()
+
+ assert descriptions is CANONICAL_DESCRIPTIONS
+ assert set(descriptions) == set(ENDPOINTS)
+ for endpoint, entry in descriptions.items():
+ primary_keys = APPLE_SEARCH_ADS_ENDPOINTS[endpoint].primary_keys
+ assert set(primary_keys) <= set(entry.get("columns", {})), endpoint
+
+ @parameterized.expand([("unauthorized", 401), ("forbidden", 403)])
+ def test_non_retryable_errors_cover_auth_failures(self, _name: str, status: int) -> None:
+ errors = self.source.get_non_retryable_errors()
+
+ assert any(str(status) in key and "searchads.apple.com" in key for key in errors)
+ assert all(message for message in errors.values())
+
+ def test_validate_credentials_maps_the_config_onto_apple_credentials(self) -> None:
+ with mock.patch(f"{SOURCE_MODULE}.validate_apple_search_ads_credentials") as mock_validate:
+ mock_validate.return_value = (True, None)
+
+ assert self.source.validate_credentials(self.config, self.team_id) == (True, None)
+
+ credentials, api_version, schema_name = mock_validate.call_args.args
+ assert credentials == AppleSearchAdsCredentials(
+ org_id="555",
+ client_id="SEARCHADS.client",
+ team_id="SEARCHADS.team",
+ key_id="key-1",
+ private_key=self.config.private_key,
+ )
+ assert api_version == "v5"
+ assert schema_name is None
+
+ def test_validate_credentials_honors_a_pinned_api_version(self) -> None:
+ with mock.patch(f"{SOURCE_MODULE}.validate_apple_search_ads_credentials") as mock_validate:
+ mock_validate.return_value = (True, None)
+ self.source.validate_credentials(self.config, self.team_id, api_version="v4")
+
+ assert mock_validate.call_args.args[1] == "v4"
+
+ def test_get_resumable_source_manager_is_namespaced_per_schema(self) -> None:
+ inputs = mock.MagicMock()
+ inputs.schema_name = "campaign_report"
+
+ manager = self.source.get_resumable_source_manager(inputs)
+
+ assert isinstance(manager, ResumableSourceManager)
+ assert manager._data_class is AppleSearchAdsResumeConfig
+ # Entity and report checkpoints have incompatible shapes, so they must not share a slot.
+ assert manager._namespace == "campaign_report"
+
+ def test_source_for_pipeline_plumbs_arguments(self) -> None:
+ inputs = mock.MagicMock()
+ inputs.schema_name = "campaign_report"
+ inputs.should_use_incremental_field = True
+ inputs.db_incremental_field_last_value = "2026-05-01"
+ inputs.api_version = None
+ manager = mock.MagicMock()
+
+ with mock.patch(f"{SOURCE_MODULE}.apple_search_ads_source") as mock_source:
+ self.source.source_for_pipeline(self.config, manager, inputs)
+
+ kwargs = cast("dict[str, Any]", mock_source.call_args.kwargs)
+ assert kwargs["endpoint"] == "campaign_report"
+ assert kwargs["api_version"] == "v5"
+ assert kwargs["resumable_source_manager"] is manager
+ assert kwargs["should_use_incremental_field"] is True
+ assert kwargs["db_incremental_field_last_value"] == "2026-05-01"
+ assert kwargs["start_date"] == "2026-01-01"
+ assert kwargs["credentials"].org_id == "555"
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/applesearchads.py b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/applesearchads.py
index ba3110fef47d..a9daa4874c19 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/applesearchads.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/applesearchads.py
@@ -6,4 +6,9 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common imp
@config.config
class AppleSearchAdsSourceConfig(config.Config):
- pass
+ org_id: str
+ client_id: str
+ apple_team_id: str
+ key_id: str
+ private_key: str
+ start_date: str | None = None