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-sources): App Store Connect review responses table (#80188)

jake sciottof257c49f9f66
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 ed48581fbe9d..e952896113ab 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
@@ -207,14 +207,25 @@ def _flatten_resource(resource: dict[str, Any]) -> dict[str, Any]:
return row
[email protected](frozen=True, kw_only=True)
+class _Page:
+ """One JSON:API page. ``resources`` and ``included`` share a type, so construction is
+ keyword-only to keep a caller from silently swapping them."""
+
+ resources: list[dict[str, Any]]
+ included: list[dict[str, Any]]
+ next_url: str | None
+
+
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).
+) -> Iterator[_Page]:
+ """Walk a JSON:API collection, yielding each page's ``data`` and ``included`` resources 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.
@@ -225,7 +236,7 @@ def _iter_pages(
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)]
+ included = body.get("included") if isinstance(body, dict) else None
links = body.get("links") if isinstance(body, dict) else None
next_url = links.get("next") if isinstance(links, dict) else None
@@ -235,7 +246,11 @@ def _iter_pages(
logger.warning(f"App Store Connect: page cap reached, truncating collection. url={url}, pages={pages}")
next_url = None
- yield rows, next_url
+ yield _Page(
+ resources=[resource for resource in (data or []) if isinstance(resource, dict)],
+ included=[resource for resource in (included or []) if isinstance(resource, dict)],
+ next_url=next_url,
+ )
if not next_url:
return
@@ -244,6 +259,39 @@ def _iter_pages(
page_params = None
+def _page_rows(config: AppStoreConnectEndpointConfig, page: _Page) -> list[dict[str, Any]]:
+ """Rows for one page: the flattened ``data`` resources, or, for endpoints configured to read a
+ related resource off another collection's pages, the flattened ``included`` resources of that type.
+ """
+ if config.rows_from_included_type is None:
+ return [_flatten_resource(resource) for resource in page.resources]
+
+ # JSON:API full linkage guarantees every included resource is referenced from a primary
+ # resource's relationship linkage; that linkage is where each row's parent id comes from.
+ parent_ids: dict[str, str] = {}
+ for resource in page.resources:
+ relationships = resource.get("relationships")
+ if not isinstance(relationships, dict) or resource.get("id") is None:
+ continue
+ for relationship in relationships.values():
+ linkage = relationship.get("data") if isinstance(relationship, dict) else None
+ if (
+ isinstance(linkage, dict)
+ and linkage.get("type") == config.rows_from_included_type
+ and linkage.get("id") is not None
+ ):
+ parent_ids[str(linkage["id"])] = str(resource["id"])
+
+ rows: list[dict[str, Any]] = []
+ for resource in page.included:
+ if resource.get("type") != config.rows_from_included_type:
+ continue
+ row = _flatten_resource(resource)
+ row[config.included_parent_column] = parent_ids.get(str(resource.get("id")))
+ rows.append(row)
+ return rows
+
+
def _load_resume(
manager: ResumableSourceManager[AppStoreConnectResumeConfig],
) -> AppStoreConnectResumeConfig | None:
@@ -256,8 +304,8 @@ def _list_app_ids(
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"))
+ 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
@@ -274,13 +322,14 @@ 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)
- for rows, next_url in _iter_pages(session, token_provider, logger, url, params):
+ for page in _iter_pages(session, token_provider, logger, url, params):
+ rows = _page_rows(config, page)
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))
+ if page.next_url:
+ manager.save_state(AppStoreConnectResumeConfig(next_url=page.next_url))
def _get_app_fanout(
@@ -311,14 +360,15 @@ def _get_app_fanout(
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):
+ for page in _iter_pages(session, token_provider, logger, url, params):
+ rows = _page_rows(config, page)
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))
+ if page.next_url:
+ manager.save_state(AppStoreConnectResumeConfig(app_id=app_id, next_url=page.next_url))
elif position + 1 < len(app_ids):
manager.save_state(AppStoreConnectResumeConfig(app_id=app_ids[position + 1]))
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.py
index 9e28bc2af280..31ee81ab502c 100644
--- 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.py
@@ -98,6 +98,19 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
"territory": "App Store territory the review was written in.",
},
},
+ "review_responses": {
+ "description": "A developer response published to a customer review, one row per responded review.",
+ "docs_url": "https://developer.apple.com/documentation/appstoreconnectapi/customerreviewresponsev1",
+ "columns": {
+ "id": "Apple's opaque identifier for the response.",
+ "type": "JSON:API resource type, always `customerReviewResponses`.",
+ "app_id": "Identifier of the app the responded review was left on.",
+ "review_id": "Identifier of the review this response answers; joins to the customer_reviews table.",
+ "responseBody": "Body text of the developer's response.",
+ "lastModifiedDate": "When the response was created or last edited.",
+ "state": "Publication state of the response, PUBLISHED or PENDING_PUBLISH.",
+ },
+ },
"in_app_purchases": {
"description": "An in-app purchase product configured for an app.",
"docs_url": "https://developer.apple.com/documentation/appstoreconnectapi/inapppurchasev2",
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 411c3a6f0908..5110e64ea21b 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
@@ -44,6 +44,13 @@ class AppStoreConnectEndpointConfig:
# Stable creation-style field to partition by — never an updated/modified field.
partition_key: Optional[str] = None
should_sync_default: bool = True
+ # When set, rows for this endpoint come from the pages' JSON:API `included` resources
+ # of this type (requested via an `include` param) instead of `data`. Lets a related
+ # resource with no list endpoint of its own ride another collection's walk.
+ rows_from_included_type: Optional[str] = None
+ # 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"
# `/v1/salesReports` filters, only meaningful for the "sales_report" kind.
report_type: str = ""
report_sub_type: str = ""
@@ -105,6 +112,23 @@ APP_STORE_CONNECT_ENDPOINTS: dict[str, AppStoreConnectEndpointConfig] = {
params={"sort": "createdDate"},
partition_key="createdDate",
),
+ # Developer responses to customer reviews: the other half of the reviews conversation.
+ # Responses have no list endpoint of their own, so they ride the per-app reviews walk
+ # via `include=response`, filtered to reviews with a published response so unresponded
+ # reviews are never paged through. Rows come from the pages' included resources, each
+ # carrying the id of the review it answers. The only timestamp on a response is
+ # lastModifiedDate, which changes when the response is edited, so the table is
+ # unpartitioned (partition keys must never change for a row). Full refresh replaces
+ # the table each sync, so edited responses update and deleted ones drop out.
+ "review_responses": AppStoreConnectEndpointConfig(
+ name="review_responses",
+ kind="app_fanout",
+ primary_keys=["app_id", "id"],
+ path="/v1/apps/{app_id}/customerReviews",
+ params={"include": "response", "exists[publishedResponse]": "true", "sort": "createdDate"},
+ rows_from_included_type="customerReviewResponses",
+ included_parent_column="review_id",
+ ),
# In-app purchase catalog per app.
"in_app_purchases": AppStoreConnectEndpointConfig(
name="in_app_purchases",
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 fc6efef84bc4..d23d5be7165e 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
@@ -118,10 +118,16 @@ def _resource(resource_type: str, resource_id: str, **attributes: Any) -> dict[s
}
-def _page(resources: list[dict[str, Any]], next_url: str | None = None) -> dict[str, Any]:
+def _page(
+ resources: list[dict[str, Any]],
+ next_url: str | None = None,
+ included: list[dict[str, Any]] | None = None,
+) -> dict[str, Any]:
body: dict[str, Any] = {"data": resources, "meta": {"paging": {"total": len(resources)}}}
if next_url:
body["links"] = {"next": next_url}
+ if included is not None:
+ body["included"] = included
return body
@@ -445,6 +451,66 @@ class TestAppFanoutEndpoints:
assert [row["id"] for row in rows] == ["R1", "R2", "R3"]
+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}}
+ return review
+
+
+class TestReviewResponses:
+ def _api(self) -> _FakeApi:
+ reviews_url = f"{BASE_URL}/v1/apps/A1/customerReviews"
+ return _FakeApi(
+ {
+ f"{BASE_URL}/v1/apps": _page([_resource("apps", "A1")]),
+ reviews_url: _page(
+ [_responded_review("R1", "RESP1"), _responded_review("R2", "RESP2")],
+ included=[
+ _resource("customerReviewResponses", "RESP1", responseBody="thanks!", state="PUBLISHED"),
+ _resource("customerReviewResponses", "RESP2", responseBody="sorry!", state="PUBLISHED"),
+ # An included resource of another type (e.g. a review territory)
+ # must not leak into the responses table.
+ _resource("territories", "USA", currency="USD"),
+ ],
+ ),
+ }
+ )
+
+ def test_rows_come_from_included_responses_with_review_and_app_ids(self) -> None:
+ rows = _collect("review_responses", self._api(), _FakeManager())
+
+ assert [(row["app_id"], row["id"], row["review_id"], row["responseBody"]) for row in rows] == [
+ ("A1", "RESP1", "R1", "thanks!"),
+ ("A1", "RESP2", "R2", "sorry!"),
+ ]
+
+ def test_walk_requests_only_reviews_with_published_responses(self) -> None:
+ # Dropping the include param loses every row; dropping the exists filter pages
+ # through the full review history (mostly unresponded) on every sync.
+ api = self._api()
+ _collect("review_responses", api, _FakeManager())
+
+ reviews_params = next(params for url, params in api.calls if url.endswith("/v1/apps/A1/customerReviews"))
+ assert reviews_params["include"] == "response"
+ assert reviews_params["exists[publishedResponse]"] == "true"
+
+ def test_source_response_is_unpartitioned(self) -> None:
+ # The only timestamp on a response is lastModifiedDate, which changes on edit;
+ # partitioning on it would move rows between partitions.
+ response = app_store_connect_source(
+ issuer_id="issuer",
+ key_id="KEY123",
+ private_key=PRIVATE_KEY_PEM,
+ vendor_number=None,
+ endpoint="review_responses",
+ logger=MagicMock(),
+ resumable_source_manager=_FakeManager(),
+ )
+ assert response.primary_keys == ["app_id", "id"]
+ assert response.partition_mode is None
+ assert response.partition_keys is None
+
+
class TestReportColumnNames:
@parameterized.expand(
[