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): add Appfigures ad, payment and ASO tables (#99198)

Tom Owers408af5866eac
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.md b/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.md
index cf0d57137f41..8bc5ebbb74c8 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.md
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.md
@@ -384,7 +384,7 @@ Note: docs.appdynamics.com now serves an SPA shell and presents a broken TLS cha
## Appfigures — gaps
-Today (10): `categories`, `countries`, `products`, `ranks`, `ratings_report`, `revenue_report`, `reviews`, `sales_report`, `stores`, `subscriptions_report`
+Today (15): `ads_report`, `adspend_report`, `aso_keywords`, `aso_stats`, `categories`, `countries`, `payments_report`, `products`, `ranks`, `ratings_report`, `revenue_report`, `reviews`, `sales_report`, `stores`, `subscriptions_report`
Diffed against: <https://docs.appfigures.com/api/reference/v2>
@@ -392,10 +392,10 @@ Diffed against: <https://docs.appfigures.com/api/reference/v2>
- [x] `/reports/subscriptions` — subscription metrics (new, renewals, churn) that sales/revenue reports do not break out (high)
- [x] `/reports/ratings` — rating counts and averages over time, the current supported replacement for /ratings (high)
- [x] `/data/stores, /data/categories, /data/countries` — lookup tables resolving the store, category and country codes on every synced report row (high)
-- [ ] `/aso (keyword ranks and stats)` — tracked keyword positions, the other half of the ASO story with /ranks (high)
-- [ ] `/reports/adspend` — campaign spend by network, needed for ROAS against revenue_report (medium)
-- [ ] `/reports/ads` — ad publishing revenue by network, a revenue stream missing from sales_report (medium)
-- [ ] `/reports/payments` — expected payouts, reconciles revenue to cash (medium)
+- [x] `/aso (keyword ranks and stats)` — tracked keyword positions, the other half of the ASO story with /ranks (high) — synced as `aso_keywords` and `aso_stats`. /aso takes one product and one country per request and returns each keyword's latest position rather than a dated series, so both are daily snapshots fanned out over the account's products and the countries set on the source.
+- [x] `/reports/adspend` — campaign spend by network, needed for ROAS against revenue_report (medium) — synced as `adspend_report`, incremental on `date`.
+- [x] `/reports/ads` — ad publishing revenue by network, a revenue stream missing from sales_report (medium) — synced as `ads_report`, incremental on `date`.
+- [x] `/reports/payments` — expected payouts, reconciles revenue to cash (medium) — synced as `payments_report`, incremental on `date`.
- [ ] `/reports/usage` — in-app usage metrics (DAU, sessions, crashes) per product (medium)
- [ ] `/reports/estimates` — download/revenue estimates for competitor apps (medium)
- [ ] `/featured` — when and where apps were featured, a step-change driver for downloads (medium)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/appfigures/appfigures.py b/products/warehouse_sources/backend/temporal/data_imports/sources/appfigures/appfigures.py
index efde3616eab4..66299e7bafc6 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/appfigures/appfigures.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/appfigures/appfigures.py
@@ -1,4 +1,3 @@
-import dataclasses
from collections import defaultdict
from collections.abc import Iterator
from datetime import UTC, date, datetime, timedelta
@@ -8,6 +7,8 @@ import requests
from structlog.types import FilteringBoundLogger
from tenacity import retry, retry_if_exception_type, stop_after_attempt, wait_exponential_jitter
+from posthog.dataclasses import frozen
+
from products.warehouse_sources.backend.temporal.data_imports.sources.appfigures.settings import (
APPFIGURES_ENDPOINTS,
AppfiguresEndpointConfig,
@@ -29,6 +30,11 @@ REPORT_BACKFILL_DAYS = 365
PRODUCTS_PATH = "/products/mine"
NON_RANKABLE_PRODUCT_TYPES = frozenset({"inapp"})
+# /aso takes one product and one country per request and Appfigures publishes no way to list the
+# countries an account tracks keywords in, so the countries come from the source form. Fall back to
+# the US storefront, which is the one nearly every account tracks.
+DEFAULT_ASO_COUNTRIES = ("US",)
+
class AppfiguresRetryableError(Exception):
pass
@@ -43,12 +49,14 @@ class AppfiguresPageLimitError(Exception):
pass
+@frozen
class AppfiguresResumeConfig:
# "paged" endpoints (reviews): the next page number to fetch (1-based).
next_page: int | None = None
# "report" endpoints: the next date window's start (yyyy-mm-dd) to fetch.
window_start: str | None = None
+ # "aso" endpoints: the "<product_id>:<country>" fan-out target to pick back up at.
+ aso_target: str | None = None
def _headers(token: str) -> dict[str, str]:
@@ -364,6 +372,164 @@ def _iter_ranks(
manager.save_state(AppfiguresResumeConfig(window_start=window_start.isoformat()))
+def _parse_aso_countries(raw: str | None) -> tuple[str, ...]:
+ """Read the comma-separated ISO country codes from the source form.
+
+ Anything that is not a two-letter code is dropped, which keeps a typo from becoming a request
+ Appfigures rejects and bounds the fan-out to the size of the ISO country list.
+ """
+ codes = [code.strip().upper() for code in (raw or "").split(",")]
+ unique = list(dict.fromkeys(code for code in codes if len(code) == 2 and code.isalpha()))
+ return tuple(unique) or DEFAULT_ASO_COUNTRIES
+
+
+@frozen
+class AsoTarget:
+ """One /aso request's scope, because Appfigures takes a single product and country per call."""
+
+ product_id: str
+ country: str
+
+ @property
+ def key(self) -> str:
+ """Identifies the target in saved resume state."""
+ return f"{self.product_id}:{self.country}"
+
+
+def _aso_targets(
+ session: requests.Session,
+ logger: FilteringBoundLogger,
+ aso_countries: str | None,
+) -> list[AsoTarget]:
+ countries = _parse_aso_countries(aso_countries)
+ return [
+ AsoTarget(product_id=product_id, country=country)
+ for product_id in _rankable_product_ids(session, logger)
+ for country in countries
+ ]
+
+
+def _resume_aso_slice(
+ manager: ResumableSourceManager[AppfiguresResumeConfig],
+ targets: list[AsoTarget],
+) -> tuple[int, int | None]:
+ """Where a fan-out picks up: the saved target's index and, for paged endpoints, its page."""
+ resume = manager.load_state() if manager.can_resume() else None
+ if not resume or not resume.aso_target:
+ return 0, None
+ keys = [target.key for target in targets]
+ if resume.aso_target not in keys:
+ # The catalog or the country list changed since the state was saved, so start over.
+ return 0, None
+ return keys.index(resume.aso_target), resume.next_page
+
+
+def _aso_window_params(config: AppfiguresEndpointConfig, today: date) -> dict[str, Any]:
+ """The trend window /aso computes its deltas over. Bounded explicitly because Appfigures does not
+ document what range it picks when the window is left off."""
+ params: dict[str, Any] = {}
+ if config.granularity:
+ params["granularity"] = config.granularity
+ if config.start_param and config.end_param:
+ params[config.start_param] = (today - timedelta(days=(config.window_days or 30) - 1)).isoformat()
+ params[config.end_param] = today.isoformat()
+ return params
+
+
+def _iter_aso(
+ session: requests.Session,
+ config: AppfiguresEndpointConfig,
+ logger: FilteringBoundLogger,
+ manager: ResumableSourceManager[AppfiguresResumeConfig],
+ aso_countries: str | None,
+) -> Iterator[list[dict[str, Any]]]:
+ """/aso, fanned out over one product and one country per request and paged per target."""
+ targets = _aso_targets(session, logger, aso_countries)
+ if not targets:
+ logger.info("Appfigures: account has no products to track keywords for, skipping aso_keywords")
+ return
+
+ start_index, resume_page = _resume_aso_slice(manager, targets)
+ today = datetime.now(UTC).date()
+ window = _aso_window_params(config, today)
+ today_str = today.isoformat()
+ url = f"{APPFIGURES_BASE_URL}{config.path}"
+
+ for index in range(start_index, len(targets)):
+ target = targets[index]
+ page = resume_page if index == start_index and resume_page else 1
+
+ while True:
+ params: dict[str, Any] = {
+ # Appfigures supports no other pivot on this endpoint today.
+ "group_by": "keyword",
+ "products": target.product_id,
+ "countries": target.country,
+ "page": page,
+ **window,
+ }
+ try:
+ data = _fetch(session, url, params, logger)
+ except AppfiguresPageLimitError:
+ logger.info(f"Appfigures: reached page-depth cap for keywords of target={target.key}")
+ break
+
+ rows = data.get(config.data_key) or [] if config.data_key else []
+ resultset = (data.get("metadata") or {}).get("resultset") or {}
+ total_pages = resultset.get("total_pages") or 1
+ this_page = resultset.get("page") or page
+
+ if rows:
+ for row in rows:
+ # The response carries the keyword only, so the request's own identifiers and the
+ # day it ran are what make the row unique.
+ row.setdefault("date", today_str)
+ row.setdefault("product_id", target.product_id)
+ row.setdefault("country", target.country)
+ yield rows
+
+ if not rows or this_page >= total_pages:
+ break
+
+ page += 1
+ # Save AFTER yielding so a crash re-fetches the page we were on rather than skipping it.
+ manager.save_state(AppfiguresResumeConfig(aso_target=target.key, next_page=page))
+
+ if index + 1 < len(targets):
+ manager.save_state(AppfiguresResumeConfig(aso_target=targets[index + 1].key))
+
+
+def _iter_aso_stats(
+ session: requests.Session,
+ config: AppfiguresEndpointConfig,
+ logger: FilteringBoundLogger,
+ manager: ResumableSourceManager[AppfiguresResumeConfig],
+ aso_countries: str | None,
+) -> Iterator[list[dict[str, Any]]]:
+ """/aso/stats, one flat object of keyword aggregates per product and country."""
+ targets = _aso_targets(session, logger, aso_countries)
+ if not targets:
+ logger.info("Appfigures: account has no products to track keywords for, skipping aso_stats")
+ return
+
+ start_index, _ = _resume_aso_slice(manager, targets)
+ today = datetime.now(UTC).date()
+ window = _aso_window_params(config, today)
+ today_str = today.isoformat()
+ url = f"{APPFIGURES_BASE_URL}{config.path}"
+
+ for index in range(start_index, len(targets)):
+ target = targets[index]
+ params: dict[str, Any] = {"products": target.product_id, "countries": target.country, **window}
+ data = _fetch(session, url, params, logger)
+
+ if isinstance(data, dict) and data:
+ yield [{"date": today_str, "product_id": target.product_id, "country": target.country, **data}]
+
+ if index + 1 < len(targets):
+ manager.save_state(AppfiguresResumeConfig(aso_target=targets[index + 1].key))
+
+
def get_rows(
token: str,
endpoint: str,
@@ -371,6 +537,7 @@ def get_rows(
resumable_source_manager: ResumableSourceManager[AppfiguresResumeConfig],
should_use_incremental_field: bool = False,
db_incremental_field_last_value: Any = None,
+ aso_countries: str | None = None,
) -> Iterator[list[dict[str, Any]]]:
config = APPFIGURES_ENDPOINTS[endpoint]
session = make_tracked_session(headers=_headers(token), redact_values=(token,))
@@ -386,6 +553,10 @@ def get_rows(
should_use_incremental_field,
db_incremental_field_last_value,
)
+ elif config.kind == "aso":
+ yield from _iter_aso(session, config, logger, resumable_source_manager, aso_countries)
+ elif config.kind == "aso_stats":
+ yield from _iter_aso_stats(session, config, logger, resumable_source_manager, aso_countries)
elif config.kind == "ranks":
yield from _iter_ranks(
session,
@@ -413,6 +584,7 @@ def appfigures_source(
resumable_source_manager: ResumableSourceManager[AppfiguresResumeConfig],
should_use_incremental_field: bool = False,
db_incremental_field_last_value: Optional[Any] = None,
+ aso_countries: Optional[str] = None,
) -> SourceResponse:
config = APPFIGURES_ENDPOINTS[endpoint]
@@ -425,6 +597,7 @@ def appfigures_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,
+ aso_countries=aso_countries,
),
primary_keys=config.primary_keys,
partition_count=1,
@@ -434,6 +607,7 @@ def appfigures_source(
partition_keys=[config.partition_key] if config.partition_key else None,
# Reviews are paged ascending by `date`; reports and ranks are emitted oldest-window-first,
# ranks buffering each window so its product chunks merge back into date order. All arrive
- # ascending so the incremental watermark checkpoints correctly.
+ # ascending so the incremental watermark checkpoints correctly. The ASO tables are snapshots
+ # of a single day, so ordering is moot for them.
sort_mode="asc",
)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/appfigures/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/appfigures/canonical_descriptions.py
index 52cefd1aacd1..e95c77d500ca 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/appfigures/canonical_descriptions.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/appfigures/canonical_descriptions.py
@@ -131,6 +131,46 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
"five_star_percent": "Share of standing ratings that are five stars.",
},
},
+ "ads_report": {
+ "description": "Daily ad publishing report aggregated across the account — how many ad requests each network filled and what those ads earned, one row per day.",
+ "docs_url": "https://docs.appfigures.com/api/reference/v2/ads",
+ "columns": {
+ "date": "Calendar day the metrics cover (yyyy-mm-dd).",
+ "requests": "Ad requests made to the ad networks. Networks that do not report requests count zero.",
+ "requests_filled": "Requests the network filled with an ad. Equivalent to impressions for most networks.",
+ "impressions": "Requests that resulted in an ad being seen.",
+ "fillrate": "Share of requests that were filled, between 0 and 1.",
+ "ecpm": "Effective cost per thousand impressions, as reported by the ad network.",
+ "clicks": "Times an ad was clicked.",
+ "ctr": "Click-through rate, between 0 and 1.",
+ "revenue": "Ad revenue earned on the day, in the currency of the connected Appfigures account.",
+ },
+ },
+ "adspend_report": {
+ "description": "Daily ad spend report aggregated across the account — what user-acquisition campaigns cost and what they delivered, one row per day.",
+ "docs_url": "https://docs.appfigures.com/api/reference/v2/ad-spend",
+ "columns": {
+ "date": "Calendar day the metrics cover (yyyy-mm-dd).",
+ "installs": "Installs the ad campaigns generated on the day.",
+ "clicks": "Times a campaign ad was clicked or tapped.",
+ "impressions": "Times a campaign ad was seen.",
+ "cost": "Total spent on campaigns on the day.",
+ "cpc": "Average cost of a single click.",
+ "cpa": "Average cost of a single install.",
+ "ctr": "Click-through rate across the campaigns, between 0 and 1.",
+ },
+ },
+ "payments_report": {
+ "description": "Daily payments report aggregated across the account — the payouts to expect from app sales, in-app purchases, and ad revenue, one row per day.",
+ "docs_url": "https://docs.appfigures.com/api/reference/v2/payments",
+ "columns": {
+ "date": "Calendar day the metrics cover (yyyy-mm-dd).",
+ "revenue": "The most accurate payment figure available for the day. It starts as the estimate, becomes the financial figure about a month after the fiscal month closes, then the converted figure about a month later.",
+ "estimated_revenue": "Amount expected to be paid at the end of the month, based on the daily reports. Available for every store.",
+ "financial_revenue": "Amount to be paid, from the store's own financial reports. Apple products only, and published about a month after the fiscal month closes.",
+ "converted_revenue": "Amount that has been paid and matches the store's deposit. Apple products only, and published about two months after the fiscal month closes.",
+ },
+ },
"ranks": {
"description": "Store category rank history, one row per product, country, category chart, and day. Rows are only written for days the product actually held a rank, and cover the country Appfigures returns by default (the United States).",
"docs_url": "https://docs.appfigures.com/api/reference/v2/ranks",
@@ -148,6 +188,47 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
"delta": "Change in position that Appfigures reports alongside the rank. Appfigures measures this against the prior hour even at daily granularity, so it is not a day-over-day move.",
},
},
+ "aso_keywords": {
+ "description": "Daily snapshot of where each product ranks in store search for every keyword tracked in Appfigures. Appfigures returns the latest position rather than a dated series, so a row records what the sync saw that day, for the countries set on the source.",
+ "docs_url": "https://docs.appfigures.com/api/reference/v2/aso",
+ "columns": {
+ "date": "Day the snapshot was taken (yyyy-mm-dd).",
+ "product_id": "Appfigures product id the keyword is tracked for. Joins to products.id.",
+ "country": "ISO code of the storefront the position was searched in. Joins to countries.iso.",
+ "keyword_id": "Appfigures id of the tracked keyword.",
+ "keyword_term": "The search term itself. May include emoji.",
+ "position": "Position the product holds in the search results for the term.",
+ "delta": "Positions moved between the latest scan and the one before it.",
+ "last_change": "Date the position last changed. Absent when the position has not moved.",
+ "num_apps": "Total number of apps that rank for the term.",
+ "popularity": "How often the term is searched, from 1 to 100. Not available on every Appfigures plan.",
+ "competitiveness": "How hard the term is to rank for, from 1 to 100. Not available on every Appfigures plan.",
+ },
+ },
+ "aso_stats": {
+ "description": "Daily snapshot summarizing the tracked keyword set for one product in one country — average position, how many keywords sit near the top of search, and how many moved.",
+ "docs_url": "https://docs.appfigures.com/api/reference/v2/aso",
+ "columns": {
+ "date": "Day the snapshot was taken (yyyy-mm-dd).",
+ "product_id": "Appfigures product id the keywords are tracked for. Joins to products.id.",
+ "country": "ISO code of the storefront the positions were searched in. Joins to countries.iso.",
+ "avg_position": "Average of the latest positions, excluding keywords the product does not rank for.",
+ "avg_position_delta": "Change in the average position.",
+ "highest": "Best position the product holds across the tracked keywords, where 1 is best.",
+ "highest_delta": "Largest improvement in position across the tracked keywords.",
+ "lowest": "Worst position the product holds across the tracked keywords.",
+ "lowest_delta": "Largest drop in position across the tracked keywords.",
+ "top_5": "Tracked keywords the product ranks in the top 5 for.",
+ "top_25": "Tracked keywords the product ranks in the top 25 for.",
+ "top_100": "Tracked keywords the product ranks in the top 100 for.",
+ "ranked_keywords": "Tracked keywords the product holds any position for.",
+ "unranked_keywords": "Tracked keywords the product holds no position for.",
+ "total_keywords": "Keywords tracked for the product in this country.",
+ "positive": "Tracked keywords whose position improved.",
+ "negative": "Tracked keywords whose position dropped.",
+ "unchanged": "Tracked keywords whose position did not move.",
+ },
+ },
"stores": {
"description": "Reference table of the stores Appfigures supports, with the features and storefronts each one offers. Resolves the store codes on products and ranks.",
"docs_url": "https://docs.appfigures.com/api/reference/v2/data",
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/appfigures/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/appfigures/settings.py
index f630ec62081c..ab85489c11fc 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/appfigures/settings.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/appfigures/settings.py
@@ -16,7 +16,12 @@ from products.warehouse_sources.backend.types import IncrementalField, Increment
# - "ranks": /ranks — a columnar response (a `dates` array plus one series per product/country/
# category holding position/delta arrays) whose product ids and date range live in the
# URL path, so we fan out over the account's products in chunks and walk date windows.
-EndpointKind = Literal["paged", "object", "report", "ranks"]
+# - "aso": /aso — a paginated list of the keywords tracked for one product in one country, each
+# carrying its latest position rather than a dated series. One product and one country
+# per request, so we fan out over both and stamp the day the sync ran.
+# - "aso_stats": /aso/stats — the same fan-out, but a single flat object of keyword aggregates per
+# product and country instead of a list.
+EndpointKind = Literal["paged", "object", "report", "ranks", "aso", "aso_stats"]
@frozen
@@ -39,6 +44,9 @@ class AppfiguresEndpointConfig:
data_key: Optional[str] = None
# Query param name for the server-side creation-date lower bound (yyyy-mm-dd), if any.
start_param: Optional[str] = None
+ # Upper bound param paired with `start_param`. /aso spells the pair start_date/end_date and
+ # /aso/stats spells it start/end, so both names come from the config.
+ end_param: Optional[str] = None
# Sort param value to force a stable ascending order so the incremental watermark advances.
sort: Optional[str] = None
page_size: int = 500
@@ -148,6 +156,47 @@ APPFIGURES_ENDPOINTS: dict[str, AppfiguresEndpointConfig] = {
default_incremental_field="date",
incremental_fields=[_REPORT_DATE_FIELD],
),
+ # Daily ad-publishing revenue by network: requests, fill rate, impressions, eCPM, and the
+ # revenue those ads earned, which the sales and revenue reports do not cover.
+ "ads_report": AppfiguresEndpointConfig(
+ name="ads_report",
+ path="/reports/ads",
+ kind="report",
+ primary_keys=["date"],
+ group_by="dates",
+ granularity="daily",
+ window_days=30,
+ partition_key="date",
+ default_incremental_field="date",
+ incremental_fields=[_REPORT_DATE_FIELD],
+ ),
+ # Daily user-acquisition campaign spend: installs, clicks, impressions, cost, CPC, and CPA, so
+ # spend can be set against the revenue report.
+ "adspend_report": AppfiguresEndpointConfig(
+ name="adspend_report",
+ path="/reports/adspend",
+ kind="report",
+ primary_keys=["date"],
+ group_by="dates",
+ granularity="daily",
+ window_days=30,
+ partition_key="date",
+ default_incremental_field="date",
+ incremental_fields=[_REPORT_DATE_FIELD],
+ ),
+ # Daily expected payouts, which reconcile recognized revenue to the cash the stores pay out.
+ "payments_report": AppfiguresEndpointConfig(
+ name="payments_report",
+ path="/reports/payments",
+ kind="report",
+ primary_keys=["date"],
+ group_by="dates",
+ granularity="daily",
+ window_days=30,
+ partition_key="date",
+ default_incremental_field="date",
+ incremental_fields=[_REPORT_DATE_FIELD],
+ ),
# Store category rank history per product, country, and category.
"ranks": AppfiguresEndpointConfig(
name="ranks",
@@ -165,6 +214,42 @@ APPFIGURES_ENDPOINTS: dict[str, AppfiguresEndpointConfig] = {
# reviews both need `public:read`, so probing reviews checks the same grant.
probe_path="/reviews",
),
+ # Search position of every keyword tracked in Appfigures, per product and country. Appfigures
+ # returns the latest position rather than a dated series, so each sync stamps the day it ran and
+ # the table builds up a daily snapshot per keyword.
+ "aso_keywords": AppfiguresEndpointConfig(
+ name="aso_keywords",
+ path="/aso",
+ kind="aso",
+ primary_keys=["date", "product_id", "country", "keyword_id"],
+ data_key="results",
+ start_param="start_date",
+ end_param="end_date",
+ granularity="daily",
+ window_days=30,
+ partition_key="date",
+ # One request per product per country, paginated. Requests cost account credits, so leave it
+ # to the user to turn on once they have picked the countries they track keywords in.
+ should_sync_default=False,
+ # /aso needs a product and a country, so there is no cheap request to probe. The fan-out
+ # reads the product catalog before anything else, so probe that instead.
+ probe_path="/products/mine",
+ ),
+ # Per-product, per-country summary of the tracked keyword set: average position, how many
+ # keywords sit in the top 5/25/100, and how many moved up or down.
+ "aso_stats": AppfiguresEndpointConfig(
+ name="aso_stats",
+ path="/aso/stats",
+ kind="aso_stats",
+ primary_keys=["date", "product_id", "country"],
+ start_param="start",
+ end_param="end",
+ granularity="daily",
+ window_days=30,
+ partition_key="date",
+ should_sync_default=False,
+ probe_path="/products/mine",
+ ),
# Store metadata resolving the `store` / `store_id` codes on products and rank rows.
"stores": AppfiguresEndpointConfig(
name="stores",
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/appfigures/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/appfigures/source.py
index 6969d0635cf5..a06c3a105db9 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/appfigures/source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/appfigures/source.py
@@ -57,10 +57,10 @@ class AppfiguresSource(ResumableSource[AppfiguresSourceConfig, AppfiguresResumeC
Create an API client and Personal Access Token at [appfigures.com/developers/keys](https://appfigures.com/developers/keys). When creating the client, grant the data sets you want to sync:
- `products:read` — Products
-- `public:read` — Reviews, Ranks, Ratings report
-- `private:read` — Sales, Revenue, and Subscriptions reports
+- `public:read` — Reviews, Ranks, Ratings report, ASO keywords and stats
+- `private:read` — Sales, Revenue, Subscriptions, Ads, Ad spend, and Payments reports
-Stores, Categories, and Countries are reference tables that need no data set granted.
+Stores, Categories, and Countries are reference tables that need no data set granted. The ASO tables only return rows for the apps and countries you track keywords for in Appfigures.
""",
iconPath="/static/services/appfigures.png",
docsUrl="https://posthog.com/docs/cdp/sources/appfigures",
@@ -75,6 +75,15 @@ Stores, Categories, and Countries are reference tables that need no data set gra
placeholder="pat_...",
secret=True,
),
+ SourceFieldInputConfig(
+ name="aso_countries",
+ label="ASO keyword countries (optional)",
+ type=SourceFieldInputConfigType.TEXT,
+ required=False,
+ placeholder="US, GB, DE",
+ secret=False,
+ caption="Country codes to pull tracked keyword positions for, comma-separated. Appfigures takes one country per request, so each code adds a request per app. Only the ASO keywords and ASO stats tables use it. They cover the United States when left blank.",
+ ),
],
),
)
@@ -171,4 +180,5 @@ Stores, Categories, and Countries are reference tables that need no data set gra
db_incremental_field_last_value=inputs.db_incremental_field_last_value
if inputs.should_use_incremental_field
else None,
+ aso_countries=config.aso_countries,
)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/appfigures/tests/test_appfigures.py b/products/warehouse_sources/backend/temporal/data_imports/sources/appfigures/tests/test_appfigures.py
index b7ae7ee075b9..741211b66c08 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/appfigures/tests/test_appfigures.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/appfigures/tests/test_appfigures.py
@@ -13,6 +13,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.appfigures
_flatten_report,
_headers,
_is_page_limit_response,
+ _parse_aso_countries,
_to_date_str,
appfigures_source,
check_credentials,
@@ -466,6 +467,269 @@ class TestIterRanks:
assert fetch.call_count == 1
+class TestParseAsoCountries:
+ @pytest.mark.parametrize(
+ "raw,expected",
+ [
+ (None, ("US",)),
+ ("", ("US",)),
+ (" ", ("US",)),
+ (",,", ("US",)),
+ ("gb", ("GB",)),
+ ("US, GB ,de", ("US", "GB", "DE")),
+ # A code repeated in the form would otherwise fan out twice and seed duplicate rows.
+ ("US,us", ("US",)),
+ # Anything that isn't a two-letter code would only ever be a request Appfigures rejects.
+ ("US, United Kingdom, 1, ??", ("US",)),
+ ],
+ )
+ def test_parse(self, raw: str | None, expected: tuple[str, ...]):
+ assert _parse_aso_countries(raw) == expected
+
+
+def _aso_page(results: list[dict[str, Any]], page: int = 1, total_pages: int = 1) -> dict[str, Any]:
+ return {
+ "metadata": {"resultset": {"count": 500, "page": page, "total_pages": total_pages, "total_count": 1}},
+ "results": results,
+ }
+
+
+class TestIterAso:
+ @time_machine.travel("2024-02-15", tick=False)
+ def test_fans_out_over_products_and_countries_stamping_row_identity(self):
+ def fake_fetch(_session, url, params, _logger):
+ if url.endswith(appfigures.PRODUCTS_PATH):
+ return {"1": {"id": 1, "type": "app"}, "2": {"id": 2, "type": "app"}, "9": {"id": 9, "type": "inapp"}}
+ return _aso_page([{"keyword_id": "k1", "keyword_term": "stream tv", "position": 12}])
+
+ with mock.patch(f"{_MODULE}._fetch", side_effect=fake_fetch) as fetch:
+ batches = list(
+ get_rows(
+ token="pat",
+ endpoint="aso_keywords",
+ logger=mock.MagicMock(),
+ resumable_source_manager=_manager(),
+ aso_countries="US,GB",
+ )
+ )
+
+ requested = [(c.args[2]["products"], c.args[2]["countries"]) for c in fetch.call_args_list[1:]]
+ # Two rankable products x two countries, one product and one country per request. The in-app
+ # purchase holds no keyword ranks, so it is left out.
+ assert requested == [("1", "US"), ("1", "GB"), ("2", "US"), ("2", "GB")]
+ rows = [row for batch in batches for row in batch]
+ assert [(r["date"], r["product_id"], r["country"], r["keyword_id"]) for r in rows] == [
+ ("2024-02-15", "1", "US", "k1"),
+ ("2024-02-15", "1", "GB", "k1"),
+ ("2024-02-15", "2", "US", "k1"),
+ ("2024-02-15", "2", "GB", "k1"),
+ ]
+
+ @time_machine.travel("2024-02-15", tick=False)
+ def test_request_carries_keyword_pivot_and_bounded_window(self):
+ def fake_fetch(_session, url, _params, _logger):
+ if url.endswith(appfigures.PRODUCTS_PATH):
+ return {"1": {"id": 1, "type": "app"}}
+ return _aso_page([])
+
+ with mock.patch(f"{_MODULE}._fetch", side_effect=fake_fetch) as fetch:
+ list(
+ get_rows(
+ token="pat",
+ endpoint="aso_keywords",
+ logger=mock.MagicMock(),
+ resumable_source_manager=_manager(),
+ )
+ )
+ params = fetch.call_args_list[1].args[2]
+ assert params["group_by"] == "keyword"
+ assert params["granularity"] == "daily"
+ # The 30-day window the deltas are computed over, sent explicitly so Appfigures doesn't pick
+ # its own undocumented range.
+ assert (params["start_date"], params["end_date"]) == ("2024-01-17", "2024-02-15")
+
+ @time_machine.travel("2024-02-15", tick=False)
+ def test_walks_pages_per_target_and_saves_state_after_each(self):
+ def fake_fetch(_session, url, params, _logger):
+ if url.endswith(appfigures.PRODUCTS_PATH):
+ return {"1": {"id": 1, "type": "app"}, "2": {"id": 2, "type": "app"}}
+ page = params["page"]
+ return _aso_page([{"keyword_id": f"k{page}", "position": page}], page=page, total_pages=2)
+
+ manager = _manager()
+ with mock.patch(f"{_MODULE}._fetch", side_effect=fake_fetch) as fetch:
+ batches = list(
+ get_rows(
+ token="pat",
+ endpoint="aso_keywords",
+ logger=mock.MagicMock(),
+ resumable_source_manager=manager,
+ aso_countries="US",
+ )
+ )
+
+ assert [(c.args[2]["products"], c.args[2]["page"]) for c in fetch.call_args_list[1:]] == [
+ ("1", 1),
+ ("1", 2),
+ ("2", 1),
+ ("2", 2),
+ ]
+ assert len([row for batch in batches for row in batch]) == 4
+ # Saved after yielding: the next page of the current target, then the next target.
+ assert manager.save_state.call_args_list == [
+ mock.call(AppfiguresResumeConfig(aso_target="1:US", next_page=2)),
+ mock.call(AppfiguresResumeConfig(aso_target="2:US")),
+ mock.call(AppfiguresResumeConfig(aso_target="2:US", next_page=2)),
+ ]
+
+ @time_machine.travel("2024-02-15", tick=False)
+ def test_resume_skips_targets_already_walked(self):
+ def fake_fetch(_session, url, _params, _logger):
+ if url.endswith(appfigures.PRODUCTS_PATH):
+ return {str(index): {"id": index, "type": "app"} for index in (1, 2, 3)}
+ return _aso_page([])
+
+ with mock.patch(f"{_MODULE}._fetch", side_effect=fake_fetch) as fetch:
+ list(
+ get_rows(
+ token="pat",
+ endpoint="aso_keywords",
+ logger=mock.MagicMock(),
+ resumable_source_manager=_manager(AppfiguresResumeConfig(aso_target="2:US", next_page=3)),
+ aso_countries="US",
+ )
+ )
+ assert [(c.args[2]["products"], c.args[2]["page"]) for c in fetch.call_args_list[1:]] == [("2", 3), ("3", 1)]
+
+ @time_machine.travel("2024-02-15", tick=False)
+ def test_resume_target_missing_from_catalog_starts_over(self):
+ def fake_fetch(_session, url, _params, _logger):
+ if url.endswith(appfigures.PRODUCTS_PATH):
+ return {"1": {"id": 1, "type": "app"}}
+ return _aso_page([])
+
+ with mock.patch(f"{_MODULE}._fetch", side_effect=fake_fetch) as fetch:
+ list(
+ get_rows(
+ token="pat",
+ endpoint="aso_keywords",
+ logger=mock.MagicMock(),
+ resumable_source_manager=_manager(AppfiguresResumeConfig(aso_target="404:US", next_page=7)),
+ aso_countries="US",
+ )
+ )
+ assert [(c.args[2]["products"], c.args[2]["page"]) for c in fetch.call_args_list[1:]] == [("1", 1)]
+
+ @time_machine.travel("2024-02-15", tick=False)
+ def test_page_limit_stops_the_target_and_moves_to_the_next(self):
+ products = _response(200)
+ products.json.return_value = {"1": {"id": 1, "type": "app"}, "2": {"id": 2, "type": "app"}}
+ first_page = _response(200)
+ first_page.json.return_value = _aso_page([{"keyword_id": "k1"}], page=1, total_pages=9)
+ page_limit = _response(400, reason=_PAGE_LIMIT_REASON)
+ second_target = _response(200)
+ second_target.json.return_value = _aso_page([{"keyword_id": "k2"}])
+
+ session = mock.MagicMock()
+ session.get.side_effect = [products, first_page, page_limit, second_target]
+
+ with mock.patch(f"{_MODULE}.make_tracked_session", return_value=session):
+ batches = list(
+ get_rows(
+ token="pat",
+ endpoint="aso_keywords",
+ logger=mock.MagicMock(),
+ resumable_source_manager=_manager(),
+ aso_countries="US",
+ )
+ )
+
+ assert [row["keyword_id"] for batch in batches for row in batch] == ["k1", "k2"]
+ assert session.get.call_count == 4
+
+ def test_account_with_no_rankable_products_makes_no_aso_request(self):
+ with mock.patch(f"{_MODULE}._fetch", return_value={"9": {"id": 9, "type": "inapp"}}) as fetch:
+ batches = list(
+ get_rows(
+ token="pat",
+ endpoint="aso_keywords",
+ logger=mock.MagicMock(),
+ resumable_source_manager=_manager(),
+ )
+ )
+ assert batches == []
+ assert fetch.call_count == 1
+
+
+class TestIterAsoStats:
+ @time_machine.travel("2024-02-15", tick=False)
+ def test_one_row_per_target_with_identity_and_window(self):
+ def fake_fetch(_session, url, params, _logger):
+ if url.endswith(appfigures.PRODUCTS_PATH):
+ return {"1": {"id": 1, "type": "app"}, "2": {"id": 2, "type": "app"}}
+ return {"avg_position": 21, "top_5": 1, "total_keywords": 5, "_asked": params["products"]}
+
+ manager = _manager()
+ with mock.patch(f"{_MODULE}._fetch", side_effect=fake_fetch) as fetch:
+ batches = list(
+ get_rows(
+ token="pat",
+ endpoint="aso_stats",
+ logger=mock.MagicMock(),
+ resumable_source_manager=manager,
+ aso_countries="US",
+ )
+ )
+
+ assert [len(batch) for batch in batches] == [1, 1]
+ rows = [row for batch in batches for row in batch]
+ assert [(r["date"], r["product_id"], r["country"], r["avg_position"]) for r in rows] == [
+ ("2024-02-15", "1", "US", 21),
+ ("2024-02-15", "2", "US", 21),
+ ]
+ # /aso/stats spells its window start/end rather than start_date/end_date.
+ params = fetch.call_args_list[1].args[2]
+ assert (params["start"], params["end"]) == ("2024-01-17", "2024-02-15")
+ manager.save_state.assert_called_once_with(AppfiguresResumeConfig(aso_target="2:US"))
+
+ @time_machine.travel("2024-02-15", tick=False)
+ def test_empty_stats_body_yields_nothing(self):
+ def fake_fetch(_session, url, _params, _logger):
+ if url.endswith(appfigures.PRODUCTS_PATH):
+ return {"1": {"id": 1, "type": "app"}}
+ return {}
+
+ with mock.patch(f"{_MODULE}._fetch", side_effect=fake_fetch):
+ batches = list(
+ get_rows(
+ token="pat",
+ endpoint="aso_stats",
+ logger=mock.MagicMock(),
+ resumable_source_manager=_manager(),
+ )
+ )
+ assert batches == []
+
+ @time_machine.travel("2024-02-15", tick=False)
+ def test_resume_skips_targets_already_walked(self):
+ def fake_fetch(_session, url, _params, _logger):
+ if url.endswith(appfigures.PRODUCTS_PATH):
+ return {str(index): {"id": index, "type": "app"} for index in (1, 2, 3)}
+ return {"avg_position": 1}
+
+ with mock.patch(f"{_MODULE}._fetch", side_effect=fake_fetch) as fetch:
+ list(
+ get_rows(
+ token="pat",
+ endpoint="aso_stats",
+ logger=mock.MagicMock(),
+ resumable_source_manager=_manager(AppfiguresResumeConfig(aso_target="3:US")),
+ aso_countries="US",
+ )
+ )
+ assert [c.args[2]["products"] for c in fetch.call_args_list[1:]] == ["3"]
+
+
class TestCheckCredentials:
@pytest.mark.parametrize("status", [200, 401, 403, 500])
def test_returns_status_code(self, status):
@@ -490,6 +754,8 @@ class TestAppfiguresSourceResponse:
("sales_report", ["date"], "date"),
("revenue_report", ["date"], "date"),
("ranks", ["date", "product_id", "country", "category_id", "category_subtype"], "date"),
+ ("aso_keywords", ["date", "product_id", "country", "keyword_id"], "date"),
+ ("aso_stats", ["date", "product_id", "country"], "date"),
# The /data lookups carry no date field, so they sync unpartitioned.
("stores", ["id"], None),
("categories", ["id"], None),
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/appfigures/tests/test_appfigures_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/appfigures/tests/test_appfigures_source.py
index 7affd5f35087..c3286dc4add6 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/appfigures/tests/test_appfigures_source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/appfigures/tests/test_appfigures_source.py
@@ -24,11 +24,22 @@ class TestAppfiguresSource:
def test_catalog_and_lookup_tables_are_full_refresh_dated_tables_incremental(self):
schemas = {s.name: s for s in self.source.get_schemas(self.config, self.team_id)}
- # The product catalog and the /data lookups have no server-side date filter to drive.
- for name in ("products", "stores", "categories", "countries"):
+ # The product catalog, the /data lookups, and the ASO snapshots have no server-side date
+ # filter to drive, because /aso reports each keyword's latest position, not a dated series.
+ for name in ("products", "stores", "categories", "countries", "aso_keywords", "aso_stats"):
assert schemas[name].supports_incremental is False
assert schemas[name].incremental_fields == []
- for name in ("reviews", "sales_report", "revenue_report", "subscriptions_report", "ratings_report", "ranks"):
+ for name in (
+ "reviews",
+ "sales_report",
+ "revenue_report",
+ "subscriptions_report",
+ "ratings_report",
+ "ads_report",
+ "adspend_report",
+ "payments_report",
+ "ranks",
+ ):
assert schemas[name].supports_incremental is True
assert [f["field"] for f in schemas[name].incremental_fields] == ["date"]
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/appfigures.py b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/appfigures.py
index a056f3446d15..6fda774dd860 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/appfigures.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/appfigures.py
@@ -7,3 +7,4 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common imp
@config.config
class AppfiguresSourceConfig(config.Config):
personal_access_token: str
+ aso_countries: str | None = None