:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(data-warehouse): implement app_store_connect source (#73756)
Tom Owers9a71aedccaf9
diff --git a/frontend/public/services/app_store_connect.png b/frontend/public/services/app_store_connect.pngindex 8965b5971e79..a91733b90e45 100644Binary files a/frontend/public/services/app_store_connect.png and b/frontend/public/services/app_store_connect.png differdiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.mdindex 3d8a1c897774..2619ca1510db 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md@@ -71,6 +71,7 @@ the row lists both.| apify_dataset | HTTP | requests | ✅ || apitally | HTTP | requests + `rest_source.RESTClient` | ✅ || apollo | HTTP | requests | ✅ |+| app_store_connect | HTTP | requests | ✅ || appdynamics | HTTP | requests | ✅ || appfigures | HTTP | requests | ✅ || appfollow | HTTP | requests | ✅ |@@ -734,7 +735,6 @@ doesn't conflict with concurrent PRs.- anodot_cost- anomalo- apaleo-- app_store_connect- appcues- appdirect- appfoliodiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/app_store_connect/app_store_connect.py b/products/warehouse_sources/backend/temporal/data_imports/sources/app_store_connect/app_store_connect.pynew file mode 100644index 000000000000..3ef9c8803386--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/app_store_connect/app_store_connect.py@@ -0,0 +1,564 @@+import io+import re+import csv+import gzip+import time+import dataclasses+from collections.abc import Iterator+from datetime import UTC, date, datetime, timedelta+from typing import Any, Optional+from urllib.parse import urlsplit++import jwt+import requests+from structlog.types import FilteringBoundLogger++from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import SourceResponse+from products.warehouse_sources.backend.temporal.data_imports.sources.app_store_connect.settings import (+ APP_STORE_CONNECT_ENDPOINTS,+ MAX_PAGE_SIZE,+ SALES_REPORT_END_OFFSET_DAYS,+ SALES_REPORT_LOOKBACK_DAYS,+ SALES_REPORT_MAX_DAYS_PER_RUN,+ AppStoreConnectEndpointConfig,+)+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++BASE_URL = "https://api.appstoreconnect.apple.com"+API_HOST = "api.appstoreconnect.apple.com"++# Apple rejects a token whose `exp` is more than 20 minutes past `iat`, so mint just under the ceiling+# and re-mint while a couple of minutes still remain.+JWT_AUDIENCE = "appstoreconnect-v1"+JWT_LIFETIME_SECONDS = 1140+JWT_REFRESH_MARGIN_SECONDS = 120++REQUEST_TIMEOUT_SECONDS = 60+# Report bodies are whole files rather than a page of JSON.+REPORT_TIMEOUT_SECONDS = 300+CREDENTIALS_TIMEOUT_SECONDS = 15++# `/v1/salesReports` returns a gzipped TSV, not JSON, and only for this Accept type.+REPORT_ACCEPT = "application/a-gzip"++# Hard cap on pages walked for one collection (or one app's collection) so a pagination bug can't scan+# forever. At 200 rows a page that is 400k rows.+MAX_PAGES_PER_RESOURCE = 2000++_PEM_HEADER = "-----BEGIN PRIVATE KEY-----"+_PEM_FOOTER = "-----END PRIVATE KEY-----"+_NON_ALNUM = re.compile(r"[^0-9a-z]+")+++class AppStoreConnectAuthError(Exception):+ """The .p8 private key, key ID, or issuer ID can't produce a signed token."""+++class AppStoreConnectUrlError(Exception):+ """A request or pagination URL points somewhere other than the App Store Connect API origin."""+++def _require_api_url(url: str) -> str:+ """Reject any URL that isn't ``https://api.appstoreconnect.apple.com`` on the default HTTPS port.++ ``links.next`` cursors from a response body and resume URLs loaded from persisted state are both+ attacker-influenceable: a tampered API response or a poisoned checkpoint could otherwise point the+ next request — which carries a freshly minted, replayable Apple bearer token — at an arbitrary host.+ Pinning every outbound request to Apple's origin makes a stray URL fail closed.+ """+ try:+ parts = urlsplit(url)+ except Exception as e:+ raise AppStoreConnectUrlError(f"Unparseable App Store Connect URL: {url!r}") from e++ if parts.scheme != "https" or parts.hostname != API_HOST or parts.port not in (None, 443):+ raise AppStoreConnectUrlError(f"Refusing to request a non-App Store Connect URL: {url!r}")+ return url+++class AppStoreConnectResumeConfig:+ # Fan-out bookmark: the app currently being walked. A stable Apple id rather than a positional+ # index, so apps added or removed between a crash and the retry can't resume into the wrong app.+ app_id: str | None = None+ # Fully-formed `links.next` URL (carries Apple's opaque cursor) for the collection being walked.+ next_url: str | None = None+ # Report streams bookmark: the next report date to fetch, as `YYYY-MM-DD`.+ report_date: str | None = None+++def _normalize_private_key(private_key: str) -> str:+ """Coerce a pasted App Store Connect .p8 key into PEM.++ Pastes arrive three ways: real PEM, PEM whose newlines were flattened into literal ``\\n``, or just+ the base64 body with the header and footer stripped off.+ """+ key = (private_key or "").strip().replace("\\n", "\n").replace("\r\n", "\n")+ if not key:+ raise AppStoreConnectAuthError("Add the contents of your App Store Connect .p8 private key file.")+ if "-----BEGIN" in key:+ return key++ body = "".join(key.split())+ lines = [body[index : index + 64] for index in range(0, len(body), 64)]+ return "\n".join([_PEM_HEADER, *lines, _PEM_FOOTER]) + "\n"+++class AppStoreConnectTokenProvider:+ """Mints and caches the short-lived ES256 JWT every App Store Connect request carries."""++ def __init__(self, issuer_id: str, key_id: str, private_key: str) -> None:+ self._issuer_id = issuer_id+ self._key_id = key_id+ self._private_key = _normalize_private_key(private_key)+ self._token: str | None = None+ self._expires_at: float = 0.0++ def token(self, force_refresh: bool = False) -> str:+ now = time.time()+ if force_refresh or self._token is None or now >= self._expires_at - JWT_REFRESH_MARGIN_SECONDS:+ self._token = self._mint(int(now))+ self._expires_at = now + JWT_LIFETIME_SECONDS+ return self._token++ def _mint(self, issued_at: int) -> str:+ payload: dict[str, Any] = {+ "iss": self._issuer_id,+ "iat": issued_at,+ "exp": issued_at + JWT_LIFETIME_SECONDS,+ "aud": JWT_AUDIENCE,+ }+ try:+ return jwt.encode(payload, self._private_key, algorithm="ES256", headers={"kid": self._key_id})+ except Exception as e:+ raise AppStoreConnectAuthError(+ "Could not sign a token with that private key. Paste the whole contents of the .p8 file "+ "you downloaded from App Store Connect, including the BEGIN and END lines."+ ) from e+++def _make_session(private_key: str) -> requests.Session:+ # The private key itself is never sent — only the signature it produces — but redact it so a future+ # change can't leak it into a captured sample. Redirects stay off so a 3xx can't quietly forward a+ # bearer-token-bearing request to another host; `_get` treats any redirect as a failure.+ return make_tracked_session(redact_values=(private_key,), allow_redirects=False)+++def _get(+ session: requests.Session,+ url: str,+ *,+ token_provider: AppStoreConnectTokenProvider,+ logger: FilteringBoundLogger,+ params: dict[str, Any] | None = None,+ accept: str = "application/json",+ timeout: int = REQUEST_TIMEOUT_SECONDS,+ tolerate: tuple[int, ...] = (),+) -> requests.Response:+ """GET with a freshly-valid token. 429 and transient 5xx are already retried by the tracked adapter."""++ # Pin the target to Apple's origin before attaching a token — covers freshly built URLs, `links.next`+ # cursors, and resume URLs alike, since every request funnels through here.+ _require_api_url(url)++ def _send(token: str) -> requests.Response:+ return session.get(+ url,+ params=params,+ headers={"Authorization": f"Bearer {token}", "Accept": accept},+ timeout=timeout,+ )++ response = _send(token_provider.token())+ if response.status_code == 401:+ # Tokens live 20 minutes and a long sync outlives one. Forcing a single re-mint separates a+ # merely stale token from a genuinely bad key, which stays a 401 and fails non-retryably.+ response = _send(token_provider.token(force_refresh=True))++ if 300 <= response.status_code < 400:+ # Redirects are pinned off on the session, so a 3xx is Apple's origin (or something posing as it)+ # trying to forward the request elsewhere. Fail closed rather than chase it with a live token.+ logger.error(f"App Store Connect unexpected redirect: status={response.status_code}, url={url}")+ raise AppStoreConnectUrlError(f"Unexpected redirect from App Store Connect: {url!r}")++ if response.status_code in tolerate:+ return response++ if not response.ok:+ logger.error(+ f"App Store Connect API error: status={response.status_code}, body={response.text[:500]}, url={url}"+ )+ response.raise_for_status()++ return response+++def _flatten_resource(resource: dict[str, Any]) -> dict[str, Any]:+ """Lift a JSON:API resource's ``attributes`` to the row root alongside its ``id`` and ``type``.++ ``relationships`` is dropped: it holds link envelopes rather than data, and the related rows are+ already available as their own tables.+ """+ attributes = resource.get("attributes")+ row: dict[str, Any] = dict(attributes) if isinstance(attributes, dict) else {}+ row["id"] = resource.get("id")+ row["type"] = resource.get("type")+ return row+++def _iter_pages(+ session: requests.Session,+ token_provider: AppStoreConnectTokenProvider,+ logger: FilteringBoundLogger,+ url: str,+ params: dict[str, Any] | None,+) -> Iterator[tuple[list[dict[str, Any]], str | None]]:+ """Walk a JSON:API collection, yielding each page's rows plus the next-page URL (``None`` at the end).++ ``params is None`` means ``url`` is already a fully-formed ``links.next`` — re-sending params there+ would duplicate the limit and cursor query args.+ """+ page_params: dict[str, Any] | None = {**params, "limit": MAX_PAGE_SIZE} if params is not None else None+ pages = 0++ while True:+ body = _get(session, url, token_provider=token_provider, logger=logger, params=page_params).json()+ data = body.get("data") if isinstance(body, dict) else None+ rows = [_flatten_resource(resource) for resource in (data or []) if isinstance(resource, dict)]++ links = body.get("links") if isinstance(body, dict) else None+ next_url = links.get("next") if isinstance(links, dict) else None++ pages += 1+ if pages >= MAX_PAGES_PER_RESOURCE and next_url:+ logger.warning(f"App Store Connect: page cap reached, truncating collection. url={url}, pages={pages}")+ next_url = None++ yield rows, next_url++ if not next_url:+ return++ url = next_url+ page_params = None+++def _load_resume(+ manager: ResumableSourceManager[AppStoreConnectResumeConfig],+) -> AppStoreConnectResumeConfig | None:+ return manager.load_state() if manager.can_resume() else None+++def _list_app_ids(+ session: requests.Session,+ token_provider: AppStoreConnectTokenProvider,+ logger: FilteringBoundLogger,+) -> list[str]:+ app_ids: list[str] = []+ for rows, _ in _iter_pages(session, token_provider, logger, f"{BASE_URL}/v1/apps", {}):+ app_ids.extend(str(row["id"]) for row in rows if row.get("id"))+ return app_ids+++def _get_collection(+ session: requests.Session,+ config: AppStoreConnectEndpointConfig,+ token_provider: AppStoreConnectTokenProvider,+ logger: FilteringBoundLogger,+ manager: ResumableSourceManager[AppStoreConnectResumeConfig],+) -> Iterator[list[dict[str, Any]]]:+ resume = _load_resume(manager)+ resumed_url = resume.next_url if resume is not None else None++ url = resumed_url or f"{BASE_URL}{config.path}"+ params: dict[str, Any] | None = None if resumed_url else dict(config.params)++ for rows, next_url in _iter_pages(session, token_provider, logger, url, params):+ if rows:+ yield rows+ # Save AFTER yielding so a crash re-fetches the page we just emitted rather than skipping it;+ # merge dedupes the re-pulled rows on the primary key.+ if next_url:+ manager.save_state(AppStoreConnectResumeConfig(next_url=next_url))+++def _get_app_fanout(+ session: requests.Session,+ config: AppStoreConnectEndpointConfig,+ token_provider: AppStoreConnectTokenProvider,+ logger: FilteringBoundLogger,+ manager: ResumableSourceManager[AppStoreConnectResumeConfig],+) -> Iterator[list[dict[str, Any]]]:+ app_ids = _list_app_ids(session, token_provider, logger)+ resume = _load_resume(manager)++ start = 0+ resumed_url: str | None = None+ if resume is not None and resume.app_id:+ index = next((i for i, app_id in enumerate(app_ids) if app_id == resume.app_id), None)+ # A bookmarked app that no longer exists restarts the fan-out; merge dedupes the re-pulled rows.+ if index is not None:+ start = index+ resumed_url = resume.next_url++ for position in range(start, len(app_ids)):+ app_id = app_ids[position]+ if position == start and resumed_url:+ url: str = resumed_url+ params: dict[str, Any] | None = None+ else:+ url = f"{BASE_URL}{config.path.format(app_id=app_id)}"+ params = dict(config.params)++ for rows, next_url in _iter_pages(session, token_provider, logger, url, params):+ if rows:+ for row in rows:+ row["app_id"] = app_id+ yield rows++ if next_url:+ manager.save_state(AppStoreConnectResumeConfig(app_id=app_id, next_url=next_url))+ elif position + 1 < len(app_ids):+ manager.save_state(AppStoreConnectResumeConfig(app_id=app_ids[position + 1]))+++def _to_date(value: Any) -> date | None:+ if value is None:+ return None+ if isinstance(value, datetime):+ aware = value if value.tzinfo is not None else value.replace(tzinfo=UTC)+ return aware.astimezone(UTC).date()+ if isinstance(value, date):+ return value+ try:+ return date.fromisoformat(str(value)[:10])+ except ValueError:+ return None+++def _normalize_report_column(name: str) -> str:+ """Turn an Apple report header (``Developer Proceeds``) into a column name (``developer_proceeds``)."""+ slug = _NON_ALNUM.sub("_", name.strip().lower()).strip("_")+ return slug or "column"+++def _decompress_report(payload: bytes) -> str:+ try:+ raw = gzip.decompress(payload)+ except (OSError, EOFError):+ # urllib3 already unwraps a `Content-Encoding: gzip` body, so the payload can arrive as plain TSV.+ raw = payload+ return raw.decode("utf-8-sig", errors="replace")+++def _parse_report(payload: bytes, report_date: date) -> list[dict[str, Any]]:+ reader = csv.reader(io.StringIO(_decompress_report(payload)), delimiter="\t")+ try:+ header = next(reader)+ except StopIteration:+ return []++ columns = [_normalize_report_column(column) for column in header]+ report_date_str = report_date.isoformat()+ rows: list[dict[str, Any]] = []++ for values in reader:+ if not any(value.strip() for value in values):+ continue+ row: dict[str, Any] = {+ column: (values[index] if index < len(values) else None) for index, column in enumerate(columns)+ }+ row["report_date"] = report_date_str+ # 1-based position in the file. A published day's report is immutable, so (report_date, _line)+ # is a stable unique key and re-reading a day merges instead of duplicating.+ row["_line"] = len(rows) + 1+ rows.append(row)++ return rows+++def _fetch_report(+ session: requests.Session,+ config: AppStoreConnectEndpointConfig,+ token_provider: AppStoreConnectTokenProvider,+ logger: FilteringBoundLogger,+ vendor_number: str,+ report_date: date,+) -> list[dict[str, Any]]:+ params: dict[str, str] = {+ "filter[frequency]": config.report_frequency,+ "filter[reportDate]": report_date.isoformat(),+ "filter[reportType]": config.report_type,+ "filter[reportSubType]": config.report_sub_type,+ "filter[vendorNumber]": vendor_number,+ }+ if config.report_version:+ params["filter[version]"] = config.report_version++ response = _get(+ session,+ f"{BASE_URL}/v1/salesReports",+ token_provider=token_provider,+ logger=logger,+ params=params,+ accept=REPORT_ACCEPT,+ timeout=REPORT_TIMEOUT_SECONDS,+ tolerate=(404,),+ )+ if response.status_code == 404:+ # Apple 404s any date with no activity at all — normal for quiet days and for dates before the+ # app shipped — so a missing day is not an error.+ return []++ return _parse_report(response.content, report_date)+++def _get_sales_report(+ session: requests.Session,+ config: AppStoreConnectEndpointConfig,+ token_provider: AppStoreConnectTokenProvider,+ logger: FilteringBoundLogger,+ manager: ResumableSourceManager[AppStoreConnectResumeConfig],+ vendor_number: str | None,+ should_use_incremental_field: bool,+ db_incremental_field_last_value: Any,+) -> Iterator[list[dict[str, Any]]]:+ if not vendor_number:+ raise ValueError(+ "Syncing App Store Connect sales reports needs your vendor number. "+ "Add it in the source settings, then run the sync again."+ )++ today = datetime.now(UTC).date()+ end = today - timedelta(days=SALES_REPORT_END_OFFSET_DAYS)+ start = today - timedelta(days=SALES_REPORT_LOOKBACK_DAYS)++ if should_use_incremental_field:+ watermark = _to_date(db_incremental_field_last_value)+ if watermark is not None:+ # Start on the watermark day itself rather than the day after: the file for a published day+ # never changes, so re-reading it merges idempotently and a half-written day self-heals.+ start = max(start, min(watermark, end))++ resume = _load_resume(manager)+ if resume is not None and resume.report_date:+ resumed = _to_date(resume.report_date)+ if resumed is not None and start <= resumed <= end:+ start = resumed++ report_date = start+ days_fetched = 0+ while report_date <= end and days_fetched < SALES_REPORT_MAX_DAYS_PER_RUN:+ rows = _fetch_report(session, config, token_provider, logger, vendor_number, report_date)+ if rows:+ yield rows++ days_fetched += 1+ report_date += timedelta(days=1)+ if report_date <= end:+ manager.save_state(AppStoreConnectResumeConfig(report_date=report_date.isoformat()))++ if report_date <= end:+ logger.info(+ f"App Store Connect: hit the per-run report day cap, resuming later. "+ f"endpoint={config.name}, next_report_date={report_date.isoformat()}"+ )+++def check_credentials(issuer_id: str, key_id: str, private_key: str) -> tuple[int | None, str | None]:+ """Probe ``/v1/apps`` with a minted token.++ Returns ``(http_status, message)``. The status is ``None`` when the request never left the process+ (a key we can't sign with, or a network failure), in which case ``message`` explains why when we know.+ """+ try:+ token_provider = AppStoreConnectTokenProvider(issuer_id, key_id, private_key)+ token = token_provider.token()+ except AppStoreConnectAuthError as e:+ return None, str(e)++ try:+ response = _make_session(private_key).get(+ f"{BASE_URL}/v1/apps",+ params={"limit": 1},+ headers={"Authorization": f"Bearer {token}", "Accept": "application/json"},+ timeout=CREDENTIALS_TIMEOUT_SECONDS,+ )+ return response.status_code, None+ except Exception:+ return None, None+++def get_rows(+ issuer_id: str,+ key_id: str,+ private_key: str,+ vendor_number: str | None,+ endpoint: str,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[AppStoreConnectResumeConfig],+ should_use_incremental_field: bool = False,+ db_incremental_field_last_value: Any = None,+) -> Iterator[list[dict[str, Any]]]:+ config = APP_STORE_CONNECT_ENDPOINTS[endpoint]+ session = _make_session(private_key)+ token_provider = AppStoreConnectTokenProvider(issuer_id, key_id, private_key)++ if config.kind == "collection":+ yield from _get_collection(session, config, token_provider, logger, resumable_source_manager)+ elif config.kind == "app_fanout":+ yield from _get_app_fanout(session, config, token_provider, logger, resumable_source_manager)+ else: # "sales_report"+ yield from _get_sales_report(+ session,+ config,+ token_provider,+ logger,+ resumable_source_manager,+ vendor_number,+ should_use_incremental_field,+ db_incremental_field_last_value,+ )++ # Walked to completion, so drop the checkpoint — leaving it would let a later attempt on this job+ # resume mid-stream instead of restarting cleanly.+ resumable_source_manager.clear_state()+++def app_store_connect_source(+ issuer_id: str,+ key_id: str,+ private_key: str,+ vendor_number: str | None,+ endpoint: str,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[AppStoreConnectResumeConfig],+ should_use_incremental_field: bool = False,+ db_incremental_field_last_value: Optional[Any] = None,+) -> SourceResponse:+ config = APP_STORE_CONNECT_ENDPOINTS[endpoint]++ return SourceResponse(+ name=endpoint,+ items=lambda: get_rows(+ issuer_id=issuer_id,+ key_id=key_id,+ private_key=private_key,+ vendor_number=vendor_number,+ endpoint=endpoint,+ logger=logger,+ resumable_source_manager=resumable_source_manager,+ should_use_incremental_field=should_use_incremental_field,+ db_incremental_field_last_value=db_incremental_field_last_value,+ ),+ primary_keys=config.primary_keys,+ 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,+ # Report streams walk dates oldest-first. Collections are full refreshes merged on a unique key,+ # so their page order doesn't affect the result either way.+ sort_mode="asc",+ )diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/app_store_connect/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/app_store_connect/canonical_descriptions.pynew file mode 100644index 000000000000..9e28bc2af280--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/app_store_connect/canonical_descriptions.py@@ -0,0 +1,226 @@+"""Canonical, documentation-sourced descriptions for App Store Connect endpoints and columns.++Sourced from Apple's App Store Connect API reference+(https://developer.apple.com/documentation/appstoreconnectapi). Keyed by the endpoint names in+`settings.py` `APP_STORE_CONNECT_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,+)++CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {+ "apps": {+ "description": "An app on the App Store, and the parent of the per-app version, review, purchase and subscription tables.",+ "docs_url": "https://developer.apple.com/documentation/appstoreconnectapi/app",+ "columns": {+ "id": "Apple's opaque identifier for the app.",+ "type": "JSON:API resource type, always `apps`.",+ "name": "Name of the app as it appears on the App Store.",+ "bundleId": "Bundle ID that uniquely identifies the app to Apple's systems.",+ "sku": "Developer-assigned SKU that also identifies the app in sales and financial reports.",+ "primaryLocale": "Default locale for the app's App Store information.",+ "isOrEverWasMadeForKids": "Whether the app is, or has ever been, part of the Kids category.",+ "subscriptionStatusUrl": "Server URL Apple notifies about subscription status changes.",+ "contentRightsDeclaration": "Whether the app contains, or has rights to use, third-party content.",+ "streamlinedPurchasingEnabled": "Whether streamlined in-app purchasing is enabled for the app.",+ },+ },+ "app_store_versions": {+ "description": "A version of an app submitted to the App Store, with its review and release state.",+ "docs_url": "https://developer.apple.com/documentation/appstoreconnectapi/appstoreversion",+ "columns": {+ "id": "Apple's opaque identifier for the version.",+ "type": "JSON:API resource type, always `appStoreVersions`.",+ "app_id": "Identifier of the app this version belongs to.",+ "platform": "Platform the version targets, such as IOS, MAC_OS or TV_OS.",+ "versionString": "Version number shown on the App Store, for example `2.4.1`.",+ "appVersionState": "Current state of the version in the submission and review flow.",+ "appStoreState": "Legacy state of the version on the App Store, superseded by appVersionState.",+ "copyright": "Copyright notice displayed on the App Store listing.",+ "reviewType": "Whether the version was submitted for App Store or TestFlight review.",+ "releaseType": "How the version is released once approved: MANUAL, AFTER_APPROVAL or SCHEDULED.",+ "earliestReleaseDate": "Earliest date the version may be released, for scheduled releases.",+ "downloadable": "Whether the version is available for download.",+ "createdDate": "When the version record was created.",+ },+ },+ "builds": {+ "description": "A build uploaded to App Store Connect for TestFlight or App Store release.",+ "docs_url": "https://developer.apple.com/documentation/appstoreconnectapi/build",+ "columns": {+ "id": "Apple's opaque identifier for the build.",+ "type": "JSON:API resource type, always `builds`.",+ "version": "Build number, unique within its pre-release version.",+ "uploadedDate": "When the build was uploaded to App Store Connect.",+ "expirationDate": "When the build stops being installable by testers.",+ "expired": "Whether the build has passed its expiration date.",+ "minOsVersion": "Minimum OS version the build supports.",+ "lsMinimumSystemVersion": "Minimum macOS version the build supports.",+ "computedMinMacOsVersion": "Minimum macOS version Apple computed for the build.",+ "iconAssetToken": "Token referencing the build's app icon asset.",+ "processingState": "Processing state of the build: PROCESSING, FAILED, INVALID or VALID.",+ "buildAudienceType": "Audience the build is available to, such as INTERNAL_ONLY or APP_STORE_ELIGIBLE.",+ "usesNonExemptEncryption": "Whether the build uses encryption that is not exempt from export rules.",+ },+ },+ "beta_groups": {+ "description": "A TestFlight group of beta testers, internal or external, with its public link settings.",+ "docs_url": "https://developer.apple.com/documentation/appstoreconnectapi/betagroup",+ "columns": {+ "id": "Apple's opaque identifier for the beta group.",+ "type": "JSON:API resource type, always `betaGroups`.",+ "name": "Name of the beta group.",+ "createdDate": "When the group was created.",+ "isInternalGroup": "Whether the group contains internal testers from your team.",+ "publicLinkEnabled": "Whether a public TestFlight link is enabled for the group.",+ "publicLinkId": "Identifier embedded in the group's public TestFlight link.",+ "publicLink": "Public TestFlight link testers use to join the group.",+ "publicLinkLimitEnabled": "Whether the number of testers joining via the public link is capped.",+ "publicLinkLimit": "Maximum number of testers who may join via the public link.",+ "feedbackEnabled": "Whether testers in the group can send feedback.",+ "hasAccessToAllBuilds": "Whether the group automatically receives every new build.",+ },+ },+ "customer_reviews": {+ "description": "A customer review left on the App Store, including its star rating and territory.",+ "docs_url": "https://developer.apple.com/documentation/appstoreconnectapi/customerreview",+ "columns": {+ "id": "Apple's opaque identifier for the review.",+ "type": "JSON:API resource type, always `customerReviews`.",+ "app_id": "Identifier of the app the review was left on.",+ "rating": "Star rating the customer gave, from 1 to 5.",+ "title": "Title the customer gave the review.",+ "body": "Body text of the review.",+ "reviewerNickname": "Display name of the customer who left the review.",+ "createdDate": "When the review was submitted.",+ "territory": "App Store territory the review was written in.",+ },+ },+ "in_app_purchases": {+ "description": "An in-app purchase product configured for an app.",+ "docs_url": "https://developer.apple.com/documentation/appstoreconnectapi/inapppurchasev2",+ "columns": {+ "id": "Apple's opaque identifier for the in-app purchase.",+ "type": "JSON:API resource type, always `inAppPurchases`.",+ "app_id": "Identifier of the app the product belongs to.",+ "name": "Reference name of the in-app purchase, visible only in App Store Connect.",+ "productId": "Product ID your app uses to request the purchase from the App Store.",+ "inAppPurchaseType": "Kind of product: CONSUMABLE, NON_CONSUMABLE or NON_RENEWING_SUBSCRIPTION.",+ "state": "Review and availability state of the product.",+ "reviewNote": "Note supplied to App Review about the product.",+ "familySharable": "Whether the purchase can be shared through Family Sharing.",+ "contentHosting": "Whether Apple hosts the product's downloadable content.",+ },+ },+ "subscription_groups": {+ "description": "A group of auto-renewable subscriptions within an app that customers can move between.",+ "docs_url": "https://developer.apple.com/documentation/appstoreconnectapi/subscriptiongroup",+ "columns": {+ "id": "Apple's opaque identifier for the subscription group.",+ "type": "JSON:API resource type, always `subscriptionGroups`.",+ "app_id": "Identifier of the app the group belongs to.",+ "referenceName": "Name of the group, visible only in App Store Connect.",+ },+ },+ "sales_reports": {+ "description": "One row of Apple's daily Sales and Trends summary report: units and developer proceeds per SKU, territory and product type.",+ "docs_url": "https://developer.apple.com/documentation/appstoreconnectapi/download_sales_and_trends_reports",+ "columns": {+ "report_date": "Date the report covers, as `YYYY-MM-DD`.",+ "_line": "1-based line number within that date's report file, used with report_date as the row key.",+ "provider": "Provider of the content, normally `APPLE`.",+ "provider_country": "Country of the provider.",+ "sku": "SKU of the app or in-app purchase the row covers.",+ "developer": "Name of the developer credited for the sale.",+ "title": "Name of the app the row covers.",+ "version": "Version of the app the transaction applied to.",+ "product_type_identifier": "Code describing the transaction type, such as a first download, update or in-app purchase.",+ "units": "Number of units for this row; negative values are refunds.",+ "developer_proceeds": "Amount paid to you per unit, in the currency of proceeds.",+ "begin_date": "First date covered by the row.",+ "end_date": "Last date covered by the row.",+ "customer_currency": "Currency the customer was charged in.",+ "country_code": "App Store territory the transaction happened in.",+ "currency_of_proceeds": "Currency your proceeds are reported in.",+ "apple_identifier": "Apple's numeric identifier for the app.",+ "customer_price": "Price the customer paid, in customer currency.",+ "promo_code": "Promotional or offer code applied to the transaction.",+ "parent_identifier": "SKU of the parent app for an in-app purchase row.",+ "subscription": "Whether the row relates to a subscription product.",+ "period": "Subscription period the row covers.",+ "category": "App Store category of the app.",+ "cmb": "Whether the transaction came through a carrier-billing arrangement.",+ "device": "Device family the transaction came from.",+ "supported_platforms": "Platforms the app supports.",+ "proceeds_reason": "Reason the applied proceeds rate was used.",+ "preserved_pricing": "Whether legacy preserved pricing applied to the transaction.",+ "client": "Client the purchase was made from, such as the App Store app.",+ "order_type": "Whether the purchase was a normal purchase or a pre-order.",+ },+ },+ "subscription_reports": {+ "description": "One row of Apple's daily Subscription summary report: active, paid and trial subscription counts by state and territory.",+ "docs_url": "https://developer.apple.com/documentation/appstoreconnectapi/download_sales_and_trends_reports",+ "columns": {+ "report_date": "Date the report covers, as `YYYY-MM-DD`.",+ "_line": "1-based line number within that date's report file, used with report_date as the row key.",+ "app_name": "Name of the app the subscription belongs to.",+ "app_apple_id": "Apple's numeric identifier for the app.",+ "subscription_name": "Name of the subscription product.",+ "subscription_apple_id": "Apple's numeric identifier for the subscription product.",+ "subscription_group_id": "Identifier of the subscription group the product belongs to.",+ "standard_subscription_duration": "Billing duration of the subscription, such as 1 Month.",+ "promotional_offer_name": "Name of the promotional offer applied, if any.",+ "promotional_offer_id": "Identifier of the promotional offer applied, if any.",+ "customer_price": "Price the customer pays per period, in customer currency.",+ "customer_currency": "Currency the customer is charged in.",+ "developer_proceeds": "Proceeds paid to you per period.",+ "proceeds_currency": "Currency your proceeds are reported in.",+ "preserved_pricing": "Whether legacy preserved pricing applies.",+ "proceeds_reason": "Reason the applied proceeds rate was used.",+ "client": "Client the subscription was purchased from.",+ "device": "Device family the subscription was purchased on.",+ "state": "State of the subscription, such as active, in a grace period, or in billing retry.",+ "country": "App Store territory the subscriptions are counted in.",+ "subscribers": "Number of subscribers in this state on the report date.",+ },+ },+ "subscription_event_reports": {+ "description": "One row of Apple's daily Subscription Event report: counts of subscription lifecycle events such as renewals, cancellations and plan changes.",+ "docs_url": "https://developer.apple.com/documentation/appstoreconnectapi/download_sales_and_trends_reports",+ "columns": {+ "report_date": "Date the report covers, as `YYYY-MM-DD`.",+ "_line": "1-based line number within that date's report file, used with report_date as the row key.",+ "event_date": "Date the events happened.",+ "event": "Lifecycle event counted, such as Subscribe, Renew, Cancel or Reactivate.",+ "app_name": "Name of the app the subscription belongs to.",+ "app_apple_id": "Apple's numeric identifier for the app.",+ "subscription_name": "Name of the subscription product.",+ "subscription_apple_id": "Apple's numeric identifier for the subscription product.",+ "subscription_group_id": "Identifier of the subscription group the product belongs to.",+ "standard_subscription_duration": "Billing duration of the subscription, such as 1 Month.",+ "promotional_offer_name": "Name of the promotional offer involved, if any.",+ "promotional_offer_id": "Identifier of the promotional offer involved, if any.",+ "subscription_offer_type": "Type of offer involved, such as an introductory or promotional offer.",+ "subscription_offer_duration": "Duration of the offer involved.",+ "marketing_opt_in": "Whether the customer opted in to marketing communication.",+ "marketing_opt_in_duration": "Duration of the marketing opt-in offer.",+ "preserved_pricing": "Whether legacy preserved pricing applies.",+ "proceeds_reason": "Reason the applied proceeds rate was used.",+ "consecutive_paid_periods": "Number of consecutive paid periods before the event.",+ "original_start_date": "Date the customer first started the subscription.",+ "client": "Client the event originated from.",+ "device": "Device family the event originated from.",+ "state": "State of the subscription at the time of the event.",+ "previous_subscription_name": "Name of the subscription the customer moved from, for plan changes.",+ "previous_subscription_apple_id": "Identifier of the subscription the customer moved from.",+ "days_before_canceling": "Days between subscribing and cancelling, for cancellation events.",+ "cancellation_reason": "Reason recorded for the cancellation.",+ "days_canceled": "Days the subscription had been cancelled before a reactivation.",+ "quantity": "Number of subscriptions the row counts.",+ "country": "App Store territory the events are counted in.",+ },+ },+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/app_store_connect/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/app_store_connect/settings.pynew file mode 100644index 000000000000..0b4c10aa9d00--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/app_store_connect/settings.py@@ -0,0 +1,164 @@+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++# App Store Connect splits into two very different transports, so the catalog carries three kinds:+#+# - "collection": a top-level JSON:API list (`/v1/apps`, `/v1/builds`, ...) walked via `links.next`.+# - "app_fanout": a per-app JSON:API list (`/v1/apps/{app_id}/customerReviews`, ...). Apps are+# discovered from `/v1/apps` first, then each app's collection is walked.+# - "sales_report": `/v1/salesReports`, which is not a collection at all — one request per report date+# returns a gzipped TSV file. Walked forward a day at a time from the watermark.+EndpointKind = Literal["collection", "app_fanout", "sales_report"]++# Apple caps most collection pages at 200 resources.+MAX_PAGE_SIZE = 200++# Daily sales/subscription reports are only retained for about a year, so a first sync walks back this+# far rather than to the App Store's launch. Each day is one request, so this also bounds the backfill.+SALES_REPORT_LOOKBACK_DAYS = 365++# Days of reports fetched in a single run. A run that hits the cap resumes from its bookmark next time,+# which keeps a cold-start backfill inside the hourly request budget (~3,500 requests per key).+SALES_REPORT_MAX_DAYS_PER_RUN = 400++# Reports for a given day only publish once Apple closes it out, so the newest date we ask for is+# yesterday (UTC). Asking for today reliably 404s.+SALES_REPORT_END_OFFSET_DAYS = 1+++@dataclass+class AppStoreConnectEndpointConfig:+ name: str+ kind: EndpointKind+ primary_keys: list[str]+ # JSON:API path. `app_fanout` paths carry a single `{app_id}` placeholder.+ path: str = ""+ # Extra query params. Only set `sort` where Apple documents the value for that specific resource —+ # an unsupported sort is a hard 400, and every collection here is a full refresh merged on a unique+ # primary key, so page order doesn't affect correctness.+ params: dict[str, str] = field(default_factory=dict)+ incremental_fields: list[IncrementalField] = field(default_factory=list)+ # Stable creation-style field to partition by — never an updated/modified field.+ partition_key: Optional[str] = None+ should_sync_default: bool = True+ # `/v1/salesReports` filters, only meaningful for the "sales_report" kind.+ report_type: str = ""+ report_sub_type: str = ""+ # Apple versions each report layout independently; these are the current documented versions for+ # the DAILY/SUMMARY combination of each report type.+ report_version: str = ""+ report_frequency: str = "DAILY"+++_REPORT_DATE_FIELD: IncrementalField = incremental_field("report_date", IncrementalFieldType.Date)+++APP_STORE_CONNECT_ENDPOINTS: dict[str, AppStoreConnectEndpointConfig] = {+ # The app inventory, and the parent every fan-out endpoint iterates. App attributes carry no+ # timestamp, so there is nothing to partition on.+ "apps": AppStoreConnectEndpointConfig(+ name="apps",+ kind="collection",+ primary_keys=["id"],+ path="/v1/apps",+ ),+ # Every version record per app — release type, review state, release dates.+ "app_store_versions": AppStoreConnectEndpointConfig(+ name="app_store_versions",+ kind="app_fanout",+ primary_keys=["app_id", "id"],+ path="/v1/apps/{app_id}/appStoreVersions",+ partition_key="createdDate",+ ),+ # Uploaded builds across the account. `uploadedDate` is a documented sort value here.+ "builds": AppStoreConnectEndpointConfig(+ name="builds",+ kind="collection",+ primary_keys=["id"],+ path="/v1/builds",+ params={"sort": "uploadedDate"},+ partition_key="uploadedDate",+ ),+ # TestFlight groups.+ "beta_groups": AppStoreConnectEndpointConfig(+ name="beta_groups",+ kind="collection",+ primary_keys=["id"],+ path="/v1/betaGroups",+ partition_key="createdDate",+ ),+ # Reviews and ratings per app. Apple exposes `sort=createdDate` but no `createdDate` filter, so an+ # "incremental" sync would still have to walk every page — this stays a full refresh.+ "customer_reviews": AppStoreConnectEndpointConfig(+ name="customer_reviews",+ kind="app_fanout",+ primary_keys=["app_id", "id"],+ path="/v1/apps/{app_id}/customerReviews",+ params={"sort": "createdDate"},+ partition_key="createdDate",+ ),+ # In-app purchase catalog per app.+ "in_app_purchases": AppStoreConnectEndpointConfig(+ name="in_app_purchases",+ kind="app_fanout",+ primary_keys=["app_id", "id"],+ path="/v1/apps/{app_id}/inAppPurchasesV2",+ ),+ # Subscription groups per app.+ "subscription_groups": AppStoreConnectEndpointConfig(+ name="subscription_groups",+ kind="app_fanout",+ primary_keys=["app_id", "id"],+ path="/v1/apps/{app_id}/subscriptionGroups",+ ),+ # Daily units and proceeds. Off by default because it needs a vendor number and a Finance or Sales+ # role on the key. Keyed on (report date, line number): a published day's file is immutable, so the+ # pair is stable and unique, and re-reading a day merges cleanly.+ "sales_reports": AppStoreConnectEndpointConfig(+ name="sales_reports",+ kind="sales_report",+ primary_keys=["report_date", "_line"],+ report_type="SALES",+ report_sub_type="SUMMARY",+ report_version="1_0",+ incremental_fields=[_REPORT_DATE_FIELD],+ partition_key="report_date",+ should_sync_default=False,+ ),+ # Daily active subscription counts by state and territory.+ "subscription_reports": AppStoreConnectEndpointConfig(+ name="subscription_reports",+ kind="sales_report",+ primary_keys=["report_date", "_line"],+ report_type="SUBSCRIPTION",+ report_sub_type="SUMMARY",+ report_version="1_4",+ incremental_fields=[_REPORT_DATE_FIELD],+ partition_key="report_date",+ should_sync_default=False,+ ),+ # Daily subscription lifecycle events (renewals, cancellations, upgrades).+ "subscription_event_reports": AppStoreConnectEndpointConfig(+ name="subscription_event_reports",+ kind="sales_report",+ primary_keys=["report_date", "_line"],+ report_type="SUBSCRIPTION_EVENT",+ report_sub_type="SUMMARY",+ report_version="1_4",+ incremental_fields=[_REPORT_DATE_FIELD],+ partition_key="report_date",+ should_sync_default=False,+ ),+}++ENDPOINTS = tuple(APP_STORE_CONNECT_ENDPOINTS.keys())++# Endpoints that read `/v1/salesReports` and therefore need a vendor number.+REPORT_ENDPOINTS = tuple(name for name, config in APP_STORE_CONNECT_ENDPOINTS.items() if config.kind == "sales_report")++INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {+ name: config.incremental_fields for name, config in APP_STORE_CONNECT_ENDPOINTS.items()+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/app_store_connect/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/app_store_connect/source.pyindex e8d548ade39b..770192bf48dc 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/app_store_connect/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/app_store_connect/source.py@@ -1,21 +1,55 @@-from typing import cast+from typing import Optional, castfrom posthog.schema import (DataWarehouseSourceCategory,ExternalDataSourceType as SchemaExternalDataSourceType,+ ReleaseStatus,SourceConfig,+ SourceFieldInputConfig,+ SourceFieldInputConfigType,)-from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, SimpleSource+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import (+ SourceInputs,+ SourceResponse,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.app_store_connect.app_store_connect import (+ AppStoreConnectResumeConfig,+ app_store_connect_source,+ check_credentials,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.app_store_connect.settings import (+ APP_STORE_CONNECT_ENDPOINTS,+ ENDPOINTS,+ INCREMENTAL_FIELDS,+ REPORT_ENDPOINTS,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, ResumableSource+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (+ CanonicalDescriptions,+)from products.warehouse_sources.backend.temporal.data_imports.sources.common.registry import SourceRegistry+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from products.warehouse_sources.backend.temporal.data_imports.sources.common.schema import (+ SourceSchema,+ build_endpoint_schemas,+)from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.appstoreconnect import (AppStoreConnectSourceConfig,)from products.warehouse_sources.backend.types import ExternalDataSourceType+_MISSING_VENDOR_NUMBER = (+ "Add your vendor number in the source settings to sync sales and subscription reports. "+ "You can find it in App Store Connect under Payments and Financial Reports."+)+@SourceRegistry.register-class AppStoreConnectSource(SimpleSource[AppStoreConnectSourceConfig]):+class AppStoreConnectSource(ResumableSource[AppStoreConnectSourceConfig, AppStoreConnectResumeConfig]):+ lists_tables_without_credentials = True # static endpoint catalog — safe for public docs+ api_docs_url = "https://developer.apple.com/documentation/appstoreconnectapi"+@propertydef source_type(self) -> ExternalDataSourceType:return ExternalDataSourceType.APPSTORECONNECT@@ -26,7 +60,147 @@ class AppStoreConnectSource(SimpleSource[AppStoreConnectSourceConfig]):name=SchemaExternalDataSourceType.APP_STORE_CONNECT,category=DataWarehouseSourceCategory.ANALYTICS,label="Apple (App Store Connect)",+ releaseStatus=ReleaseStatus.ALPHA,+ keywords=["app store", "ios", "apple", "mobile analytics"],+ caption="""Pull your App Store apps, versions, builds, reviews and sales reports into the PostHog Data warehouse.++An Account Holder or Admin creates an API key under **Users and Access → Integrations → App Store Connect API** in App Store Connect. Copy the issuer ID and key ID from that page, then paste the contents of the `.p8` private key file you download. Apple only lets you download that file once, so keep a copy.++Sales and subscription reports also need your vendor number (App Store Connect → **Payments and Financial Reports**) and a key with the Finance, Sales, or Admin role. Leave it blank if you only want app, review and build data.""",iconPath="/static/services/app_store_connect.png",- fields=cast(list[FieldType], []),- unreleasedSource=True,+ docsUrl="https://posthog.com/docs/cdp/sources/app-store-connect",+ fields=cast(+ list[FieldType],+ [+ SourceFieldInputConfig(+ name="issuer_id",+ label="Issuer ID",+ type=SourceFieldInputConfigType.TEXT,+ required=True,+ placeholder="57246542-96fe-1a63-e053-0824d011072a",+ secret=False,+ ),+ SourceFieldInputConfig(+ name="key_id",+ label="Key ID",+ type=SourceFieldInputConfigType.TEXT,+ required=True,+ placeholder="2X9R4HXF34",+ secret=False,+ ),+ SourceFieldInputConfig(+ name="private_key",+ label="Private key (.p8 contents)",+ type=SourceFieldInputConfigType.TEXTAREA,+ required=True,+ placeholder="-----BEGIN PRIVATE KEY-----",+ secret=True,+ ),+ SourceFieldInputConfig(+ name="vendor_number",+ label="Vendor number (optional)",+ type=SourceFieldInputConfigType.TEXT,+ required=False,+ placeholder="85234567",+ secret=False,+ ),+ ],+ ),+ )++ def get_canonical_descriptions(self) -> CanonicalDescriptions:+ from products.warehouse_sources.backend.temporal.data_imports.sources.app_store_connect.canonical_descriptions import (+ CANONICAL_DESCRIPTIONS,+ )++ return CANONICAL_DESCRIPTIONS++ def get_non_retryable_errors(self) -> dict[str, str | None]:+ # Match the stable status text plus the base host, not the per-request path and cursor.+ return {+ "401 Client Error: Unauthorized for url: https://api.appstoreconnect.apple.com": "App Store Connect rejected your API key. Check the issuer ID, key ID and private key, or generate a new key, then reconnect.",+ "403 Client Error: Forbidden for url: https://api.appstoreconnect.apple.com": "Your App Store Connect API key does not have access to this data. Give the key a role that can read it (Finance or Sales for reports), then reconnect.",+ }++ def get_schemas(+ self,+ config: AppStoreConnectSourceConfig,+ 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,+ should_sync_default={+ name: endpoint.should_sync_default for name, endpoint in APP_STORE_CONNECT_ENDPOINTS.items()+ },+ )+ for schema in schemas:+ schema.detected_primary_keys = APP_STORE_CONNECT_ENDPOINTS[schema.name].primary_keys+ return schemas++ def get_endpoint_permissions(+ self,+ config: AppStoreConnectSourceConfig,+ team_id: int,+ endpoints: list[str],+ api_version: str | None = None,+ ) -> dict[str, str | None]:+ # The report endpoints can't be read at all without a vendor number, so flag them in the picker+ # instead of letting the user select a table that will fail at sync time.+ if config.vendor_number:+ return dict.fromkeys(endpoints)+ return {name: (_MISSING_VENDOR_NUMBER if name in REPORT_ENDPOINTS else None) for name in endpoints}++ def validate_credentials(+ self,+ config: AppStoreConnectSourceConfig,+ team_id: int,+ schema_name: Optional[str] = None,+ api_version: str | None = None,+ ) -> tuple[bool, str | None]:+ if schema_name in REPORT_ENDPOINTS and not config.vendor_number:+ return False, _MISSING_VENDOR_NUMBER++ status, message = check_credentials(config.issuer_id, config.key_id, config.private_key)++ if status is None:+ return False, message or "Could not reach App Store Connect. Please try again."+ if status == 401:+ return False, "App Store Connect rejected your API key. Check the issuer ID, key ID and private key."+ if status == 403 and schema_name is None:+ # A valid key whose role can't read `/v1/apps` is still a real key — the per-table check+ # reports what it can't reach, so don't block source creation on it.+ return True, None+ if status == 403:+ return False, "Your App Store Connect API key does not have permission to read this data."+ if status == 200:+ return True, None+ return False, f"App Store Connect returned status {status}"++ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[AppStoreConnectResumeConfig]:+ return ResumableSourceManager[AppStoreConnectResumeConfig](inputs, AppStoreConnectResumeConfig)++ def source_for_pipeline(+ self,+ config: AppStoreConnectSourceConfig,+ resumable_source_manager: ResumableSourceManager[AppStoreConnectResumeConfig],+ inputs: SourceInputs,+ ) -> SourceResponse:+ return app_store_connect_source(+ issuer_id=config.issuer_id,+ key_id=config.key_id,+ private_key=config.private_key,+ vendor_number=config.vendor_number,+ endpoint=inputs.schema_name,+ logger=inputs.logger,+ resumable_source_manager=resumable_source_manager,+ should_use_incremental_field=inputs.should_use_incremental_field,+ db_incremental_field_last_value=inputs.db_incremental_field_last_value+ if inputs.should_use_incremental_field+ else None,)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/app_store_connect/tests/test_app_store_connect.py b/products/warehouse_sources/backend/temporal/data_imports/sources/app_store_connect/tests/test_app_store_connect.pynew file mode 100644index 000000000000..eceb06aab2fc--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/app_store_connect/tests/test_app_store_connect.py@@ -0,0 +1,685 @@+import gzip+from datetime import date, timedelta+from typing import Any++import pytest+from freezegun import freeze_time+from unittest.mock import MagicMock, patch++import jwt+from cryptography.hazmat.primitives import serialization+from cryptography.hazmat.primitives.asymmetric import ec+from parameterized import parameterized++from products.warehouse_sources.backend.temporal.data_imports.sources.app_store_connect.app_store_connect import (+ BASE_URL,+ JWT_AUDIENCE,+ JWT_LIFETIME_SECONDS,+ AppStoreConnectAuthError,+ AppStoreConnectResumeConfig,+ AppStoreConnectTokenProvider,+ AppStoreConnectUrlError,+ _flatten_resource,+ _get,+ _normalize_private_key,+ _normalize_report_column,+ _parse_report,+ _require_api_url,+ app_store_connect_source,+ check_credentials,+ get_rows,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.app_store_connect.settings import (+ APP_STORE_CONNECT_ENDPOINTS,+ ENDPOINTS,+ SALES_REPORT_LOOKBACK_DAYS,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager++MODULE = "products.warehouse_sources.backend.temporal.data_imports.sources.app_store_connect.app_store_connect"+++def _make_pem() -> str:+ key = ec.generate_private_key(ec.SECP256R1())+ return key.private_bytes(+ encoding=serialization.Encoding.PEM,+ format=serialization.PrivateFormat.PKCS8,+ encryption_algorithm=serialization.NoEncryption(),+ ).decode()+++PRIVATE_KEY_PEM = _make_pem()+++class _FakeManager(ResumableSourceManager[AppStoreConnectResumeConfig]):+ """Minimal stand-in for ResumableSourceManager that records saved state in memory."""++ def __init__(self, state: AppStoreConnectResumeConfig | None = None) -> None:+ self._state = state+ self.saved: list[AppStoreConnectResumeConfig] = []+ self.cleared = 0++ def can_resume(self) -> bool:+ return self._state is not None++ def load_state(self) -> AppStoreConnectResumeConfig | None:+ return self._state++ def save_state(self, data: AppStoreConnectResumeConfig) -> None:+ self.saved.append(data)++ def clear_state(self) -> None:+ self.cleared += 1+++class _FakeTokenProvider(AppStoreConnectTokenProvider):+ """Hands out a new token string every time a refresh is forced, so re-mints are observable."""++ def __init__(self) -> None:+ self.calls: list[bool] = []+ self._generation = 0++ def token(self, force_refresh: bool = False) -> str:+ self.calls.append(force_refresh)+ if force_refresh:+ self._generation += 1+ return f"token-{self._generation}"+++def _json_response(body: dict[str, Any], status_code: int = 200) -> MagicMock:+ response = MagicMock()+ response.status_code = status_code+ response.ok = 200 <= status_code < 300+ response.json.return_value = body+ response.text = ""+ return response+++def _report_response(tsv: str | None, missing_status_code: int = 404) -> MagicMock:+ """A gzipped-TSV report response, or the 404 Apple returns for a date with no activity."""+ response = MagicMock()+ if tsv is None:+ response.status_code = missing_status_code+ response.ok = False+ response.text = '{"errors":[{"code":"NOT_FOUND"}]}'+ return response+ response.status_code = 200+ response.ok = True+ response.content = gzip.compress(tsv.encode())+ return response+++def _resource(resource_type: str, resource_id: str, **attributes: Any) -> dict[str, Any]:+ return {+ "type": resource_type,+ "id": resource_id,+ "attributes": attributes,+ "relationships": {"app": {"links": {"related": "https://example.test"}}},+ }+++def _page(resources: list[dict[str, Any]], next_url: str | None = None) -> dict[str, Any]:+ body: dict[str, Any] = {"data": resources, "meta": {"paging": {"total": len(resources)}}}+ if next_url:+ body["links"] = {"next": next_url}+ return body+++class _FakeApi:+ """Routes JSON:API requests by URL to a canned body, recording every (url, params) pair."""++ def __init__(self, bodies: dict[str, dict[str, Any]]) -> None:+ self.bodies = bodies+ self.calls: list[tuple[str, Any]] = []++ def get(self, url: str, **kwargs: Any) -> MagicMock:+ self.calls.append((url, kwargs.get("params")))+ if url not in self.bodies:+ raise AssertionError(f"unexpected url {url}")+ return _json_response(self.bodies[url])+++class _FakeReportApi:+ """Serves `/v1/salesReports` per requested report date; an unknown date 404s like Apple's does."""++ def __init__(self, tsv_by_date: dict[str, str]) -> None:+ self.tsv_by_date = tsv_by_date+ self.calls: list[tuple[str, dict[str, Any]]] = []++ def get(self, url: str, **kwargs: Any) -> MagicMock:+ params: dict[str, Any] = kwargs.get("params") or {}+ self.calls.append((url, params))+ return _report_response(self.tsv_by_date.get(params["filter[reportDate]"]))+++def _collect(+ endpoint: str,+ api: _FakeApi | _FakeReportApi,+ manager: _FakeManager,+ *,+ vendor_number: str | None = None,+ **kwargs: Any,+) -> list[dict[str, Any]]:+ session = MagicMock()+ session.get.side_effect = api.get+ rows: list[dict[str, Any]] = []+ with patch(f"{MODULE}._make_session", return_value=session):+ for batch in get_rows(+ issuer_id="issuer",+ key_id="KEY123",+ private_key=PRIVATE_KEY_PEM,+ vendor_number=vendor_number,+ endpoint=endpoint,+ logger=MagicMock(),+ resumable_source_manager=manager,+ **kwargs,+ ):+ rows.extend(batch)+ return rows+++class TestNormalizePrivateKey:+ def test_pem_is_passed_through_unchanged(self) -> None:+ assert _normalize_private_key(f"\n {PRIVATE_KEY_PEM} \n") == PRIVATE_KEY_PEM.strip()++ def test_escaped_newlines_are_restored(self) -> None:+ flattened = PRIVATE_KEY_PEM.strip().replace("\n", "\\n")+ assert _normalize_private_key(flattened) == PRIVATE_KEY_PEM.strip()++ def test_bare_base64_body_is_wrapped_in_pem(self) -> None:+ body = "".join(line for line in PRIVATE_KEY_PEM.splitlines() if "-----" not in line)+ rebuilt = _normalize_private_key(body)+ assert rebuilt.startswith("-----BEGIN PRIVATE KEY-----\n")+ assert rebuilt.rstrip().endswith("-----END PRIVATE KEY-----")+ # A wrapped key must still be loadable, otherwise the convenience is a foot-gun.+ serialization.load_pem_private_key(rebuilt.encode(), password=None)++ @parameterized.expand([("empty", ""), ("whitespace", " \n ")])+ def test_missing_key_raises(self, _name: str, value: str) -> None:+ with pytest.raises(AppStoreConnectAuthError):+ _normalize_private_key(value)+++class TestTokenProvider:+ def test_mints_es256_token_with_key_id_and_apple_claims(self) -> None:+ with freeze_time("2026-03-04 10:00:00"):+ token = AppStoreConnectTokenProvider("issuer-1", "KEY123", PRIVATE_KEY_PEM).token()++ header = jwt.get_unverified_header(token)+ claims = jwt.decode(token, options={"verify_signature": False})+ assert header["alg"] == "ES256"+ assert header["kid"] == "KEY123"+ assert claims["iss"] == "issuer-1"+ assert claims["aud"] == JWT_AUDIENCE+ # Apple rejects a token whose lifetime exceeds 20 minutes.+ assert claims["exp"] - claims["iat"] == JWT_LIFETIME_SECONDS+ assert claims["exp"] - claims["iat"] <= 1200++ def test_token_is_cached_until_it_nears_expiry(self) -> None:+ provider = AppStoreConnectTokenProvider("issuer-1", "KEY123", PRIVATE_KEY_PEM)+ with freeze_time("2026-03-04 10:00:00") as frozen:+ first = provider.token()+ frozen.tick(60)+ assert provider.token() == first+ # Past the refresh margin the provider mints a fresh token.+ frozen.tick(JWT_LIFETIME_SECONDS)+ assert provider.token() != first++ def test_force_refresh_mints_a_new_token(self) -> None:+ provider = AppStoreConnectTokenProvider("issuer-1", "KEY123", PRIVATE_KEY_PEM)+ with freeze_time("2026-03-04 10:00:00") as frozen:+ first = provider.token()+ frozen.tick(1)+ assert provider.token(force_refresh=True) != first++ def test_unusable_key_raises_auth_error(self) -> None:+ with pytest.raises(AppStoreConnectAuthError):+ AppStoreConnectTokenProvider("issuer-1", "KEY123", "not-a-key").token()+++class TestGet:+ def test_401_forces_one_remint_and_retries(self) -> None:+ session = MagicMock()+ session.get.side_effect = [_json_response({}, status_code=401), _json_response({"data": []})]+ provider = _FakeTokenProvider()++ response = _get(session, f"{BASE_URL}/v1/apps", token_provider=provider, logger=MagicMock())++ assert response.status_code == 200+ assert provider.calls == [False, True]+ assert session.get.call_args_list[0].kwargs["headers"]["Authorization"] == "Bearer token-0"+ assert session.get.call_args_list[1].kwargs["headers"]["Authorization"] == "Bearer token-1"++ def test_persistent_401_raises(self) -> None:+ session = MagicMock()+ unauthorized = _json_response({}, status_code=401)+ unauthorized.raise_for_status.side_effect = Exception("401 Client Error: Unauthorized")+ session.get.side_effect = [unauthorized, unauthorized]++ with pytest.raises(Exception, match="401"):+ _get(session, f"{BASE_URL}/v1/apps", token_provider=_FakeTokenProvider(), logger=MagicMock())++ def test_tolerated_status_is_returned_without_raising(self) -> None:+ session = MagicMock()+ missing = _report_response(None)+ session.get.return_value = missing++ response = _get(+ session,+ f"{BASE_URL}/v1/salesReports",+ token_provider=_FakeTokenProvider(),+ logger=MagicMock(),+ tolerate=(404,),+ )++ assert response.status_code == 404+ missing.raise_for_status.assert_not_called()+++class TestUrlPinning:+ @parameterized.expand(+ [+ ("base", BASE_URL),+ ("collection", f"{BASE_URL}/v1/apps"),+ ("pagination_cursor", f"{BASE_URL}/v1/apps?cursor=P2&limit=200"),+ ("explicit_default_port", f"https://{BASE_URL.split('//')[1]}:443/v1/apps"),+ ]+ )+ def test_apple_origin_urls_are_allowed(self, _name: str, url: str) -> None:+ assert _require_api_url(url) == url++ @parameterized.expand(+ [+ ("off_host", "https://evil.test/v1/apps"),+ ("look_alike_host", "https://api.appstoreconnect.apple.com.evil.test/v1/apps"),+ ("http_scheme", "http://api.appstoreconnect.apple.com/v1/apps"),+ ("non_default_port", "https://api.appstoreconnect.apple.com:8443/v1/apps"),+ ("scheme_relative", "//evil.test/v1/apps"),+ ]+ )+ def test_non_apple_urls_are_refused(self, _name: str, url: str) -> None:+ # A tampered `links.next` or a poisoned resume cursor could otherwise redirect a token-bearing+ # request off Apple's origin.+ with pytest.raises(AppStoreConnectUrlError):+ _require_api_url(url)++ def test_off_host_pagination_cursor_aborts_the_walk(self) -> None:+ # The pin runs inside `_get`, so an off-host `links.next` fails before the request is dispatched.+ api = _FakeApi(+ {f"{BASE_URL}/v1/apps": _page([_resource("apps", "1")], next_url="https://evil.test/v1/apps?cursor=P2")}+ )++ with pytest.raises(AppStoreConnectUrlError):+ _collect("apps", api, _FakeManager())++ def test_off_host_resume_url_is_refused(self) -> None:+ manager = _FakeManager(AppStoreConnectResumeConfig(next_url="https://evil.test/v1/apps?cursor=P9"))++ with pytest.raises(AppStoreConnectUrlError):+ _collect("apps", _FakeApi({}), manager)++ def test_unexpected_redirect_is_treated_as_a_failure(self) -> None:+ session = MagicMock()+ session.get.return_value = _json_response({}, status_code=302)++ with pytest.raises(AppStoreConnectUrlError):+ _get(session, f"{BASE_URL}/v1/apps", token_provider=_FakeTokenProvider(), logger=MagicMock())+++class TestFlattenResource:+ def test_attributes_are_lifted_and_relationships_dropped(self) -> None:+ row = _flatten_resource(_resource("apps", "1234", name="Acme", bundleId="com.acme"))+ assert row == {"id": "1234", "type": "apps", "name": "Acme", "bundleId": "com.acme"}++ def test_missing_attributes_still_yields_identity(self) -> None:+ assert _flatten_resource({"id": "1", "type": "builds"}) == {"id": "1", "type": "builds"}+++class TestCollectionEndpoints:+ def test_follows_links_next_until_absent(self) -> None:+ api = _FakeApi(+ {+ f"{BASE_URL}/v1/apps": _page(+ [_resource("apps", "1", name="One")], next_url=f"{BASE_URL}/v1/apps?cursor=P2"+ ),+ f"{BASE_URL}/v1/apps?cursor=P2": _page([_resource("apps", "2", name="Two")]),+ }+ )+ manager = _FakeManager()++ rows = _collect("apps", api, manager)++ assert [row["id"] for row in rows] == ["1", "2"]+ # Page one carries the request params; the cursor URL is already fully formed, so re-sending+ # them would duplicate limit and cursor.+ assert api.calls[0][1] == {"limit": 200}+ assert api.calls[1][1] is None++ def test_saves_next_url_after_yielding_each_page(self) -> None:+ api = _FakeApi(+ {+ f"{BASE_URL}/v1/apps": _page([_resource("apps", "1")], next_url=f"{BASE_URL}/v1/apps?cursor=P2"),+ f"{BASE_URL}/v1/apps?cursor=P2": _page([_resource("apps", "2")]),+ }+ )+ manager = _FakeManager()++ _collect("apps", api, manager)++ assert [state.next_url for state in manager.saved] == [f"{BASE_URL}/v1/apps?cursor=P2"]++ def test_resumes_from_saved_next_url(self) -> None:+ api = _FakeApi({f"{BASE_URL}/v1/apps?cursor=P9": _page([_resource("apps", "9")])})+ manager = _FakeManager(AppStoreConnectResumeConfig(next_url=f"{BASE_URL}/v1/apps?cursor=P9"))++ rows = _collect("apps", api, manager)++ assert [row["id"] for row in rows] == ["9"]+ assert api.calls == [(f"{BASE_URL}/v1/apps?cursor=P9", None)]++ def test_checkpoint_is_cleared_once_the_walk_completes(self) -> None:+ api = _FakeApi({f"{BASE_URL}/v1/apps": _page([_resource("apps", "1")])})+ manager = _FakeManager()++ _collect("apps", api, manager)++ # A leftover checkpoint would resume a later attempt mid-stream instead of restarting cleanly.+ assert manager.cleared == 1++ def test_documented_sort_is_sent_for_builds(self) -> None:+ api = _FakeApi({f"{BASE_URL}/v1/builds": _page([_resource("builds", "1", version="42")])})++ _collect("builds", api, _FakeManager())++ assert api.calls[0][1] == {"sort": "uploadedDate", "limit": 200}+++class TestAppFanoutEndpoints:+ def _api(self) -> _FakeApi:+ return _FakeApi(+ {+ f"{BASE_URL}/v1/apps": _page([_resource("apps", "A1"), _resource("apps", "A2")]),+ f"{BASE_URL}/v1/apps/A1/customerReviews": _page(+ [_resource("customerReviews", "R1", rating=5)],+ next_url=f"{BASE_URL}/v1/apps/A1/customerReviews?cursor=P2",+ ),+ f"{BASE_URL}/v1/apps/A1/customerReviews?cursor=P2": _page(+ [_resource("customerReviews", "R2", rating=4)]+ ),+ f"{BASE_URL}/v1/apps/A2/customerReviews": _page([_resource("customerReviews", "R3", rating=1)]),+ }+ )++ def test_stamps_parent_app_id_on_every_row(self) -> None:+ rows = _collect("customer_reviews", self._api(), _FakeManager())++ assert [(row["app_id"], row["id"]) for row in rows] == [("A1", "R1"), ("A1", "R2"), ("A2", "R3")]++ def test_bookmark_tracks_page_then_advances_to_next_app(self) -> None:+ manager = _FakeManager()++ _collect("customer_reviews", self._api(), manager)++ assert [(state.app_id, state.next_url) for state in manager.saved] == [+ ("A1", f"{BASE_URL}/v1/apps/A1/customerReviews?cursor=P2"),+ ("A2", None),+ ]++ def test_resumes_mid_fanout_without_refetching_earlier_apps(self) -> None:+ api = self._api()+ manager = _FakeManager(+ AppStoreConnectResumeConfig(app_id="A1", next_url=f"{BASE_URL}/v1/apps/A1/customerReviews?cursor=P2")+ )++ rows = _collect("customer_reviews", api, manager)++ assert [(row["app_id"], row["id"]) for row in rows] == [("A1", "R2"), ("A2", "R3")]+ assert f"{BASE_URL}/v1/apps/A1/customerReviews" not in [url for url, _ in api.calls]++ def test_stale_bookmark_restarts_the_fanout(self) -> None:+ manager = _FakeManager(AppStoreConnectResumeConfig(app_id="DELETED", next_url="https://stale.test"))++ rows = _collect("customer_reviews", self._api(), manager)++ assert [row["id"] for row in rows] == ["R1", "R2", "R3"]+++class TestReportColumnNames:+ @parameterized.expand(+ [+ ("spaces", "Developer Proceeds", "developer_proceeds"),+ ("acronym", "CMB", "cmb"),+ ("punctuation", "Provider Country", "provider_country"),+ ("parenthesis", "Units (Net)", "units_net"),+ ("dash", "Apple-Identifier", "apple_identifier"),+ ("padding", " Begin Date ", "begin_date"),+ ("unnamed", " ", "column"),+ ]+ )+ def test_header_is_normalized_to_snake_case(self, _name: str, header: str, expected: str) -> None:+ assert _normalize_report_column(header) == expected+++class TestParseReport:+ def test_gzipped_tsv_becomes_keyed_rows(self) -> None:+ tsv = "Provider\tSKU\tUnits\tDeveloper Proceeds\nAPPLE\tacme-pro\t3\t2.10\nAPPLE\tacme-lite\t1\t0.70\n"++ rows = _parse_report(gzip.compress(tsv.encode()), date(2026, 3, 4))++ assert rows == [+ {+ "provider": "APPLE",+ "sku": "acme-pro",+ "units": "3",+ "developer_proceeds": "2.10",+ "report_date": "2026-03-04",+ "_line": 1,+ },+ {+ "provider": "APPLE",+ "sku": "acme-lite",+ "units": "1",+ "developer_proceeds": "0.70",+ "report_date": "2026-03-04",+ "_line": 2,+ },+ ]++ def test_blank_lines_are_skipped_so_line_numbers_stay_dense(self) -> None:+ tsv = "SKU\tUnits\nacme-pro\t3\n\n \nacme-lite\t1\n"++ rows = _parse_report(gzip.compress(tsv.encode()), date(2026, 3, 4))++ assert [(row["sku"], row["_line"]) for row in rows] == [("acme-pro", 1), ("acme-lite", 2)]++ def test_short_rows_are_padded_with_none(self) -> None:+ tsv = "SKU\tUnits\tDevice\nacme-pro\t3\n"++ rows = _parse_report(gzip.compress(tsv.encode()), date(2026, 3, 4))++ assert rows[0]["device"] is None++ def test_uncompressed_payload_is_parsed_too(self) -> None:+ # urllib3 unwraps a `Content-Encoding: gzip` body before we see it.+ rows = _parse_report(b"SKU\tUnits\nacme-pro\t3\n", date(2026, 3, 4))++ assert rows[0]["sku"] == "acme-pro"++ @parameterized.expand([("empty", b""), ("header_only", b"SKU\tUnits\n")])+ def test_reports_without_data_rows_yield_nothing(self, _name: str, payload: bytes) -> None:+ assert _parse_report(payload, date(2026, 3, 4)) == []+++class TestSalesReports:+ def _api(self, tsv_by_date: dict[str, str]) -> _FakeReportApi:+ return _FakeReportApi(tsv_by_date)++ def test_missing_vendor_number_fails_loudly(self) -> None:+ with pytest.raises(ValueError, match="vendor number"):+ _collect("sales_reports", _FakeApi({}), _FakeManager(), vendor_number=None)++ @freeze_time("2026-03-05 09:00:00")+ def test_walks_dates_forward_from_the_watermark_and_skips_empty_days(self) -> None:+ api = self._api({"2026-03-02": "SKU\tUnits\nacme\t1\n", "2026-03-04": "SKU\tUnits\nacme\t2\n"})++ rows = _collect(+ "sales_reports",+ api,+ _FakeManager(),+ vendor_number="85234567",+ should_use_incremental_field=True,+ db_incremental_field_last_value=date(2026, 3, 2),+ )++ # Yesterday (2026-03-04) is the newest date Apple has published; 03-03 404s and is skipped.+ assert [(row["report_date"], row["units"]) for row in rows] == [("2026-03-02", "1"), ("2026-03-04", "2")]+ assert [params["filter[reportDate]"] for _, params in api.calls] == ["2026-03-02", "2026-03-03", "2026-03-04"]++ @freeze_time("2026-03-05 09:00:00")+ def test_sends_the_report_type_filters_from_settings(self) -> None:+ api = self._api({"2026-03-04": "SKU\tUnits\nacme\t1\n"})++ _collect(+ "subscription_event_reports",+ api,+ _FakeManager(),+ vendor_number="85234567",+ should_use_incremental_field=True,+ db_incremental_field_last_value=date(2026, 3, 4),+ )++ _, params = api.calls[0]+ assert params["filter[reportType]"] == "SUBSCRIPTION_EVENT"+ assert params["filter[reportSubType]"] == "SUMMARY"+ assert params["filter[frequency]"] == "DAILY"+ assert params["filter[version]"] == "1_4"+ assert params["filter[vendorNumber]"] == "85234567"++ @freeze_time("2026-03-05 09:00:00")+ def test_first_sync_starts_one_retention_window_back(self) -> None:+ api = self._api({})++ _collect("sales_reports", api, _FakeManager(), vendor_number="85234567")++ first_requested = api.calls[0][1]["filter[reportDate]"]+ assert first_requested == (date(2026, 3, 5) - timedelta(days=SALES_REPORT_LOOKBACK_DAYS)).isoformat()++ @freeze_time("2026-03-05 09:00:00")+ def test_future_watermark_is_clamped_to_the_newest_published_date(self) -> None:+ api = self._api({})++ _collect(+ "sales_reports",+ api,+ _FakeManager(),+ vendor_number="85234567",+ should_use_incremental_field=True,+ db_incremental_field_last_value=date(2027, 1, 1),+ )++ assert [params["filter[reportDate]"] for _, params in api.calls] == ["2026-03-04"]++ @freeze_time("2026-03-05 09:00:00")+ def test_bookmark_advances_to_the_next_unfetched_date(self) -> None:+ api = self._api({"2026-03-02": "SKU\tUnits\nacme\t1\n"})+ manager = _FakeManager()++ _collect(+ "sales_reports",+ api,+ manager,+ vendor_number="85234567",+ should_use_incremental_field=True,+ db_incremental_field_last_value=date(2026, 3, 2),+ )++ assert [state.report_date for state in manager.saved] == ["2026-03-03", "2026-03-04"]++ @freeze_time("2026-03-05 09:00:00")+ def test_resumes_from_the_saved_report_date(self) -> None:+ api = self._api({})+ manager = _FakeManager(AppStoreConnectResumeConfig(report_date="2026-03-04"))++ _collect(+ "sales_reports",+ api,+ manager,+ vendor_number="85234567",+ should_use_incremental_field=True,+ db_incremental_field_last_value=date(2026, 3, 1),+ )++ assert [params["filter[reportDate]"] for _, params in api.calls] == ["2026-03-04"]++ @freeze_time("2026-03-05 09:00:00")+ def test_per_run_day_cap_stops_the_walk(self) -> None:+ api = self._api({})++ with patch(f"{MODULE}.SALES_REPORT_MAX_DAYS_PER_RUN", 2):+ _collect(+ "sales_reports",+ api,+ _FakeManager(),+ vendor_number="85234567",+ should_use_incremental_field=True,+ db_incremental_field_last_value=date(2026, 3, 1),+ )++ assert [params["filter[reportDate]"] for _, params in api.calls] == ["2026-03-01", "2026-03-02"]+++class TestCheckCredentials:+ @parameterized.expand([("ok", 200), ("unauthorized", 401), ("forbidden", 403), ("server_error", 500)])+ def test_returns_the_probe_status(self, _name: str, status_code: int) -> None:+ session = MagicMock()+ session.get.return_value = _json_response({}, status_code=status_code)++ with patch(f"{MODULE}.make_tracked_session", return_value=session):+ status, message = check_credentials("issuer", "KEY123", PRIVATE_KEY_PEM)++ assert status == status_code+ assert message is None++ def test_unusable_key_reports_before_any_request(self) -> None:+ with patch(f"{MODULE}.make_tracked_session") as mocked:+ status, message = check_credentials("issuer", "KEY123", "not-a-key")++ assert status is None+ assert message is not None+ mocked.assert_not_called()++ def test_network_failure_reports_no_status(self) -> None:+ session = MagicMock()+ session.get.side_effect = Exception("boom")++ with patch(f"{MODULE}.make_tracked_session", return_value=session):+ status, message = check_credentials("issuer", "KEY123", PRIVATE_KEY_PEM)++ assert status is None+ assert message is None+++class TestSourceResponse:+ @parameterized.expand([(name,) for name in ENDPOINTS])+ def test_response_matches_the_endpoint_catalog(self, endpoint: str) -> None:+ config = APP_STORE_CONNECT_ENDPOINTS[endpoint]++ response = app_store_connect_source(+ issuer_id="issuer",+ key_id="KEY123",+ private_key=PRIVATE_KEY_PEM,+ vendor_number="85234567",+ endpoint=endpoint,+ logger=MagicMock(),+ resumable_source_manager=_FakeManager(),+ )++ assert response.name == endpoint+ assert response.primary_keys == config.primary_keys+ assert response.sort_mode == "asc"+ if config.partition_key:+ assert response.partition_keys == [config.partition_key]+ assert response.partition_mode == "datetime"+ else:+ assert response.partition_keys is None+ assert response.partition_mode is Nonediff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/app_store_connect/tests/test_app_store_connect_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/app_store_connect/tests/test_app_store_connect_source.pynew file mode 100644index 000000000000..69257a907a5d--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/app_store_connect/tests/test_app_store_connect_source.py@@ -0,0 +1,203 @@+from typing import Any, cast++from unittest.mock import MagicMock, patch++from parameterized import parameterized++from posthog.schema import (+ DataWarehouseSourceCategory,+ ReleaseStatus,+ SourceFieldInputConfig,+ SourceFieldInputConfigType,+)++from products.warehouse_sources.backend.temporal.data_imports.sources.app_store_connect.app_store_connect import (+ AppStoreConnectResumeConfig,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.app_store_connect.settings import (+ APP_STORE_CONNECT_ENDPOINTS,+ ENDPOINTS,+ REPORT_ENDPOINTS,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.app_store_connect.source import (+ AppStoreConnectSource,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.appstoreconnect import (+ AppStoreConnectSourceConfig,+)+from products.warehouse_sources.backend.types import ExternalDataSourceType++SOURCE_MODULE = "products.warehouse_sources.backend.temporal.data_imports.sources.app_store_connect.source"+++def _config(vendor_number: str | None = "85234567") -> AppStoreConnectSourceConfig:+ return AppStoreConnectSourceConfig(+ issuer_id="57246542-96fe-1a63-e053-0824d011072a",+ key_id="2X9R4HXF34",+ private_key="-----BEGIN PRIVATE KEY-----\nkey\n-----END PRIVATE KEY-----",+ vendor_number=vendor_number,+ )+++def _input_fields(source: AppStoreConnectSource) -> dict[str, SourceFieldInputConfig]:+ return {+ field.name: field+ for field in source.get_source_config.fields or []+ if isinstance(field, SourceFieldInputConfig)+ }+++class TestAppStoreConnectSource:+ def test_source_type(self) -> None:+ assert AppStoreConnectSource().source_type == ExternalDataSourceType.APPSTORECONNECT++ def test_source_is_visible_and_labelled_alpha(self) -> None:+ config = AppStoreConnectSource().get_source_config++ # `unreleasedSource` hides a source from users entirely; a finished source must not set it.+ assert not config.unreleasedSource+ assert config.releaseStatus == ReleaseStatus.ALPHA+ assert config.category == DataWarehouseSourceCategory.ANALYTICS+ assert config.docsUrl is not None++ @parameterized.expand(+ [+ ("issuer_id", SourceFieldInputConfigType.TEXT, True, False),+ ("key_id", SourceFieldInputConfigType.TEXT, True, False),+ ("private_key", SourceFieldInputConfigType.TEXTAREA, True, True),+ ("vendor_number", SourceFieldInputConfigType.TEXT, False, False),+ ]+ )+ def test_credential_fields(+ self, name: str, field_type: SourceFieldInputConfigType, required: bool, secret: bool+ ) -> None:+ field = _input_fields(AppStoreConnectSource())[name]++ assert field.type == field_type+ assert field.required is required+ assert field.secret is secret++ def test_get_schemas_returns_the_whole_catalog_with_its_keys(self) -> None:+ schemas = AppStoreConnectSource().get_schemas(_config(), team_id=1)++ assert [schema.name for schema in schemas] == list(ENDPOINTS)+ for schema in schemas:+ assert schema.detected_primary_keys == APP_STORE_CONNECT_ENDPOINTS[schema.name].primary_keys++ def test_get_schemas_filters_by_name(self) -> None:+ schemas = AppStoreConnectSource().get_schemas(_config(), team_id=1, names=["customer_reviews"])++ assert [schema.name for schema in schemas] == ["customer_reviews"]++ def test_only_report_tables_are_incremental_and_opt_in(self) -> None:+ schemas = {schema.name: schema for schema in AppStoreConnectSource().get_schemas(_config(), team_id=1)}++ for name, schema in schemas.items():+ is_report = name in REPORT_ENDPOINTS+ # Apple exposes no server-side timestamp filter on the JSON:API collections, so only the+ # report streams (filtered by reportDate) can sync incrementally.+ assert schema.supports_incremental is is_report+ assert schema.should_sync_default is not is_report+ if is_report:+ assert [field["field"] for field in schema.incremental_fields] == ["report_date"]++ def test_canonical_descriptions_cover_the_catalog(self) -> None:+ descriptions = AppStoreConnectSource().get_canonical_descriptions()++ assert set(descriptions) == set(ENDPOINTS)+ for name in ENDPOINTS:+ assert descriptions[name].get("description")+ assert descriptions[name].get("columns")++ def test_report_tables_need_a_vendor_number_in_the_picker(self) -> None:+ permissions = AppStoreConnectSource().get_endpoint_permissions(+ _config(vendor_number=None), team_id=1, endpoints=list(ENDPOINTS)+ )++ assert [name for name, reason in permissions.items() if reason is not None] == list(REPORT_ENDPOINTS)++ def test_all_tables_are_reachable_once_a_vendor_number_is_set(self) -> None:+ permissions = AppStoreConnectSource().get_endpoint_permissions(_config(), team_id=1, endpoints=list(ENDPOINTS))++ assert set(permissions.values()) == {None}++ @parameterized.expand(+ [+ ("ok", 200, None, True),+ ("unauthorized", 401, None, False),+ ("server_error", 500, None, False),+ ("unreachable", None, None, False),+ ("bad_private_key", None, "bad key", False),+ ]+ )+ def test_validate_credentials_status_mapping(+ self, _name: str, status: int | None, message: str | None, expected_valid: bool+ ) -> None:+ with patch(f"{SOURCE_MODULE}.check_credentials", return_value=(status, message)):+ valid, error = AppStoreConnectSource().validate_credentials(_config(), team_id=1)++ assert valid is expected_valid+ assert (error is None) is expected_valid++ def test_forbidden_is_accepted_at_source_create_but_not_per_schema(self) -> None:+ source = AppStoreConnectSource()++ with patch(f"{SOURCE_MODULE}.check_credentials", return_value=(403, None)):+ created, create_error = source.validate_credentials(_config(), team_id=1)+ per_schema, schema_error = source.validate_credentials(_config(), team_id=1, schema_name="builds")++ # A key whose role can't read `/v1/apps` is still a real key, so source creation must not fail.+ assert (created, create_error) == (True, None)+ assert per_schema is False+ assert schema_error is not None++ def test_report_schema_without_a_vendor_number_fails_before_probing(self) -> None:+ with patch(f"{SOURCE_MODULE}.check_credentials") as mocked:+ valid, error = AppStoreConnectSource().validate_credentials(+ _config(vendor_number=None), team_id=1, schema_name="sales_reports"+ )++ assert valid is False+ assert error is not None and "vendor number" in error+ mocked.assert_not_called()++ def test_resumable_manager_is_bound_to_the_resume_dataclass(self) -> None:+ manager = AppStoreConnectSource().get_resumable_source_manager(MagicMock())++ assert manager._data_class is AppStoreConnectResumeConfig++ def test_source_for_pipeline_plumbs_credentials_and_the_watermark(self) -> None:+ inputs = MagicMock()+ inputs.schema_name = "sales_reports"+ inputs.should_use_incremental_field = True+ inputs.db_incremental_field_last_value = "2026-03-01"+ manager = MagicMock()++ with patch(f"{SOURCE_MODULE}.app_store_connect_source") as mocked:+ AppStoreConnectSource().source_for_pipeline(_config(), manager, inputs)++ kwargs = mocked.call_args.kwargs+ assert kwargs["issuer_id"] == "57246542-96fe-1a63-e053-0824d011072a"+ assert kwargs["key_id"] == "2X9R4HXF34"+ assert kwargs["vendor_number"] == "85234567"+ assert kwargs["endpoint"] == "sales_reports"+ assert kwargs["resumable_source_manager"] is manager+ assert kwargs["db_incremental_field_last_value"] == "2026-03-01"++ def test_full_refresh_run_does_not_pass_a_watermark(self) -> None:+ inputs = MagicMock()+ inputs.schema_name = "apps"+ inputs.should_use_incremental_field = False+ inputs.db_incremental_field_last_value = "2026-03-01"++ with patch(f"{SOURCE_MODULE}.app_store_connect_source") as mocked:+ AppStoreConnectSource().source_for_pipeline(_config(), MagicMock(), inputs)++ assert mocked.call_args.kwargs["db_incremental_field_last_value"] is None++ def test_auth_and_permission_failures_are_non_retryable(self) -> None:+ errors = cast(dict[str, Any], AppStoreConnectSource().get_non_retryable_errors())++ assert any("401" in key for key in errors)+ assert any("403" in key for key in errors)+ assert all(message for message in errors.values())diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/appstoreconnect.py b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/appstoreconnect.pyindex 634c70459e00..1f332eeb262e 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/appstoreconnect.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/appstoreconnect.py@@ -6,4 +6,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common imp@config.configclass AppStoreConnectSourceConfig(config.Config):- pass+ issuer_id: str+ key_id: str+ private_key: str+ vendor_number: str | None = None