: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 appfollow import source (#67837)
Tom Owers4d6a72d941f8
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.mdindex c74959e16633..04eb259accfe 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md@@ -56,6 +56,7 @@ the row lists both.| apify_dataset | HTTP | requests | ✅ || apollo | HTTP | requests | ✅ || appfigures | HTTP | requests | ✅ |+| appfollow | HTTP | requests | ✅ || appsflyer | HTTP (CSV reports) | requests | ✅ || asana | HTTP | requests | ✅ || ashby | HTTP | requests | ✅ |@@ -376,7 +377,6 @@ doesn't conflict with concurrent PRs.- amazon_sns- amazon_sqs- appcues-- appfollow- apple_search_ads- appstack- apptivodiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/appfollow/api_inventory.md b/products/warehouse_sources/backend/temporal/data_imports/sources/appfollow/api_inventory.mdnew file mode 100644index 000000000000..4a44e063cc02--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/appfollow/api_inventory.md@@ -0,0 +1,50 @@+# AppFollow API inventory++Reference for the endpoints this source syncs. AppFollow API v2, base URL `https://api.appfollow.io/api/v2`,+auth via the `X-AppFollow-API-Token` header. Docs: <https://docs.api.appfollow.io/reference/overview>.++> **Verification status:** the response shapes below are reconstructed from the public API docs and the+> open-source Airbyte `source-appfollow` connector (which confirms `app_collections`, `app_lists`,+> `users`, and `ratings` shapes). We did **not** have an API token to curl-verify the `reviews` and+> `ratings_history` request/response details live, so a few field names and the `last_modified` format+> are best-effort — see the inline notes in `appfollow.py`.++## Cost & limits++- Rate limits: 1000 requests/hour per token, 10000 requests/hour per account.+- Credit-based cost model: 1–100 credits per request. Reviews cost 10 credits/request; ratings history+ costs 10 credits plus a recurring per-30-day charge. Hence `reviews` default-syncs but+ `ratings_history` and `users` are opt-in.+- Pagination only functions when filtering by `ext_id` (not `collection_name`), so every per-app+ fan-out request passes `ext_id`.++## Endpoints++| Schema | Path | Shape | Rows under | Primary key | Incremental | Default sync |+| ----------------- | ----------------------------------------------------------------------- | ------------------------------------- | ---------- | ----------------------------- | ----------------------------- | ------------ |+| `app_collections` | `/account/apps` | single request | `apps` | `[id]` | — (full refresh) | ✅ |+| `app_lists` | `/account/apps/app?apps_id=<id>` | fan-out over collections | `apps_app` | `[app_collection_id, app_id]` | — (full refresh) | ✅ |+| `users` | `/account/users` | single request | root list | `[id]` | — (full refresh) | ❌ |+| `reviews` | `/reviews?ext_id=<ext_id>&from=&to=&page=` | fan-out over apps, page/`pages_count` | `reviews` | `[ext_id, review_id]` | `updated` via `last_modified` | ✅ |+| `ratings_history` | `/meta/ratings/history?ext_id=<ext_id>&store=&from=&to=&offset=&limit=` | fan-out over apps, offset/limit | `ratings` | `[ext_id, store, date]` | `date` via `from` | ❌ |++## Discovery chain++AppFollow is app-centric: most data is queried per app by its store `ext_id`, and the only way to+enumerate a workspace's apps is:++```text+/account/apps -> collections (id, title, title_normalized)+ /account/apps/app?apps_id=<id> -> apps (ext_id, store, app_id) per collection+```++`reviews` and `ratings_history` iterate the discovered apps. `reviews` keys on `ext_id`;+`ratings_history` also needs `store` (and passes `collection_name` from the parent collection).++## Incremental notes++- `reviews`: the `updated` field is the review's last-modified timestamp; the server-side `last_modified`+ filter drives the delta. `from`/`to` are required and filter the publication `date`, so we open the+ window to `DEFAULT_START_DATE`..today and let `last_modified` do the incremental work.+- `ratings_history`: `type=total` returns one dated snapshot per day; the `from` date filter is the+ incremental cursor (past snapshots don't change, so `from`=watermark is safe).diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/appfollow/appfollow.py b/products/warehouse_sources/backend/temporal/data_imports/sources/appfollow/appfollow.pynew file mode 100644index 000000000000..16abc72f995b--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/appfollow/appfollow.py@@ -0,0 +1,423 @@+import dataclasses+from collections.abc import Iterator+from datetime import UTC, date, datetime+from typing import Any, Optional++import requests+from structlog.types import FilteringBoundLogger+from tenacity import retry, retry_if_exception_type, stop_after_attempt, wait_exponential_jitter++from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import SourceResponse+from products.warehouse_sources.backend.temporal.data_imports.sources.appfollow.settings import (+ APPFOLLOW_ENDPOINTS,+ DEFAULT_START_DATE,+ AppfollowEndpointConfig,+)+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++APPFOLLOW_BASE_URL = "https://api.appfollow.io/api/v2"++# Ratings history is offset/limit paginated; reviews use page/pages_count. Both cap a page at 100 rows.+DEFAULT_PAGE_SIZE = 100+++class AppfollowRetryableError(Exception):+ pass+++class AppfollowResumeConfig:+ # Fan-out bookmark: the store `ext_id` currently being processed. A stable id (not a positional+ # index) so apps added/removed between a crash and the retry can't resume us into the wrong app.+ # `None` for the top-level (`app_collections`, `users`, `app_lists`) endpoints.+ ext_id: str | None = None+ # Pagination cursor within the current app's resource: 1-indexed `page` for reviews, or the row+ # `offset` for ratings history.+ cursor: int | None = None+++def _headers(api_key: str) -> dict[str, str]:+ return {"X-AppFollow-API-Token": api_key, "Accept": "application/json"}+++def _today_str() -> str:+ return datetime.now(UTC).date().isoformat()+++def _to_date_str(value: Any) -> str | None:+ """Format a datetime/date/ISO-string value as the yyyy-mm-dd AppFollow date filters expect."""+ if value is None:+ return None+ if isinstance(value, datetime):+ return value.astimezone(UTC).date().isoformat() if value.tzinfo else value.date().isoformat()+ if isinstance(value, date):+ return value.isoformat()+ text = str(value)[:10]+ try:+ date.fromisoformat(text)+ except ValueError:+ return None+ return text+++def _to_datetime_str(value: Any) -> str | None:+ """Format the reviews `last_modified` filter value.++ AppFollow documents `last_modified` as a date-time; the exact accepted format isn't published and+ we have no credentials to probe it, so we send `YYYY-MM-DD HH:MM:SS` (UTC). A `date` is widened to+ the start of that day.+ """+ 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).strftime("%Y-%m-%d %H:%M:%S")+ if isinstance(value, date):+ return f"{value.isoformat()} 00:00:00"+ return str(value)+++def _clamp_future_value_to_now(value: Any) -> Any:+ """Cap a future datetime/date incremental cursor at now.++ A future-dated record would push the cursor past now, and every later sync would then filter on a+ future timestamp — a no-op that can silently freeze the table. Clamping keeps the filter meaningful+ and lets the sync self-heal.+ """+ now = datetime.now(UTC)+ if isinstance(value, datetime):+ aware = value if value.tzinfo is not None else value.replace(tzinfo=UTC)+ return now if aware > now else value+ if isinstance(value, date):+ return now.date() if value > now.date() else value+ return value+++@retry(+ retry=retry_if_exception_type(+ (+ AppfollowRetryableError,+ requests.ReadTimeout,+ requests.ConnectionError,+ requests.exceptions.ChunkedEncodingError,+ )+ ),+ stop=stop_after_attempt(5),+ wait=wait_exponential_jitter(initial=1, max=30),+ reraise=True,+)+def _fetch(+ session: requests.Session,+ url: str,+ params: dict[str, Any],+ logger: FilteringBoundLogger,+) -> Any:+ response = session.get(url, params=params, timeout=60)++ # AppFollow rate-limits per token (1000/hr) and per account (10000/hr); treat 429 and transient+ # 5xx as retryable. 401 (bad token) / 402 (out of credits) / 403 raise for the caller and are+ # mapped to non-retryable errors at the source layer.+ if response.status_code == 429 or response.status_code >= 500:+ raise AppfollowRetryableError(f"AppFollow API error (retryable): status={response.status_code}, url={url}")++ if not response.ok:+ logger.error(f"AppFollow API error: status={response.status_code}, body={response.text}, url={url}")+ response.raise_for_status()++ return response.json()+++def _extract_rows(data: Any, data_key: str | None) -> list[dict[str, Any]]:+ """Pull the row list out of an AppFollow response.++ Rows live either at the response root (``data_key is None``) or under a single body key+ (e.g. ``apps``, ``reviews``, ``ratings``). Anything unexpected degrades to an empty page rather+ than raising, since AppFollow occasionally returns a non-list error envelope with HTTP 200.+ """+ if data_key is None:+ return data if isinstance(data, list) else []+ value = data.get(data_key) if isinstance(data, dict) else None+ return value if isinstance(value, list) else []+++def check_credentials(api_key: str) -> int | None:+ """Probe the account collections endpoint and return its HTTP status, or None on a network error.++ ``/account/apps`` costs a single credit and is reachable by any valid token, so it's the cheapest+ genuine liveness check. 200 = valid, 401 = bad token, 402 = out of credits.+ """+ try:+ response = make_tracked_session(headers=_headers(api_key), redact_values=(api_key,)).get(+ f"{APPFOLLOW_BASE_URL}/account/apps", timeout=10+ )+ return response.status_code+ except Exception:+ return None+++def _iter_collections(session: requests.Session, logger: FilteringBoundLogger) -> Iterator[dict[str, Any]]:+ data = _fetch(session, f"{APPFOLLOW_BASE_URL}/account/apps", {}, logger)+ yield from _extract_rows(data, "apps")+++def _iter_apps(session: requests.Session, logger: FilteringBoundLogger) -> Iterator[dict[str, Any]]:+ """Fan out over every collection and yield each app row, enriched for keying and downstream fan-out.++ Each app row is stamped with its `app_collection_id` and `collection_name`, and `ext_id`/`store`+ are lifted from the nested `app` object to the top level when absent so the review/rating fan-outs+ and the composite primary key can rely on them.+ """+ for collection in _iter_collections(session, logger):+ collection_id = collection.get("id")+ collection_name = collection.get("title_normalized") or collection.get("title")+ data = _fetch(session, f"{APPFOLLOW_BASE_URL}/account/apps/app", {"apps_id": collection_id}, logger)+ for app in _extract_rows(data, "apps_app"):+ nested = app.get("app") or {}+ app["app_collection_id"] = collection_id+ app["collection_name"] = collection_name+ if not app.get("ext_id") and (nested_ext_id := nested.get("ext_id")):+ app["ext_id"] = nested_ext_id+ if not app.get("store") and (nested_store := nested.get("store")):+ app["store"] = nested_store+ yield app+++class _AppTarget:+ ext_id: str+ store: str | None+ collection_name: str | None+++def _iter_app_targets(+ session: requests.Session, logger: FilteringBoundLogger, *, dedupe_by_store: bool+) -> list[_AppTarget]:+ """Discover the apps the review/rating fan-outs iterate.++ Reviews key on `ext_id` alone; ratings key on `ext_id` + `store`. The same app can appear in+ several collections, so we de-duplicate to avoid fetching (and paying credits for) it twice.+ """+ seen: set[tuple[str, str | None]] = set()+ targets: list[_AppTarget] = []+ for app in _iter_apps(session, logger):+ ext_id = app.get("ext_id")+ if not ext_id:+ continue+ store = app.get("store")+ key = (str(ext_id), store if dedupe_by_store else None)+ if key in seen:+ continue+ seen.add(key)+ targets.append(_AppTarget(ext_id=str(ext_id), store=store, collection_name=app.get("collection_name")))+ return targets+++def _resume_slice(+ targets: list[_AppTarget], manager: ResumableSourceManager[AppfollowResumeConfig]+) -> tuple[list[_AppTarget], int]:+ """Resolve the saved ext_id bookmark to the remaining targets and the cursor to resume the first at.++ If the bookmarked app no longer exists (removed between runs) we start over from the first app —+ merge dedupes the re-pulled rows on the primary key.+ """+ resume = manager.load_state() if manager.can_resume() else None+ if resume is None or resume.ext_id is None:+ return targets, 0+ index = next((i for i, t in enumerate(targets) if t.ext_id == resume.ext_id), None)+ if index is None:+ return targets, 0+ return targets[index:], resume.cursor or 0+++def _get_list(+ session: requests.Session,+ config: AppfollowEndpointConfig,+ logger: FilteringBoundLogger,+) -> Iterator[list[dict[str, Any]]]:+ data = _fetch(session, f"{APPFOLLOW_BASE_URL}{config.path}", {}, logger)+ rows = _extract_rows(data, config.data_key)+ if rows:+ yield rows+++def _get_apps(+ session: requests.Session,+ logger: FilteringBoundLogger,+) -> Iterator[list[dict[str, Any]]]:+ rows = list(_iter_apps(session, logger))+ if rows:+ yield rows+++def _get_reviews(+ session: requests.Session,+ config: AppfollowEndpointConfig,+ logger: FilteringBoundLogger,+ manager: ResumableSourceManager[AppfollowResumeConfig],+ should_use_incremental_field: bool,+ db_incremental_field_last_value: Any,+) -> Iterator[list[dict[str, Any]]]:+ targets = _iter_app_targets(session, logger, dedupe_by_store=False)+ remaining, resume_page = _resume_slice(targets, manager)++ last_modified: str | None = None+ if should_use_incremental_field and db_incremental_field_last_value:+ last_modified = _to_datetime_str(_clamp_future_value_to_now(db_incremental_field_last_value))++ to_date = _today_str()+ for i, target in enumerate(remaining):+ page = resume_page if i == 0 and resume_page else 1+ while True:+ params: dict[str, Any] = {+ "ext_id": target.ext_id,+ "from": DEFAULT_START_DATE,+ "to": to_date,+ "page": page,+ }+ if last_modified:+ params["last_modified"] = last_modified++ data = _fetch(session, f"{APPFOLLOW_BASE_URL}{config.path}", params, logger)+ rows = _extract_rows(data, config.data_key)+ pages_count = int(data.get("pages_count") or data.get("pages") or 1) if isinstance(data, dict) else 1++ if rows:+ for row in rows:+ row.setdefault("ext_id", target.ext_id)+ yield rows++ if not rows or page >= pages_count:+ break++ page += 1+ # Save AFTER yielding so a crash re-fetches the current page rather than skipping it; merge+ # dedupes the re-pulled rows on the [ext_id, review_id] primary key.+ manager.save_state(AppfollowResumeConfig(ext_id=target.ext_id, cursor=page))++ # Advance the bookmark to the next app so a crash between apps resumes correctly.+ if i + 1 < len(remaining):+ manager.save_state(AppfollowResumeConfig(ext_id=remaining[i + 1].ext_id, cursor=1))+++def _get_ratings(+ session: requests.Session,+ config: AppfollowEndpointConfig,+ logger: FilteringBoundLogger,+ manager: ResumableSourceManager[AppfollowResumeConfig],+ should_use_incremental_field: bool,+ db_incremental_field_last_value: Any,+) -> Iterator[list[dict[str, Any]]]:+ targets = _iter_app_targets(session, logger, dedupe_by_store=True)+ remaining, resume_offset = _resume_slice(targets, manager)++ from_date = DEFAULT_START_DATE+ if should_use_incremental_field and db_incremental_field_last_value:+ from_date = _to_date_str(_clamp_future_value_to_now(db_incremental_field_last_value)) or DEFAULT_START_DATE++ to_date = _today_str()+ limit = config.page_size or DEFAULT_PAGE_SIZE+ for i, target in enumerate(remaining):+ # Ratings history requires a store; skip apps whose store we couldn't resolve rather than 422.+ if not target.store:+ continue+ offset = resume_offset if i == 0 and resume_offset else 0+ while True:+ params: dict[str, Any] = {+ "ext_id": target.ext_id,+ "store": target.store,+ "from": from_date,+ "to": to_date,+ "period": "daily",+ "type": "total",+ "offset": offset,+ "limit": limit,+ }+ if target.collection_name:+ params["collection_name"] = target.collection_name++ data = _fetch(session, f"{APPFOLLOW_BASE_URL}{config.path}", params, logger)+ rows = _extract_rows(data, config.data_key)++ if rows:+ for row in rows:+ row.setdefault("ext_id", target.ext_id)+ row.setdefault("store", target.store)+ yield rows++ if len(rows) < limit:+ break++ offset += limit+ manager.save_state(AppfollowResumeConfig(ext_id=target.ext_id, cursor=offset))++ if i + 1 < len(remaining):+ manager.save_state(AppfollowResumeConfig(ext_id=remaining[i + 1].ext_id, cursor=0))+++def get_rows(+ api_key: str,+ endpoint: str,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[AppfollowResumeConfig],+ should_use_incremental_field: bool = False,+ db_incremental_field_last_value: Any = None,+) -> Iterator[list[dict[str, Any]]]:+ config = APPFOLLOW_ENDPOINTS[endpoint]+ session = make_tracked_session(headers=_headers(api_key), redact_values=(api_key,))++ if config.kind == "list":+ yield from _get_list(session, config, logger)+ elif config.kind == "apps":+ yield from _get_apps(session, logger)+ elif config.kind == "reviews":+ yield from _get_reviews(+ session,+ config,+ logger,+ resumable_source_manager,+ should_use_incremental_field,+ db_incremental_field_last_value,+ )+ else: # "ratings"+ yield from _get_ratings(+ session,+ config,+ logger,+ resumable_source_manager,+ should_use_incremental_field,+ db_incremental_field_last_value,+ )+++def appfollow_source(+ api_key: str,+ endpoint: str,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[AppfollowResumeConfig],+ should_use_incremental_field: bool = False,+ db_incremental_field_last_value: Optional[Any] = None,+) -> SourceResponse:+ config = APPFOLLOW_ENDPOINTS[endpoint]++ return SourceResponse(+ name=endpoint,+ items=lambda: get_rows(+ api_key=api_key,+ 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,+ # We re-open the full incremental window each run (reviews filter on `last_modified`, ratings on+ # `from`) and rely on merge to dedupe, so every in-window row is written regardless of the order+ # AppFollow returns pages in — "asc" simply lets the watermark checkpoint after each batch.+ sort_mode="asc",+ )diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/appfollow/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/appfollow/canonical_descriptions.pynew file mode 100644index 000000000000..1a00a07da21b--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/appfollow/canonical_descriptions.py@@ -0,0 +1,89 @@+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (+ CanonicalDescriptions,+)++# Curated from the AppFollow API v2 documentation (https://docs.api.appfollow.io/reference/overview and+# the per-endpoint response-field references). Partial coverage is fine — anything omitted falls back+# to LLM enrichment.+CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {+ "app_collections": {+ "description": "Workspaces (collections) on your AppFollow account, each grouping a set of tracked apps.",+ "docs_url": "https://docs.api.appfollow.io/reference/app_collections_list_api_v2_account_apps_get-1",+ "columns": {+ "id": "Unique collection (workspace) identifier.",+ "title": "Collection display name.",+ "title_normalized": "Normalized collection name used as `collection_name` in other endpoints.",+ "count_apps": "Number of apps in the collection.",+ "countries": "Countries tracked for the collection.",+ "languages": "Languages tracked for the collection.",+ "created": "When the collection was created.",+ },+ },+ "app_lists": {+ "description": "The apps tracked across every collection, including each app's store `ext_id`.",+ "docs_url": "https://docs.api.appfollow.io/reference/list_of_apps_from_the_collection_api_v2_account_apps_app_get-1",+ "columns": {+ "app_id": "AppFollow's internal identifier for the app.",+ "app_collection_id": "Identifier of the collection this app row belongs to.",+ "collection_name": "Normalized name of the collection this app row belongs to.",+ "ext_id": "The app's external store id (App Store / Google Play app id) used to query reviews and ratings.",+ "store": "Store the app is published on (as = App Store, gp = Google Play, ms, am, mc, xs).",+ "count_reviews": "Number of reviews AppFollow has collected for the app.",+ "created": "When the app was added to AppFollow.",+ "watch_url": "AppFollow dashboard URL for the app.",+ },+ },+ "users": {+ "description": "Users on your AppFollow account.",+ "docs_url": "https://docs.api.appfollow.io/reference/users_list_api_v2_account_users_get-1",+ "columns": {+ "id": "Unique user identifier.",+ "email": "User email address.",+ "name": "User display name.",+ "role": "User role on the account.",+ "status": "User account status.",+ "updated": "When the user was last updated.",+ },+ },+ "reviews": {+ "description": "App Store and Google Play reviews for your tracked apps, incrementally synced on the review's last-modified timestamp.",+ "docs_url": "https://docs.api.appfollow.io/reference/reviews_api_v2_reviews_get-1",+ "columns": {+ "id": "AppFollow's internal review identifier.",+ "review_id": "The store's review identifier (unique within an app).",+ "ext_id": "External store id of the app the review belongs to.",+ "app_id": "AppFollow's internal identifier for the app.",+ "store": "Store the review was posted on.",+ "title": "Review title.",+ "content": "Review text.",+ "author": "Review author.",+ "rating": "Star rating the review gave.",+ "rating_prev": "Previous rating, when the review was edited.",+ "date": "When the review was published in the store.",+ "dt": "When the review was written, if provided by the store.",+ "created": "When AppFollow collected the review.",+ "updated": "When the review was last updated (the incremental cursor).",+ "app_version": "App version the review was left on.",+ "locale": "Two-letter country code of the review.",+ "is_answer": "Whether the review has a developer reply.",+ "was_changed": "Whether the review was edited.",+ "user_id": "Store user id of the author, if available.",+ },+ },+ "ratings_history": {+ "description": "Daily star-rating history per app and store, incrementally synced by date.",+ "docs_url": "https://docs.api.appfollow.io/reference/ratings_history_api_v2_meta_ratings_history_get",+ "columns": {+ "ext_id": "External store id of the app.",+ "store": "Store the ratings belong to.",+ "date": "Day the rating snapshot is for.",+ "avg_rating": "Average star rating on that day.",+ "stars": "Total number of ratings on that day.",+ "stars1": "Count of 1-star ratings.",+ "stars2": "Count of 2-star ratings.",+ "stars3": "Count of 3-star ratings.",+ "stars4": "Count of 4-star ratings.",+ "stars5": "Count of 5-star ratings.",+ },+ },+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/appfollow/posthog_com_doc.md b/products/warehouse_sources/backend/temporal/data_imports/sources/appfollow/posthog_com_doc.mdnew file mode 100644index 000000000000..67006cc51aae--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/appfollow/posthog_com_doc.md@@ -0,0 +1,75 @@+---+title: Linking AppFollow as a source+sidebar: Docs+showTitle: true+availability: { free: full, selfServe: full, enterprise: full }+sourceId: Appfollow+beta: true+---++<!--+This is the user-facing posthog.com doc for the AppFollow source. It must be copied to the posthog.com+repo at contents/docs/cdp/sources/appfollow.md (served at /docs/cdp/sources/appfollow). It lives here+only because no posthog.com checkout was available when the source was implemented — it does not belong+in the posthog repo long-term. Once moved, run:+ python manage.py audit_source_docs --docs-dir ../posthog.com/contents/docs/cdp/sources+-->++import SourceSetupIntro from "../\_snippets/source-setup-intro.mdx"+import SyncModes from "../\_snippets/sync-modes.mdx"+import TroubleshootingLink from "../\_snippets/dw-troubleshooting-link.mdx"+import AlphaRelease from "../\_snippets/alpha-release.mdx"++<AlphaRelease />++[AppFollow](https://appfollow.io) aggregates App Store and Google Play data for app analytics, review+management, and app store optimization. This connector pulls your tracked apps, their reviews, and their+rating history into the PostHog Data warehouse, where you can join them with product analytics, build+insights, and monitor review sentiment over time.++## Prerequisites++You need an AppFollow account with API access. Only an Account Owner or Admin can generate an API token,+on the [API management page](https://watch.appfollow.io/settings/api) in your AppFollow account.++AppFollow bills API usage against a credit balance — reviews and ratings requests cost more credits than+the account and app-listing endpoints — and rate-limits to 1000 requests/hour per token and 10,000+requests/hour per account. The reviews and ratings tables can therefore consume a meaningful amount of+credits on their first (full history) sync.++## Adding a data source++<SourceSetupIntro />++Paste the API token you generated on the AppFollow API management page. It authenticates every request+through the `X-AppFollow-API-Token` header.++## Sync modes++<SyncModes />++The `reviews` table syncs incrementally on each review's last-modified timestamp, and `ratings_history`+syncs incrementally by date, so after the first backfill only new and changed rows are fetched. The+`app_collections`, `app_lists`, and `users` tables are small and sync as full refresh.++## Configuration++<SourceParameters />++## Supported tables++<SourceTables />++The `reviews` and `ratings_history` tables are queried per app using the app's store `ext_id`, which is+discovered by walking your collections (`app_collections`) and their apps (`app_lists`). Because those+requests cost credits, `ratings_history` and `users` are off by default — enable them in the table+picker if you want them.++## Troubleshooting++- **Invalid API token** — the token is wrong or was revoked. Generate a new one on the AppFollow API+ management page and reconnect.+- **Out of API credits** — your AppFollow account has exhausted its credit balance. Wait for the balance+ to reset or upgrade your plan, then retry the sync.++<TroubleshootingLink />diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/appfollow/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/appfollow/settings.pynew file mode 100644index 000000000000..d34e989ffd4b--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/appfollow/settings.py@@ -0,0 +1,121 @@+from dataclasses import dataclass, field+from typing import Literal, Optional++from products.warehouse_sources.backend.types import IncrementalField, IncrementalFieldType++# AppFollow's data model is app-centric: most data is queried per app via its store `ext_id`, and the+# only way to discover a workspace's apps is to walk collections (`/account/apps`) and then their apps+# (`/account/apps/app`). So the source exposes five endpoints across three request shapes:+#+# - "list": a single top-level GET whose rows live at the response root or under a body key+# (`app_collections` -> `apps`, `users` -> root). No app context needed. Full refresh.+# - "apps": `app_lists` — fans out over every collection, calling `/account/apps/app?apps_id=<id>`+# and flattening the per-collection app rows. This is also the app inventory that the+# review/rating fan-outs iterate to discover `ext_id`s. Full refresh.+# - "reviews": `/reviews` — fans out over every discovered app, page/`pages_count` paginated, with a+# server-side `last_modified` filter we drive incrementally off the review `updated` field.+# - "ratings": `/meta/ratings/history` — fans out over every app, offset/limit paginated, with a+# server-side `from` date filter we drive incrementally off the record `date` field.+EndpointKind = Literal["list", "apps", "reviews", "ratings"]++# AppFollow requires a `from`/`to` window on the reviews and ratings endpoints. On a first (backfill)+# sync we open the window all the way back to this date so the whole history is captured once; from+# then on the incremental filter (`last_modified` for reviews, `from`=watermark for ratings) does the+# delta work. Predates the App Store (2008) and Google Play (2012) so no real review/rating is missed.+DEFAULT_START_DATE = "2008-01-01"+++@dataclass+class AppfollowEndpointConfig:+ name: str+ path: str+ kind: EndpointKind+ primary_keys: list[str]+ # Body key the rows live under. `None` means the response root is itself the row list.+ data_key: Optional[str] = None+ incremental_fields: list[IncrementalField] = field(default_factory=list)+ default_incremental_field: Optional[str] = None+ # Stable, creation-style field to partition by — never an updated/last-modified field.+ partition_key: Optional[str] = None+ should_sync_default: bool = True+ # Max rows per page. Reviews cap at 100/page; ratings history uses offset/limit.+ page_size: int = 100+++_REVIEW_UPDATED_FIELD: IncrementalField = {+ "label": "updated",+ "type": IncrementalFieldType.DateTime,+ "field": "updated",+ "field_type": IncrementalFieldType.DateTime,+}++_RATINGS_DATE_FIELD: IncrementalField = {+ "label": "date",+ "type": IncrementalFieldType.Date,+ "field": "date",+ "field_type": IncrementalFieldType.Date,+}+++APPFOLLOW_ENDPOINTS: dict[str, AppfollowEndpointConfig] = {+ # Workspaces (collections) on the account — a small dimension table and the parent of `app_lists`.+ "app_collections": AppfollowEndpointConfig(+ name="app_collections",+ path="/account/apps",+ kind="list",+ primary_keys=["id"],+ data_key="apps",+ partition_key="created",+ ),+ # Every app across every collection, carrying the store `ext_id` the review/rating fan-outs need.+ # Keyed on (collection, app) because the same app can belong to several collections.+ "app_lists": AppfollowEndpointConfig(+ name="app_lists",+ path="/account/apps/app",+ kind="apps",+ primary_keys=["app_collection_id", "app_id"],+ data_key="apps_app",+ partition_key="created",+ ),+ # Account users — small dimension table. Rows sit at the response root.+ "users": AppfollowEndpointConfig(+ name="users",+ path="/account/users",+ kind="list",+ primary_keys=["id"],+ should_sync_default=False,+ ),+ # App reviews across stores. Fans out over every app, page paginated, incremental on `updated`+ # via the server-side `last_modified` filter. `review_id` is the store's id (unique per app), so+ # the primary key includes `ext_id` to stay unique across the whole fanned-out table.+ "reviews": AppfollowEndpointConfig(+ name="reviews",+ path="/reviews",+ kind="reviews",+ primary_keys=["ext_id", "review_id"],+ data_key="reviews",+ partition_key="date",+ default_incremental_field="updated",+ incremental_fields=[_REVIEW_UPDATED_FIELD],+ ),+ # Daily ratings history per app/store. Fans out over every app, offset/limit paginated, incremental+ # on the record `date` via the server-side `from` filter. Off by default: each request costs credits+ # and adds a recurring per-30-day charge, so it's opt-in.+ "ratings_history": AppfollowEndpointConfig(+ name="ratings_history",+ path="/meta/ratings/history",+ kind="ratings",+ primary_keys=["ext_id", "store", "date"],+ data_key="ratings",+ partition_key="date",+ default_incremental_field="date",+ incremental_fields=[_RATINGS_DATE_FIELD],+ should_sync_default=False,+ ),+}++ENDPOINTS = tuple(APPFOLLOW_ENDPOINTS.keys())++INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {+ name: config.incremental_fields for name, config in APPFOLLOW_ENDPOINTS.items()+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/appfollow/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/appfollow/source.pyindex abf1190a0c8b..caadc28e6105 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/appfollow/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/appfollow/source.py@@ -1,19 +1,43 @@-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.appfollow.appfollow import (+ AppfollowResumeConfig,+ appfollow_source,+ check_credentials,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.appfollow.settings import (+ APPFOLLOW_ENDPOINTS,+ ENDPOINTS,+ INCREMENTAL_FIELDS,+)+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 SourceSchemafrom products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs import AppfollowSourceConfigfrom products.warehouse_sources.backend.types import ExternalDataSourceType@SourceRegistry.register-class AppfollowSource(SimpleSource[AppfollowSourceConfig]):+class AppfollowSource(ResumableSource[AppfollowSourceConfig, AppfollowResumeConfig]):+ lists_tables_without_credentials = True # static endpoint catalog — safe for public docs+@propertydef source_type(self) -> ExternalDataSourceType:return ExternalDataSourceType.APPFOLLOW@@ -23,8 +47,105 @@ class AppfollowSource(SimpleSource[AppfollowSourceConfig]):return SourceConfig(name=SchemaExternalDataSourceType.APPFOLLOW,category=DataWarehouseSourceCategory.ANALYTICS,- label="Appfollow",- iconPath="/static/services/appfollow.png",- fields=cast(list[FieldType], []),+ label="AppFollow",+ releaseStatus=ReleaseStatus.ALPHA,unreleasedSource=True,+ caption="""Enter your AppFollow API token to pull your app reviews and ratings into the PostHog Data warehouse.++An Account Owner or Admin can generate an API token on the [API management page](https://watch.appfollow.io/settings/api) in your AppFollow account. The token authenticates every request via the `X-AppFollow-API-Token` header.++Note that AppFollow bills API usage against a credit balance (reviews and ratings cost more per request) and rate-limits to 1000 requests/hour per token.""",+ iconPath="/static/services/appfollow.png",+ docsUrl="https://posthog.com/docs/cdp/sources/appfollow",+ fields=cast(+ list[FieldType],+ [+ SourceFieldInputConfig(+ name="api_key",+ label="API token",+ type=SourceFieldInputConfigType.PASSWORD,+ required=True,+ placeholder="Your AppFollow API token",+ secret=True,+ ),+ ],+ ),+ )++ def get_canonical_descriptions(self) -> CanonicalDescriptions:+ from products.warehouse_sources.backend.temporal.data_imports.sources.appfollow.canonical_descriptions import (+ CANONICAL_DESCRIPTIONS,+ )++ return CANONICAL_DESCRIPTIONS++ def get_non_retryable_errors(self) -> dict[str, str | None]:+ # A bad token (401), an exhausted credit balance (402), or a permission problem (403) can't be+ # fixed by retrying. Match the stable status text and base host, not the per-request path/query.+ return {+ "401 Client Error: Unauthorized for url: https://api.appfollow.io": "Your AppFollow API token is invalid. Generate a new token on the API management page in your AppFollow account, then reconnect.",+ "402 Client Error: Payment Required for url: https://api.appfollow.io": "Your AppFollow account is out of API credits. Wait for your credit balance to reset or upgrade your plan, then retry the sync.",+ "403 Client Error: Forbidden for url: https://api.appfollow.io": "Your AppFollow API token does not have access to this data. Check the token's permissions, then reconnect.",+ }++ def get_schemas(+ self,+ config: AppfollowSourceConfig,+ team_id: int,+ with_counts: bool = False,+ names: list[str] | None = None,+ force_refresh: bool = False,+ ) -> list[SourceSchema]:+ def _build_schema(endpoint: str) -> SourceSchema:+ endpoint_config = APPFOLLOW_ENDPOINTS[endpoint]+ has_incremental = bool(INCREMENTAL_FIELDS.get(endpoint))+ return SourceSchema(+ name=endpoint,+ supports_incremental=has_incremental,+ supports_append=has_incremental,+ incremental_fields=INCREMENTAL_FIELDS.get(endpoint, []),+ should_sync_default=endpoint_config.should_sync_default,+ detected_primary_keys=endpoint_config.primary_keys,+ )++ schemas = [_build_schema(endpoint) for endpoint in ENDPOINTS]+ if names is not None:+ names_set = set(names)+ schemas = [s for s in schemas if s.name in names_set]+ return schemas++ def validate_credentials(+ self, config: AppfollowSourceConfig, team_id: int, schema_name: Optional[str] = None+ ) -> tuple[bool, str | None]:+ status = check_credentials(config.api_key)+ if status is None:+ return False, "Could not reach AppFollow. Please try again."+ if status == 401:+ return False, "Invalid AppFollow API token"+ if status == 402:+ return False, "Your AppFollow account is out of API credits"+ if status in (200, 403):+ # A single account-wide token authenticates every endpoint, so a genuine 200 (or a 403 that+ # still proves the token is real) means the credentials are valid.+ return True, None+ return False, f"AppFollow returned status {status}"++ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[AppfollowResumeConfig]:+ return ResumableSourceManager[AppfollowResumeConfig](inputs, AppfollowResumeConfig)++ def source_for_pipeline(+ self,+ config: AppfollowSourceConfig,+ resumable_source_manager: ResumableSourceManager[AppfollowResumeConfig],+ inputs: SourceInputs,+ ) -> SourceResponse:+ return appfollow_source(+ api_key=config.api_key,+ 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/appfollow/tests/test_appfollow.py b/products/warehouse_sources/backend/temporal/data_imports/sources/appfollow/tests/test_appfollow.pynew file mode 100644index 000000000000..46c7ea644cc4--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/appfollow/tests/test_appfollow.py@@ -0,0 +1,363 @@+from datetime import UTC, date, datetime+from typing import Any++import pytest+from freezegun import freeze_time+from unittest import mock++import requests++from products.warehouse_sources.backend.temporal.data_imports.sources.appfollow import appfollow+from products.warehouse_sources.backend.temporal.data_imports.sources.appfollow.appfollow import (+ APPFOLLOW_BASE_URL,+ AppfollowResumeConfig,+ _clamp_future_value_to_now,+ _extract_rows,+ _to_date_str,+ _to_datetime_str,+ appfollow_source,+ get_rows,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.appfollow.settings import APPFOLLOW_ENDPOINTS+++class _FakeManager:+ def __init__(self, state: AppfollowResumeConfig | None = None) -> None:+ self._state = state+ self.saved: list[AppfollowResumeConfig] = []++ def can_resume(self) -> bool:+ return self._state is not None++ def load_state(self) -> AppfollowResumeConfig | None:+ return self._state++ def save_state(self, data: AppfollowResumeConfig) -> None:+ self.saved.append(data)+++class _FakeApi:+ """Canned AppFollow responses plus a record of every request the transport made."""++ def __init__(+ self,+ collections: list[dict[str, Any]],+ apps_by_collection: dict[Any, list[dict[str, Any]]],+ reviews_pages: dict[str, list[list[dict[str, Any]]]] | None = None,+ ratings_pages: dict[str, list[list[dict[str, Any]]]] | None = None,+ ) -> None:+ self.collections = collections+ self.apps_by_collection = apps_by_collection+ self.reviews_pages = reviews_pages or {}+ self.ratings_pages = ratings_pages or {}+ self.calls: list[tuple[str, dict[str, Any]]] = []++ def fetch(self, session: Any, url: str, params: dict[str, Any], logger: Any) -> Any:+ self.calls.append((url, params))+ if url.endswith("/account/apps/app"):+ return {"apps_app": self.apps_by_collection.get(params["apps_id"], [])}+ if url.endswith("/account/apps"):+ return {"apps": self.collections}+ if url.endswith("/reviews"):+ pages = self.reviews_pages.get(params["ext_id"], [])+ page = params["page"]+ rows = pages[page - 1] if 1 <= page <= len(pages) else []+ return {"reviews": rows, "pages_count": len(pages)}+ if url.endswith("/meta/ratings/history"):+ pages = self.ratings_pages.get(params["ext_id"], [])+ index = params["offset"] // params["limit"]+ return {"ratings": pages[index] if 0 <= index < len(pages) else []}+ raise AssertionError(f"unexpected url {url}")+++def _collect(endpoint: str, manager: _FakeManager, monkeypatch: Any, api: _FakeApi, **kwargs: Any) -> list[dict]:+ monkeypatch.setattr(appfollow, "_fetch", api.fetch)+ monkeypatch.setattr(appfollow, "make_tracked_session", lambda **k: mock.MagicMock())+ rows: list[dict] = []+ for batch in get_rows(+ api_key="tok",+ endpoint=endpoint,+ logger=mock.MagicMock(),+ resumable_source_manager=manager, # type: ignore[arg-type]+ **kwargs,+ ):+ rows.extend(batch)+ return rows+++class TestExtractRows:+ @pytest.mark.parametrize(+ "data,key,expected",+ [+ ([{"a": 1}], None, [{"a": 1}]),+ ({"reviews": [{"a": 1}]}, "reviews", [{"a": 1}]),+ ({"other": [1]}, "reviews", []),+ ({"detail": "Invalid API token"}, "reviews", []),+ ("boom", None, []),+ ({"reviews": None}, "reviews", []),+ ],+ )+ def test_extract_rows(self, data, key, expected):+ assert _extract_rows(data, key) == expected+++class TestDateFormatting:+ @pytest.mark.parametrize(+ "value,expected",+ [+ (datetime(2024, 3, 4, 2, 58, 14, tzinfo=UTC), "2024-03-04"),+ (date(2024, 3, 4), "2024-03-04"),+ ("2024-03-04T05:06:07", "2024-03-04"),+ ("not-a-date", None),+ (None, None),+ ],+ )+ def test_to_date_str(self, value, expected):+ assert _to_date_str(value) == expected++ @pytest.mark.parametrize(+ "value,expected",+ [+ (datetime(2024, 3, 4, 2, 58, 14, tzinfo=UTC), "2024-03-04 02:58:14"),+ (datetime(2024, 3, 4, 2, 58, 14), "2024-03-04 02:58:14"),+ (date(2024, 3, 4), "2024-03-04 00:00:00"),+ (None, None),+ ],+ )+ def test_to_datetime_str(self, value, expected):+ assert _to_datetime_str(value) == expected+++class TestClampFutureValueToNow:+ @freeze_time("2026-06-15T12:00:00Z")+ def test_future_datetime_is_clamped(self):+ assert _clamp_future_value_to_now(datetime(2027, 1, 1, tzinfo=UTC)) == datetime(2026, 6, 15, 12, 0, tzinfo=UTC)++ @freeze_time("2026-06-15T12:00:00Z")+ def test_past_datetime_is_unchanged(self):+ value = datetime(2024, 3, 4, tzinfo=UTC)+ assert _clamp_future_value_to_now(value) == value++ @freeze_time("2026-06-15T12:00:00Z")+ def test_future_date_is_clamped(self):+ assert _clamp_future_value_to_now(date(2027, 1, 1)) == date(2026, 6, 15)+++def _one_app_api(+ reviews_pages: dict[str, list[list[dict[str, Any]]]] | None = None,+ ratings_pages: dict[str, list[list[dict[str, Any]]]] | None = None,+ ext_id: str = "111",+ store: str | None = "gp",+) -> _FakeApi:+ return _FakeApi(+ collections=[{"id": 10, "title": "Team", "title_normalized": "team"}],+ apps_by_collection={10: [{"app_id": 1, "ext_id": ext_id, "store": store, "app": {}}]},+ reviews_pages=reviews_pages,+ ratings_pages=ratings_pages,+ )+++class TestAppDiscovery:+ def test_iter_apps_enriches_ext_id_store_and_collection(self, monkeypatch):+ # ext_id/store nested under `app` must be lifted to the top level, and collection context stamped.+ api = _FakeApi(+ collections=[{"id": 10, "title": "Team", "title_normalized": "team"}],+ apps_by_collection={10: [{"app_id": 1, "app": {"ext_id": "999", "store": "as"}}]},+ )+ rows = _collect("app_lists", _FakeManager(), monkeypatch, api)+ assert len(rows) == 1+ assert rows[0]["ext_id"] == "999"+ assert rows[0]["store"] == "as"+ assert rows[0]["app_collection_id"] == 10+ assert rows[0]["collection_name"] == "team"+++class TestReviewsFanOut:+ def test_paginates_and_injects_ext_id(self, monkeypatch):+ api = _one_app_api(reviews_pages={"111": [[{"review_id": "r1"}], [{"review_id": "r2"}]]})+ rows = _collect(+ "reviews",+ _FakeManager(),+ monkeypatch,+ api,+ should_use_incremental_field=False,+ db_incremental_field_last_value=None,+ )+ assert [r["review_id"] for r in rows] == ["r1", "r2"]+ # ext_id is injected so the [ext_id, review_id] primary key is always populated.+ assert all(r["ext_id"] == "111" for r in rows)+ review_calls = [p for (u, p) in api.calls if u.endswith("/reviews")]+ assert [p["page"] for p in review_calls] == [1, 2]+ assert all(p["ext_id"] == "111" for p in review_calls)++ def test_first_sync_sends_no_last_modified(self, monkeypatch):+ api = _one_app_api(reviews_pages={"111": [[{"review_id": "r1"}]]})+ _collect(+ "reviews",+ _FakeManager(),+ monkeypatch,+ api,+ should_use_incremental_field=True,+ db_incremental_field_last_value=None,+ )+ review_params = next(p for (u, p) in api.calls if u.endswith("/reviews"))+ assert "last_modified" not in review_params++ def test_incremental_sync_sends_last_modified(self, monkeypatch):+ api = _one_app_api(reviews_pages={"111": [[{"review_id": "r1"}]]})+ _collect(+ "reviews",+ _FakeManager(),+ monkeypatch,+ api,+ should_use_incremental_field=True,+ db_incremental_field_last_value=datetime(2024, 3, 4, 5, 6, 7, tzinfo=UTC),+ )+ review_params = next(p for (u, p) in api.calls if u.endswith("/reviews"))+ assert review_params["last_modified"] == "2024-03-04 05:06:07"++ def test_same_app_in_two_collections_fetched_once(self, monkeypatch):+ # Reviews key on ext_id alone; an app shared across collections must not be paid for twice.+ api = _FakeApi(+ collections=[{"id": 10, "title_normalized": "a"}, {"id": 20, "title_normalized": "b"}],+ apps_by_collection={+ 10: [{"app_id": 1, "ext_id": "111", "store": "gp", "app": {}}],+ 20: [{"app_id": 1, "ext_id": "111", "store": "gp", "app": {}}],+ },+ reviews_pages={"111": [[{"review_id": "r1"}]]},+ )+ _collect(+ "reviews",+ _FakeManager(),+ monkeypatch,+ api,+ should_use_incremental_field=False,+ db_incremental_field_last_value=None,+ )+ review_calls = [p for (u, p) in api.calls if u.endswith("/reviews")]+ assert len(review_calls) == 1++ def test_resume_starts_from_saved_page(self, monkeypatch):+ api = _one_app_api(reviews_pages={"111": [[{"review_id": "r1"}], [{"review_id": "r2"}]]})+ manager = _FakeManager(AppfollowResumeConfig(ext_id="111", cursor=2))+ rows = _collect(+ "reviews",+ manager,+ monkeypatch,+ api,+ should_use_incremental_field=False,+ db_incremental_field_last_value=None,+ )+ # Page 1 is skipped on resume; only page 2 is re-fetched.+ assert [r["review_id"] for r in rows] == ["r2"]+ assert [p["page"] for (u, p) in api.calls if u.endswith("/reviews")] == [2]++ def test_saves_state_after_yielding_each_page(self, monkeypatch):+ api = _one_app_api(reviews_pages={"111": [[{"review_id": "r1"}], [{"review_id": "r2"}]]})+ manager = _FakeManager()+ _collect(+ "reviews",+ manager,+ monkeypatch,+ api,+ should_use_incremental_field=False,+ db_incremental_field_last_value=None,+ )+ # State is saved so a mid-sync crash resumes at the next page rather than restarting the app.+ assert AppfollowResumeConfig(ext_id="111", cursor=2) in manager.saved+++class TestRatingsFanOut:+ def test_offset_pagination_injects_ext_id_and_store(self, monkeypatch):+ api = _one_app_api(ratings_pages={"111": [[{"date": "2024-01-01"}] * 100, [{"date": "2024-02-01"}]]})+ rows = _collect(+ "ratings_history",+ _FakeManager(),+ monkeypatch,+ api,+ should_use_incremental_field=False,+ db_incremental_field_last_value=None,+ )+ assert len(rows) == 101+ assert all(r["ext_id"] == "111" and r["store"] == "gp" for r in rows)+ offsets = [p["offset"] for (u, p) in api.calls if u.endswith("/meta/ratings/history")]+ # Second page fetched at offset=100 because the first returned a full page.+ assert offsets == [0, 100]++ def test_incremental_from_uses_watermark(self, monkeypatch):+ api = _one_app_api(ratings_pages={"111": [[{"date": "2024-05-02"}]]})+ _collect(+ "ratings_history",+ _FakeManager(),+ monkeypatch,+ api,+ should_use_incremental_field=True,+ db_incremental_field_last_value=date(2024, 5, 1),+ )+ params = next(p for (u, p) in api.calls if u.endswith("/meta/ratings/history"))+ assert params["from"] == "2024-05-01"+ assert params["store"] == "gp"++ def test_app_without_store_is_skipped(self, monkeypatch):+ # Ratings history requires a store; an app we can't resolve one for must not 422 the whole sync.+ api = _one_app_api(ratings_pages={"111": [[{"date": "2024-01-01"}]]}, store=None)+ rows = _collect(+ "ratings_history",+ _FakeManager(),+ monkeypatch,+ api,+ should_use_incremental_field=False,+ db_incremental_field_last_value=None,+ )+ assert rows == []+ assert not any(u.endswith("/meta/ratings/history") for (u, _) in api.calls)+++class TestFetchRetryClassification:+ def _session_returning(self, status_code: int, json_body: Any = None) -> Any:+ response = mock.MagicMock()+ response.status_code = status_code+ response.ok = 200 <= status_code < 300+ response.json.return_value = json_body if json_body is not None else {}+ if not response.ok:+ response.raise_for_status.side_effect = requests.HTTPError(f"{status_code} error", response=response)+ session = mock.MagicMock()+ session.get.return_value = response+ return session++ @pytest.mark.parametrize("status", [429, 500, 503])+ def test_retryable_statuses_raise_retryable_error(self, status):+ session = self._session_returning(status)+ with mock.patch.object(appfollow._fetch.retry, "sleep", lambda *_: None): # type: ignore[attr-defined]+ with pytest.raises(appfollow.AppfollowRetryableError):+ appfollow._fetch(session, f"{APPFOLLOW_BASE_URL}/reviews", {}, mock.MagicMock())++ @pytest.mark.parametrize("status", [401, 402, 403])+ def test_credential_statuses_raise_http_error(self, status):+ session = self._session_returning(status)+ with pytest.raises(requests.HTTPError):+ appfollow._fetch(session, f"{APPFOLLOW_BASE_URL}/account/apps", {}, mock.MagicMock())++ def test_ok_returns_json(self):+ session = self._session_returning(200, {"apps": []})+ assert appfollow._fetch(session, f"{APPFOLLOW_BASE_URL}/account/apps", {}, mock.MagicMock()) == {"apps": []}+++class TestSourceResponse:+ @pytest.mark.parametrize("endpoint", list(APPFOLLOW_ENDPOINTS))+ def test_source_response_matches_endpoint_config(self, endpoint):+ config = APPFOLLOW_ENDPOINTS[endpoint]+ response = appfollow_source(+ api_key="tok",+ endpoint=endpoint,+ logger=mock.MagicMock(),+ resumable_source_manager=mock.MagicMock(),+ )+ assert response.name == endpoint+ assert response.primary_keys == config.primary_keys+ assert response.sort_mode == "asc"+ if config.partition_key:+ assert response.partition_mode == "datetime"+ assert response.partition_keys == [config.partition_key]+ else:+ assert response.partition_mode is Nonediff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/appfollow/tests/test_appfollow_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/appfollow/tests/test_appfollow_source.pynew file mode 100644index 000000000000..5934581de230--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/appfollow/tests/test_appfollow_source.py@@ -0,0 +1,198 @@+import pytest+from unittest import mock++from posthog.schema import (+ DataWarehouseSourceCategory,+ ReleaseStatus,+ SourceFieldInputConfig,+ SourceFieldInputConfigType,+)++from products.warehouse_sources.backend.temporal.data_imports.sources.appfollow.appfollow import AppfollowResumeConfig+from products.warehouse_sources.backend.temporal.data_imports.sources.appfollow.settings import (+ APPFOLLOW_ENDPOINTS,+ ENDPOINTS,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.appfollow.source import AppfollowSource+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs import AppfollowSourceConfig+from products.warehouse_sources.backend.types import ExternalDataSourceType+++class TestAppfollowSource:+ def setup_method(self):+ self.source = AppfollowSource()+ self.team_id = 123+ self.config = AppfollowSourceConfig(api_key="tok_test")++ def test_source_type(self):+ assert self.source.source_type == ExternalDataSourceType.APPFOLLOW++ def test_get_source_config(self):+ config = self.source.get_source_config+ assert config.name.value == "Appfollow"+ assert config.category == DataWarehouseSourceCategory.ANALYTICS+ assert config.releaseStatus == ReleaseStatus.ALPHA+ assert config.unreleasedSource is True+ assert config.iconPath == "/static/services/appfollow.png"+ assert config.docsUrl == "https://posthog.com/docs/cdp/sources/appfollow"++ def test_api_key_field_is_secret_password(self):+ config = self.source.get_source_config+ field = next(f for f in config.fields if isinstance(f, SourceFieldInputConfig) and f.name == "api_key")+ assert field.type == SourceFieldInputConfigType.PASSWORD+ assert field.secret is True+ assert field.required is True++ def test_lists_tables_without_credentials(self):+ # get_schemas is a static catalog with no I/O, so the public docs can render the table list.+ assert self.source.lists_tables_without_credentials is True++ def test_get_schemas_covers_all_endpoints(self):+ schemas = self.source.get_schemas(self.config, self.team_id)+ assert {s.name for s in schemas} == set(ENDPOINTS)++ @pytest.mark.parametrize(+ "name,incremental,field",+ [+ ("app_collections", False, None),+ ("app_lists", False, None),+ ("users", False, None),+ ("reviews", True, "updated"),+ ("ratings_history", True, "date"),+ ],+ )+ def test_incremental_capability_per_endpoint(self, name, incremental, field):+ # Only reviews (server-side last_modified) and ratings_history (server-side from-date) expose a+ # real server filter; the discovery/dimension tables must stay full refresh.+ schemas = {s.name: s for s in self.source.get_schemas(self.config, self.team_id)}+ assert schemas[name].supports_incremental is incremental+ if incremental:+ assert [f["field"] for f in schemas[name].incremental_fields] == [field]+ else:+ assert schemas[name].incremental_fields == []++ @pytest.mark.parametrize(+ "name,default_sync",+ [+ ("app_collections", True),+ ("app_lists", True),+ ("reviews", True),+ ("users", False),+ ("ratings_history", False),+ ],+ )+ def test_should_sync_defaults(self, name, default_sync):+ # ratings_history and users cost extra credits / are niche, so they're opt-in by default.+ schemas = {s.name: s for s in self.source.get_schemas(self.config, self.team_id)}+ assert schemas[name].should_sync_default is default_sync++ @pytest.mark.parametrize(+ "name,primary_keys",+ [+ ("app_collections", ["id"]),+ ("app_lists", ["app_collection_id", "app_id"]),+ ("users", ["id"]),+ # Fan-out children must include the parent id so keys stay unique table-wide.+ ("reviews", ["ext_id", "review_id"]),+ ("ratings_history", ["ext_id", "store", "date"]),+ ],+ )+ def test_primary_keys_are_unique_table_wide(self, name, primary_keys):+ schemas = {s.name: s for s in self.source.get_schemas(self.config, self.team_id)}+ assert schemas[name].detected_primary_keys == primary_keys++ def test_get_schemas_filtered_by_names(self):+ schemas = self.source.get_schemas(self.config, self.team_id, names=["reviews"])+ assert len(schemas) == 1+ assert schemas[0].name == "reviews"++ @pytest.mark.parametrize(+ "status,expected_ok",+ [+ (200, True),+ # A single account-wide token: a 403 still proves the token is genuine.+ (403, True),+ (401, False),+ (402, False),+ (500, False),+ (None, False),+ ],+ )+ def test_validate_credentials(self, status, expected_ok):+ with mock.patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.appfollow.source.check_credentials",+ return_value=status,+ ):+ ok, _ = self.source.validate_credentials(self.config, self.team_id)+ assert ok is expected_ok++ @pytest.mark.parametrize(+ "observed_error",+ [+ "401 Client Error: Unauthorized for url: https://api.appfollow.io/api/v2/account/apps",+ "402 Client Error: Payment Required for url: https://api.appfollow.io/api/v2/reviews?ext_id=1",+ "403 Client Error: Forbidden for url: https://api.appfollow.io/api/v2/meta/ratings/history",+ ],+ )+ def test_non_retryable_errors_match_auth_and_credit_failures(self, observed_error):+ non_retryable = self.source.get_non_retryable_errors()+ assert any(key in observed_error for key in non_retryable)++ @pytest.mark.parametrize(+ "unrelated_error",+ [+ "401 Client Error: Unauthorized for url: https://api.stripe.com/v1/customers",+ "500 Server Error for url: https://api.appfollow.io/api/v2/reviews",+ "429 Client Error: Too Many Requests for url: https://api.appfollow.io/api/v2/reviews",+ ],+ )+ def test_non_retryable_errors_ignore_retryable_and_unrelated(self, unrelated_error):+ non_retryable = self.source.get_non_retryable_errors()+ assert not any(key in unrelated_error for key in non_retryable)++ def test_get_resumable_source_manager_bound_to_resume_config(self):+ manager = self.source.get_resumable_source_manager(mock.MagicMock())+ assert isinstance(manager, ResumableSourceManager)+ assert manager._data_class is AppfollowResumeConfig++ def test_source_for_pipeline_plumbs_arguments(self):+ manager = mock.MagicMock()+ inputs = mock.MagicMock()+ inputs.schema_name = "reviews"+ inputs.should_use_incremental_field = True+ inputs.db_incremental_field_last_value = "2024-01-01"+ with mock.patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.appfollow.source.appfollow_source"+ ) as appfollow_source:+ self.source.source_for_pipeline(self.config, manager, inputs)+ kwargs = appfollow_source.call_args.kwargs+ assert kwargs["api_key"] == "tok_test"+ assert kwargs["endpoint"] == "reviews"+ assert kwargs["resumable_source_manager"] is manager+ assert kwargs["should_use_incremental_field"] is True+ assert kwargs["db_incremental_field_last_value"] == "2024-01-01"++ def test_source_for_pipeline_drops_last_value_when_not_incremental(self):+ manager = mock.MagicMock()+ inputs = mock.MagicMock()+ inputs.schema_name = "app_collections"+ inputs.should_use_incremental_field = False+ inputs.db_incremental_field_last_value = "2024-01-01"+ with mock.patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.appfollow.source.appfollow_source"+ ) as appfollow_source:+ self.source.source_for_pipeline(self.config, manager, inputs)+ assert appfollow_source.call_args.kwargs["db_incremental_field_last_value"] is None++ def test_canonical_descriptions_keyed_by_endpoint_names(self):+ descriptions = self.source.get_canonical_descriptions()+ assert set(descriptions.keys()) == set(APPFOLLOW_ENDPOINTS)++ def test_documented_tables_render_for_public_docs(self):+ # lists_tables_without_credentials=True must produce a credential-free catalog for posthog.com;+ # a regression in get_schemas' placeholder path would silently empty the docs' Supported tables.+ tables = {t["name"]: t for t in self.source.get_documented_tables()}+ assert set(tables) == set(ENDPOINTS)+ assert "Incremental" in tables["reviews"]["sync_methods"]+ assert tables["app_collections"]["sync_methods"] == ["Full refresh"]diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.py b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.pyindex 98391a472840..8fa7ce34346f 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.py@@ -301,7 +301,7 @@ class AppfiguresSourceConfig(config.Config):@config.configclass AppfollowSourceConfig(config.Config):- pass+ api_key: str@config.config