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(warehouse): let App Store Connect sync only selected apps (#97196)

Luke Beltonaf45e67de71c
diff --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.py
index 0a6fa24ebf7e..efccafa7f0ac 100644
--- 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.py
@@ -14,6 +14,7 @@ from urllib.parse import urlsplit
import jwt
import requests
+import structlog
from structlog.types import FilteringBoundLogger
from posthog.dataclasses import frozen
@@ -28,6 +29,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.app_store_
SALES_REPORT_MAX_DAYS_PER_RUN,
AppStoreConnectEndpointConfig,
)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.config import str_to_optional_list
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
@@ -65,6 +67,10 @@ ANALYTICS_SEGMENT_SPOOL_BYTES = 32 * 1024 * 1024
ANALYTICS_ROWS_PER_BATCH = 2000
+# The message goes in a form field error and an account can hold hundreds of apps, so the rest
+# are counted rather than listed.
+MAX_APPS_LISTED_IN_ERROR = 10
+
_PEM_HEADER = "-----BEGIN PRIVATE KEY-----"
_PEM_FOOTER = "-----END PRIVATE KEY-----"
_NON_ALNUM = re.compile(r"[^0-9a-z]+")
@@ -112,6 +118,13 @@ APP_STORE_CONNECT_ANALYTICS_INACTIVE_ERROR = (
"new request, which only an Admin key can create. Give the key the Admin role, then reconnect."
)
+# The source's app id filter selected none of the apps the key can read. Every retry resolves the
+# same empty set, so `AppStoreConnectSource.get_non_retryable_errors` matches on this text.
+APP_STORE_CONNECT_NO_MATCHING_APPS_ERROR = (
+ "None of the app IDs in your App Store Connect source settings match an app this API key can "
+ "read. Check the IDs, or clear the field to sync every app."
+)
+
# A sales or subscription report sync started without a vendor number. `/v1/salesReports` can't be
# read without one, so every retry fails identically until the user adds it in the source settings.
# `AppStoreConnectSource.get_non_retryable_errors` matches on this text to fail fast.
@@ -628,15 +641,65 @@ def _load_resume(
return manager.load_state() if manager.can_resume() else None
+def parse_app_ids(raw: str | None) -> frozenset[str]:
+ """Split the source's optional app id filter into ids.
+
+ An empty result means the source syncs every app the key can read, which is what a blank field
+ has always done. The generator types a text input as ``str``, so the field arrives as one
+ string and is split with the same converter every other multi-value source field uses.
+ """
+ return frozenset(str_to_optional_list(raw) or ())
+
+
+def list_apps(
+ session: requests.Session,
+ token_provider: AppStoreConnectTokenProvider,
+ logger: FilteringBoundLogger,
+) -> dict[str, str | None]:
+ """Every app the key can read, as id to name, in the order Apple returns them.
+
+ The name is what a person recognises, so the save-time check can name the apps the key reaches
+ rather than only the ids it does not.
+ """
+ apps: dict[str, str | None] = {}
+ for page in _iter_pages(session, token_provider, logger, f"{BASE_URL}/v1/apps", {}):
+ for resource in page.resources:
+ if resource.get("id") is None:
+ continue
+ attributes = resource.get("attributes")
+ name = attributes.get("name") if isinstance(attributes, dict) else None
+ apps[str(resource["id"])] = str(name) if name else None
+ return apps
+
+
def _list_app_ids(
session: requests.Session,
token_provider: AppStoreConnectTokenProvider,
logger: FilteringBoundLogger,
+ app_ids: frozenset[str],
) -> list[str]:
- app_ids: list[str] = []
- for page in _iter_pages(session, token_provider, logger, f"{BASE_URL}/v1/apps", {}):
- app_ids.extend(str(resource["id"]) for resource in page.resources if resource.get("id"))
- return app_ids
+ """The app ids a fan-out or analytics walk visits, after the source's app id filter.
+
+ Discovery order is preserved, because the fan-out resume bookmark finds its place by index in
+ this list.
+ """
+ discovered = list(list_apps(session, token_provider, logger))
+ if not app_ids:
+ return discovered
+
+ selected = [app_id for app_id in discovered if app_id in app_ids]
+
+ unknown = sorted(app_ids.difference(discovered))
+ if unknown:
+ # Not fatal: a key that lost access to one app of several must not stop the others.
+ logger.warning(
+ f"App Store Connect: app id filter names apps this key cannot read, skipping them. "
+ f"app_ids={','.join(unknown)}"
+ )
+
+ if not selected:
+ raise ValueError(APP_STORE_CONNECT_NO_MATCHING_APPS_ERROR)
+ return selected
def _get_collection(
@@ -646,6 +709,7 @@ def _get_collection(
logger: FilteringBoundLogger,
manager: ResumableSourceManager[AppStoreConnectResumeConfig],
failures: _ParseFailureCounter,
+ app_ids: frozenset[str],
) -> Iterator[list[dict[str, Any]]]:
resume = _load_resume(manager)
resumed_url = resume.next_url if resume is not None else None
@@ -653,8 +717,16 @@ def _get_collection(
url = resumed_url or f"{BASE_URL}{config.path}"
params: dict[str, Any] | None = None if resumed_url else dict(config.params)
+ app_id_column = config.app_id_column if app_ids else None
+ matched_an_app = False
+
for page in _iter_pages(session, token_provider, logger, url, params):
rows = _page_rows(config, page, failures)
+ if app_id_column is not None:
+ # Filtered on fetched rows rather than through a query param, because Apple's
+ # per-resource filter support varies by endpoint and an unsupported filter is a hard 400.
+ rows = [row for row in rows if str(row.get(app_id_column)) in app_ids]
+ matched_an_app = matched_an_app or bool(rows)
if rows:
yield rows
# Save AFTER yielding so a crash re-fetches the page we just emitted rather than skipping it;
@@ -662,6 +734,12 @@ def _get_collection(
if page.next_url:
manager.save_state(AppStoreConnectResumeConfig(next_url=page.next_url))
+ if app_id_column is not None and not matched_an_app:
+ # This table is a full refresh, so finishing with no rows would replace the existing table
+ # with an empty one. The fan-out and analytics walks already fail on an empty selection, and
+ # a silent wipe here would be worse than either.
+ raise ValueError(APP_STORE_CONNECT_NO_MATCHING_APPS_ERROR)
+
def _get_app_fanout(
session: requests.Session,
@@ -670,8 +748,9 @@ def _get_app_fanout(
logger: FilteringBoundLogger,
manager: ResumableSourceManager[AppStoreConnectResumeConfig],
failures: _ParseFailureCounter,
+ selected_app_ids: frozenset[str],
) -> Iterator[list[dict[str, Any]]]:
- app_ids = _list_app_ids(session, token_provider, logger)
+ app_ids = _list_app_ids(session, token_provider, logger, selected_app_ids)
resume = _load_resume(manager)
start = 0
@@ -1305,8 +1384,11 @@ def _get_analytics_report(
failures: _ParseFailureCounter,
should_use_incremental_field: bool,
db_incremental_field_last_value: Any,
+ selected_app_ids: frozenset[str],
) -> Iterator[list[dict[str, Any]]]:
- app_ids = _list_app_ids(session, token_provider, logger)
+ # Filtering before the loop keeps `_ensure_report_request` away from the excluded apps, so an
+ # unselected app never gets an ONGOING analytics report request created on it.
+ app_ids = _list_app_ids(session, token_provider, logger, selected_app_ids)
resume = _load_resume(manager)
resumed_date = _to_date(resume.processing_date) if resume is not None else None
watermark = _to_date(db_incremental_field_last_value) if should_use_incremental_field else None
@@ -1428,6 +1510,51 @@ def check_credentials(issuer_id: str, key_id: str, private_key: str) -> tuple[in
return None, None
+def _describe_app(app_id: str, name: str | None) -> str:
+ return f"{name} ({app_id})" if name else app_id
+
+
+def check_app_ids(issuer_id: str, key_id: str, private_key: str, app_ids: str | None) -> str | None:
+ """Return the message for a filter naming app ids the key cannot read, or ``None`` if it can.
+
+ ``None`` also covers a filter that is not set, and a probe that cannot reach Apple. Reporting
+ nothing on a failed probe keeps a network blip from surfacing as a misleading "unknown app id"
+ while the real credential problem goes unreported.
+
+ The message lists the apps the key can read, because the field takes the numeric Apple ID and a
+ user is as likely to paste a bundle ID or a SKU. Naming only the rejected value leaves them
+ guessing; naming the accepted values lets them copy one.
+ """
+ wanted = parse_app_ids(app_ids)
+ if not wanted:
+ return None
+
+ logger = structlog.get_logger(__name__)
+ try:
+ token_provider = AppStoreConnectTokenProvider(issuer_id, key_id, private_key)
+ readable = list_apps(_make_session(private_key), token_provider, logger)
+ except Exception:
+ return None
+
+ unknown = sorted(wanted.difference(readable))
+ if not unknown:
+ return None
+
+ message = f"This API key cannot read these app IDs: {', '.join(unknown)}."
+ if not readable:
+ return (
+ f"{message} It cannot read any app in this account. Check the key's role and its app "
+ f"access in App Store Connect."
+ )
+
+ shown = list(readable.items())[:MAX_APPS_LISTED_IN_ERROR]
+ listed = ", ".join(_describe_app(app_id, name) for app_id, name in shown)
+ remaining = len(readable) - len(shown)
+ if remaining:
+ listed = f"{listed}, and {remaining} more"
+ return f"{message} It can read: {listed}. Check the IDs, or clear the field to sync every app."
+
+
def get_rows(
issuer_id: str,
key_id: str,
@@ -1438,17 +1565,23 @@ def get_rows(
resumable_source_manager: ResumableSourceManager[AppStoreConnectResumeConfig],
should_use_incremental_field: bool = False,
db_incremental_field_last_value: Any = None,
+ app_ids: str | None = 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)
failures = _ParseFailureCounter(logger, endpoint)
+ selected_app_ids = parse_app_ids(app_ids)
try:
if config.kind == "collection":
- yield from _get_collection(session, config, token_provider, logger, resumable_source_manager, failures)
+ yield from _get_collection(
+ session, config, token_provider, logger, resumable_source_manager, failures, selected_app_ids
+ )
elif config.kind == "app_fanout":
- yield from _get_app_fanout(session, config, token_provider, logger, resumable_source_manager, failures)
+ yield from _get_app_fanout(
+ session, config, token_provider, logger, resumable_source_manager, failures, selected_app_ids
+ )
elif config.kind == "analytics_report":
yield from _get_analytics_report(
session,
@@ -1463,8 +1596,10 @@ def get_rows(
failures,
should_use_incremental_field,
db_incremental_field_last_value,
+ selected_app_ids,
)
else: # "sales_report"
+ # `/v1/salesReports` returns one file per vendor number, so no app id filter applies.
yield from _get_sales_report(
session,
config,
@@ -1496,6 +1631,7 @@ def app_store_connect_source(
resumable_source_manager: ResumableSourceManager[AppStoreConnectResumeConfig],
should_use_incremental_field: bool = False,
db_incremental_field_last_value: Optional[Any] = None,
+ app_ids: Optional[str] = None,
) -> SourceResponse:
config = APP_STORE_CONNECT_ENDPOINTS[endpoint]
@@ -1511,6 +1647,7 @@ def app_store_connect_source(
resumable_source_manager=resumable_source_manager,
should_use_incremental_field=should_use_incremental_field,
db_incremental_field_last_value=db_incremental_field_last_value,
+ app_ids=app_ids,
),
primary_keys=config.primary_keys,
partition_count=1,
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.py
index 470f0a729c22..b49bb81b3146 100644
--- 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.py
@@ -69,6 +69,9 @@ class AppStoreConnectEndpointConfig:
# Column that carries the id of the `data` resource referencing each included row, so
# the table joins back to its parent without a per-row request.
included_parent_column: str = "parent_id"
+ # Column holding the app's id, so a "collection" endpoint can honor the source's app id
+ # filter. Unset on the account-wide collections whose rows carry no app dimension.
+ app_id_column: Optional[str] = None
# Analytics Reports API selectors, only meaningful for the "analytics_report" kind.
# Acceptable report names in preference order: Apple exposes most reports as separate
# "<name> Standard" / "<name> Detailed" resources, but a few (App Crashes, App Clip
@@ -127,6 +130,7 @@ APP_STORE_CONNECT_ENDPOINTS: dict[str, AppStoreConnectEndpointConfig] = {
kind="collection",
primary_keys=["id"],
path="/v1/apps",
+ app_id_column="id",
),
# Every version record per app — release type, review state, release dates.
"app_store_versions": AppStoreConnectEndpointConfig(
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.py
index 6c96d3898158..293edaf932f1 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
@@ -14,10 +14,12 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.app_store_
APP_STORE_CONNECT_ANALYTICS_INACTIVE_ERROR,
APP_STORE_CONNECT_INVALID_REPORT_ERROR,
APP_STORE_CONNECT_MISSING_VENDOR_NUMBER_ERROR,
+ APP_STORE_CONNECT_NO_MATCHING_APPS_ERROR,
APP_STORE_CONNECT_READ_FORBIDDEN_ERROR,
APP_STORE_CONNECT_UNKNOWN_VENDOR_NUMBER_ERROR,
AppStoreConnectResumeConfig,
app_store_connect_source,
+ check_app_ids,
check_credentials,
)
from products.warehouse_sources.backend.temporal.data_imports.sources.app_store_connect.settings import (
@@ -69,7 +71,9 @@ An Account Holder or Admin creates an API key under **Users and Access → Integ
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.
-The analytics tables need a key with the Admin role. Apple lets only an Admin key start an analytics report."""
+The analytics tables need a key with the Admin role. Apple lets only an Admin key start an analytics report.
+
+Leave **app IDs** blank to sync every app the key can read. To sync only some of your apps, list their Apple IDs, separated by commas. You can find an app's Apple ID in App Store Connect under **App Information → General Information**. The filter covers the apps, versions, reviews, review responses, in-app purchases, subscription groups and analytics tables. Builds, TestFlight groups and the sales reports cover your whole account, so they are not filtered."""
restatement_note = restatement_caption()
if restatement_note:
caption = f"{caption}\n\n{restatement_note}"
@@ -118,6 +122,14 @@ The analytics tables need a key with the Admin role. Apple lets only an Admin ke
placeholder="85234567",
secret=False,
),
+ SourceFieldInputConfig(
+ name="app_ids",
+ label="App IDs (optional)",
+ type=SourceFieldInputConfigType.TEXT,
+ required=False,
+ placeholder="1234567890, 9876543210",
+ secret=False,
+ ),
],
),
)
@@ -166,6 +178,8 @@ The analytics tables need a key with the Admin role. Apple lets only an Admin ke
APP_STORE_CONNECT_INVALID_REPORT_ERROR: "App Store Connect rejected this report request. The report type or version it asks for may no longer be valid. This usually needs a source update — contact support if it keeps failing.",
# A vendor number Apple doesn't know. Every retry fails identically until it is corrected.
APP_STORE_CONNECT_UNKNOWN_VENDOR_NUMBER_ERROR: "App Store Connect does not recognize your vendor number. Find it in App Store Connect under Payments and Financial Reports, update it in this source's settings, then run the sync again.",
+ # Retrying only delays the message that tells the user to fix the field.
+ APP_STORE_CONNECT_NO_MATCHING_APPS_ERROR: APP_STORE_CONNECT_NO_MATCHING_APPS_ERROR,
}
def get_retryable_errors(self) -> set[str]:
@@ -238,9 +252,16 @@ The analytics tables need a key with the Admin role. Apple lets only an Admin ke
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}"
+ if status != 200:
+ return False, f"App Store Connect returned status {status}"
+
+ # Create and edit only: the per-schema call runs once per table in the picker, and each
+ # would list every app again.
+ if schema_name is None:
+ unreadable_app_ids = check_app_ids(config.issuer_id, config.key_id, config.private_key, config.app_ids)
+ if unreadable_app_ids:
+ return False, unreadable_app_ids
+ return True, None
def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[AppStoreConnectResumeConfig]:
return ResumableSourceManager[AppStoreConnectResumeConfig](inputs, AppStoreConnectResumeConfig)
@@ -256,6 +277,7 @@ The analytics tables need a key with the Admin role. Apple lets only an Admin ke
key_id=config.key_id,
private_key=config.private_key,
vendor_number=config.vendor_number,
+ app_ids=config.app_ids,
endpoint=inputs.schema_name,
logger=inputs.logger,
resumable_source_manager=resumable_source_manager,
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.py
index 7aeb6b4db098..02fc03504c34 100644
--- 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.py
@@ -38,8 +38,10 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.app_store_
_require_api_url,
_typed_report_value,
app_store_connect_source,
+ check_app_ids,
check_credentials,
get_rows,
+ parse_app_ids,
)
from products.warehouse_sources.backend.temporal.data_imports.sources.app_store_connect.settings import (
APP_STORE_CONNECT_ENDPOINTS,
@@ -496,6 +498,111 @@ class TestAppFanoutEndpoints:
assert [row["id"] for row in rows] == ["R1", "R2", "R3"]
+class TestCheckAppIds:
+ def _message(self, app_ids: str | None, apps: list[dict[str, Any]]) -> tuple[str | None, _FakeApi]:
+ api = _FakeApi({f"{BASE_URL}/v1/apps": _page(apps)})
+ session = MagicMock()
+ session.get.side_effect = api.get
+ with patch(f"{MODULE}._make_session", return_value=session):
+ return check_app_ids("issuer", "KEY123", PRIVATE_KEY_PEM, app_ids), api
+
+ def test_a_readable_filter_saves(self) -> None:
+ message, _ = self._message("A1", [_resource("apps", "A1", name="Acme")])
+
+ assert message is None
+
+ def test_an_unset_filter_never_lists_apps(self) -> None:
+ message, api = self._message(None, [_resource("apps", "A1", name="Acme")])
+
+ assert message is None
+ assert api.calls == []
+
+ @parameterized.expand(
+ [
+ ("readable_apps_are_named", 1, "It can read: App 0 (A0)."),
+ ("a_long_account_is_truncated", 12, "and 2 more"),
+ ]
+ )
+ def test_the_message_lists_the_apps_the_key_can_read(self, _name: str, app_count: int, expected: str) -> None:
+ apps = [_resource("apps", f"A{index}", name=f"App {index}") for index in range(app_count)]
+
+ message, _ = self._message("MISSING", apps)
+
+ assert message is not None
+ assert "cannot read these app IDs: MISSING" in message
+ assert expected in message
+
+ def test_an_app_without_a_name_falls_back_to_its_id(self) -> None:
+ message, _ = self._message("MISSING", [_resource("apps", "A1")])
+
+ assert message is not None and "It can read: A1." in message
+
+ def test_a_key_that_reaches_no_app_says_so(self) -> None:
+ message, _ = self._message("MISSING", [])
+
+ assert message is not None and "cannot read any app in this account" in message
+
+
+class TestAppIdFilter:
+ 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)]),
+ f"{BASE_URL}/v1/apps/A2/customerReviews": _page([_resource("customerReviews", "R3", rating=1)]),
+ }
+ )
+
+ @parameterized.expand(
+ [
+ ("unset", None, frozenset()),
+ ("blank", " ", frozenset()),
+ ("single", "A1", frozenset({"A1"})),
+ ("comma_separated", "A1,A2", frozenset({"A1", "A2"})),
+ ("comma_and_space_separated", " A1 , A2 ", frozenset({"A1", "A2"})),
+ ("trailing_comma", "A1,", frozenset({"A1"})),
+ ]
+ )
+ def test_parses_the_filter_field(self, _name: str, raw: str | None, expected: frozenset[str]) -> None:
+ assert parse_app_ids(raw) == expected
+
+ def test_fanout_visits_only_the_selected_apps(self) -> None:
+ api = self._api()
+
+ rows = _collect("customer_reviews", api, _FakeManager(), app_ids="A1")
+
+ assert [(row["app_id"], row["id"]) for row in rows] == [("A1", "R1")]
+ assert f"{BASE_URL}/v1/apps/A2/customerReviews" not in [url for url, _ in api.calls]
+
+ def test_blank_filter_still_visits_every_app(self) -> None:
+ rows = _collect("customer_reviews", self._api(), _FakeManager(), app_ids="")
+
+ assert [row["app_id"] for row in rows] == ["A1", "A2"]
+
+ def test_apps_table_drops_the_unselected_apps(self) -> None:
+ rows = _collect("apps", self._api(), _FakeManager(), app_ids="A2")
+
+ assert [row["id"] for row in rows] == ["A2"]
+
+ def test_apps_table_fails_rather_than_replacing_itself_with_nothing(self) -> None:
+ # A full refresh that finishes with no rows leaves an empty table behind, so an app the key
+ # lost access to after setup would silently erase the synced inventory.
+ with pytest.raises(ValueError, match="match an app this API key can read"):
+ _collect("apps", self._api(), _FakeManager(), app_ids="A9")
+
+ def test_filter_matching_no_app_fails_with_the_curated_message(self) -> None:
+ with pytest.raises(ValueError, match="match an app this API key can read"):
+ _collect("customer_reviews", self._api(), _FakeManager(), app_ids="A9")
+
+ def test_unreadable_id_is_warned_about_while_the_readable_ones_sync(self) -> None:
+ logger = MagicMock()
+
+ rows = _collect("customer_reviews", self._api(), _FakeManager(), logger=logger, app_ids="A1,A9")
+
+ assert [row["app_id"] for row in rows] == ["A1"]
+ assert "A9" in logger.warning.call_args[0][0]
+
+
def _responded_review(review_id: str, response_id: str) -> dict[str, Any]:
review = _resource("customerReviews", review_id, rating=5)
review["relationships"]["response"] = {"data": {"type": "customerReviewResponses", "id": response_id}}
@@ -706,6 +813,21 @@ def _collect_analytics(
class TestAnalyticsReportStreams:
+ def test_a_report_request_is_started_only_on_a_selected_app(self) -> None:
+ api = _FakeAnalyticsApi(
+ {
+ APPS_URL: _page([_resource("apps", "A1"), _resource("apps", "A2")]),
+ REQUESTS_URL: _page([]),
+ f"{BASE_URL}/v1/apps/A2/analyticsReportRequests": _page([]),
+ }
+ )
+
+ _collect_analytics(api, _FakeManager(), app_ids="A1")
+
+ # The ONGOING request is this source's only write to the customer's account.
+ assert [post[1]["data"]["relationships"]["app"]["data"]["id"] for post in api.posts] == ["A1"]
+ assert f"{BASE_URL}/v1/apps/A2/analyticsReportRequests" not in [url for url, _ in api.calls]
+
def test_full_chain_parses_daily_instances_into_keyed_rows(self) -> None:
segment_1 = _gzip_csv("Date,App Name,App Apple Identifier,Sessions\n2026-07-31,Example,123,5\n")
segment_2 = _gzip_csv("Date,App Name,App Apple Identifier,Sessions\n2026-08-01,Example,123,7\n")
diff --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.py
index 637b1fe844da..dd95f46f575d 100644
--- 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.py
@@ -42,12 +42,13 @@ def _resolve_friendly_error(error_message: str) -> str | None:
return None
-def _config(vendor_number: str | None = "85234567") -> AppStoreConnectSourceConfig:
+def _config(vendor_number: str | None = "85234567", app_ids: str | None = None) -> 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,
+ app_ids=app_ids,
)
@@ -75,6 +76,7 @@ class TestAppStoreConnectSource:
("key_id", SourceFieldInputConfigType.TEXT, True, False),
("private_key", SourceFieldInputConfigType.TEXTAREA, True, True),
("vendor_number", SourceFieldInputConfigType.TEXT, False, False),
+ ("app_ids", SourceFieldInputConfigType.TEXT, False, False),
]
)
def test_credential_fields(
@@ -183,6 +185,31 @@ class TestAppStoreConnectSource:
assert per_schema is False
assert schema_error is not None
+ def test_an_unreadable_app_id_blocks_the_source_with_the_probe_message(self) -> None:
+ probe_message = "This API key cannot read these app IDs: 999. It can read: Acme (1234567890)."
+
+ with (
+ patch(f"{SOURCE_MODULE}.check_credentials", return_value=(200, None)),
+ patch(f"{SOURCE_MODULE}.check_app_ids", return_value=probe_message),
+ ):
+ valid, error = AppStoreConnectSource().validate_credentials(_config(app_ids="999"), team_id=1)
+
+ # Saved as-is the source would sync nothing, so the message reaches the user at save time.
+ assert (valid, error) == (False, probe_message)
+
+ def test_the_app_id_probe_is_skipped_for_a_per_schema_check(self) -> None:
+ with (
+ patch(f"{SOURCE_MODULE}.check_credentials", return_value=(200, None)),
+ patch(f"{SOURCE_MODULE}.check_app_ids") as probe,
+ ):
+ valid, _ = AppStoreConnectSource().validate_credentials(
+ _config(app_ids="999"), team_id=1, schema_name="builds"
+ )
+
+ # The picker calls this once per table, and each probe would list every app again.
+ assert valid is True
+ probe.assert_not_called()
+
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(
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.py
index 1f332eeb262e..7818c2060cd5 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
@@ -10,3 +10,4 @@ class AppStoreConnectSourceConfig(config.Config):
key_id: str
private_key: str
vendor_number: str | None = None
+ app_ids: str | None = None