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): support appfollow API version v3 (#113234)

Tom Owers9bbb7971a409
diff --git a/.agents/skills/warehouse-source-new-version/SKILL.md b/.agents/skills/warehouse-source-new-version/SKILL.md
index 3f172d02967d..866328a0fc21 100644
--- a/.agents/skills/warehouse-source-new-version/SKILL.md
+++ b/.agents/skills/warehouse-source-new-version/SKILL.md
@@ -108,6 +108,7 @@ The opposite gap also occurs: a reference rendered from one version-blind OpenAP
- A new version can page a horizon the old one returned whole (a fixed record cap plus `next`/`prev` links). For a snapshot-polling source, keep one request per sync rather than following the links — vendors bill each page — and state the resulting horizon in each table's description, since it can be shorter than the old version's.
- A version that drops the sort parameters the old request path used to order rows by the incremental field (for example a fixed newest-first order) breaks the per-batch watermark checkpoint that `sort_mode="asc"` implies. Report `sort_mode="desc"` for those endpoints under the new pin, so the pipeline persists the watermark only when a sync completes, and stop sending the sort params the new version rejects.
- A version that changes the pagination _mechanism_ (e.g. offset→cursor, or one opaque cursor param for another, since a token one generation issued means nothing to the other) also changes the resumable checkpoint's persisted shape. Add a new defaulted field to the resume-config dataclass rather than repurposing the existing one — so state persisted under the old version still decodes — and make the seed and save-checkpoint logic dispatch on the resolved version. Reusing one field across incompatible mechanisms corrupts in-flight resumes of the other version. When a table stays on its old wire under the new pin, key the check on the wire that issued the cursor, not on the pin.
+- Other products can read a synced table's columns by name, e.g. a signal emitter registered on `(source_type, table)` in `products/signals/backend/emission/registry.py`. Grep for the source type outside its directory before a new version renames or nests a column such a reader uses, and keep that column under its old name on the new version's rows.
- When the vendor renames a collection between versions, keep the schema/table name set identical across versions and put the rename in a per-version path on the endpoint config — otherwise discovery diffs orphan the table on repin.
- When the new version has no equivalent for an old endpoint (a dropped collection, not a rename), keep that table only on the versions that serve it and let the table set differ by version — never map it to a guessed path just to keep the sets equal, since docs are the sole source of truth and an unverified path makes a new source surface a table that 404s at sync time.
- A source with no dispatch may currently read its version from a constant on a shared model (e.g. the OAuth `Integration` model) that also drives version-independent flows like OAuth token minting. Repoint only the sync request path onto the resolved pin; leave that constant, since bumping it changes those other flows' version with a blast radius beyond this source.
diff --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.md
index 74b69f1ce850..cc4ad5a17a4c 100644
--- 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.md
@@ -1,6 +1,7 @@
# AppFollow API inventory
-Reference for the endpoints this source syncs. AppFollow API v2, base URL `https://api.appfollow.io/api/v2`,
+Reference for the endpoints this source syncs. The source supports API `v2` and `v3` (the default for new
+sources). See [API v3](#api-v3) for the tables that change under a v3 pin. 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:** every path and query parameter below was checked against the published v2
@@ -77,3 +78,37 @@ enumerate a workspace's apps is:
resolves it per app: the app's own `country`, then the nested `app.country`, then the collection's
`default_country`, then the first entry of the collection's `countries`, then `us`. An app tracked in
two collections with different countries is fetched once per country, because versions vary by country.
+
+## API v3
+
+API v3 (<https://docs.api.appfollow.io/v3.0/reference/overview>) is a new set of endpoints under
+`https://api.appfollow.io/api/v3`. They are not backward compatible with v2, but the same token and
+`X-AppFollow-API-Token` header work. v3 publishes response schemas, so the v3 columns below come from the
+reference rather than from reconstruction.
+
+v3 replaces only the collection, app, and review endpoints. Under a v3 pin those three tables move to the
+v3 wire. Every other table keeps its v2 request path, which AppFollow still serves, including the v2
+collection and app walk that discovers the `ext_id`s those fan-outs need. The table set does not change.
+
+| Schema | v3 path | Shape | Rows under | Primary key | Incremental |
+| ----------------- | ---------------------------------- | ------------------------------------- | ----------------------- | ------------------------ | ----------------- |
+| `app_collections` | `GET /workspaces` | single request | values of `collections` | `[collectionId]` | — (full refresh) |
+| `app_lists` | `GET /workspaces/apps?appsId=<id>` | fan-out over workspaces | `apps` | `[collectionId, itemId]` | — (full refresh) |
+| `reviews` | `POST /reviews/feed` (JSON body) | fan-out over workspaces, `nextCursor` | `reviews` | `[itemId, id]` | `date` via `from` |
+
+- `/workspaces` returns a map from `collectionCode` to workspace. We emit the values in the
+ `sortedCollections` order so the reviews resume bookmark stays stable.
+- `/workspaces/apps` rows carry no workspace id, so we stamp `collectionId` for the primary key.
+ `itemId` identifies an app within one workspace.
+- `/reviews/feed` takes `appsId` (required), `from`/`to` (required dates), `limit` (max 100), `sort`,
+ and `cursor`. We send `sort=oldest`. There is no last-modified filter, so `from`=watermark is the
+ incremental cursor, and an edit to a review older than the watermark is not re-synced.
+- Review rows nest store, rating, country, version, and dates under `metaInformation`. We lift those
+ fields to the top level and also write `date` (from `created`) and `app_version` (from `version`),
+ the v2 column names that readers of the `reviews` table key on.
+- v3 has no `users`, rankings, keywords, store release history, or per-day review-statistics endpoint,
+ so those tables stay on v2.
+- `ratings_history` also stays on v2. The v3 `POST /ratings/chart` requires a `store` from its own
+ store-code enum, but the v3 app list documents a different store value (`itunes`), so the docs do not
+ show how to feed one into the other. It also returns a different row shape (`value`, `starsTotal`,
+ `stars` per period).
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.py
index b4b9b70ba842..9180516b3a6f 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/appfollow/appfollow.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/appfollow/appfollow.py
@@ -1,4 +1,3 @@
-import dataclasses
from collections.abc import Iterator
from datetime import UTC, date, datetime
from typing import Any, Optional
@@ -10,15 +9,18 @@ from tenacity import retry, retry_if_exception_type, stop_after_attempt, wait_ex
from posthog.dataclasses import frozen
from products.warehouse_sources.backend.temporal.data_imports.sources.appfollow.settings import (
- APPFOLLOW_ENDPOINTS,
+ APPFOLLOW_V2,
+ APPFOLLOW_V3,
DEFAULT_START_DATE,
AppfollowEndpointConfig,
+ endpoints_for_version,
)
from products.warehouse_sources.backend.temporal.data_imports.sources.common.http import make_tracked_session
from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceResponse
APPFOLLOW_BASE_URL = "https://api.appfollow.io/api/v2"
+APPFOLLOW_V3_BASE_URL = "https://api.appfollow.io/api/v3"
# Ratings history is offset/limit paginated; reviews use page/pages_count. Both cap a page at 100 rows.
DEFAULT_PAGE_SIZE = 100
@@ -27,6 +29,11 @@ DEFAULT_PAGE_SIZE = 100
# the walk can only end on an empty page. Cap it so a misbehaving endpoint can't spend credits forever.
MAX_PAGES_PER_APP = 100
+# The v3 reviews feed pages on a vendor-issued cursor with no published total, and each page costs
+# credits. The feed is sorted oldest first and an incremental sync restarts at the watermark, so a sync
+# that stops at this cap continues from that point on the next run.
+MAX_REVIEW_FEED_PAGES_PER_WORKSPACE = 1000
+
# `/meta/versions` requires a country and an app does not always carry one. Last resort when neither
# the app nor its collection names one.
FALLBACK_COUNTRY = "us"
@@ -36,7 +43,7 @@ class AppfollowRetryableError(Exception):
pass
+@frozen
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.
@@ -45,6 +52,9 @@ class AppfollowResumeConfig:
# Pagination cursor within the current app's resource: 1-indexed `page` for reviews, or the row
# `offset` for ratings history.
cursor: int | None = None
+ # v3 reviews fan out over workspaces and page with an opaque cursor, so they bookmark here instead.
+ collection_id: int | None = None
+ page_cursor: str | None = None
def _headers(api_key: str) -> dict[str, str]:
@@ -104,7 +114,7 @@ def _clamp_future_value_to_now(value: Any) -> Any:
return value
-@retry(
+_retry_transient_errors = retry(
retry=retry_if_exception_type(
(
AppfollowRetryableError,
@@ -117,14 +127,9 @@ def _clamp_future_value_to_now(value: Any) -> Any:
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)
+
+def _parse_response(response: requests.Response, url: str, logger: FilteringBoundLogger) -> Any:
# 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.
@@ -138,6 +143,26 @@ def _fetch(
return response.json()
+@_retry_transient_errors
+def _fetch(
+ session: requests.Session,
+ url: str,
+ params: dict[str, Any],
+ logger: FilteringBoundLogger,
+) -> Any:
+ return _parse_response(session.get(url, params=params, timeout=60), url, logger)
+
+
+@_retry_transient_errors
+def _post(
+ session: requests.Session,
+ url: str,
+ body: dict[str, Any],
+ logger: FilteringBoundLogger,
+) -> Any:
+ return _parse_response(session.post(url, json=body, timeout=60), url, logger)
+
+
def _extract_rows(data: Any, data_key: str | tuple[str, ...] | None) -> list[dict[str, Any]]:
"""Pull the row list out of an AppFollow response.
@@ -159,16 +184,21 @@ def _extract_rows(data: Any, data_key: str | tuple[str, ...] | None) -> list[dic
return data if isinstance(data, 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.
+_CREDENTIALS_PROBE_URLS = {
+ APPFOLLOW_V2: f"{APPFOLLOW_BASE_URL}/account/apps",
+ APPFOLLOW_V3: f"{APPFOLLOW_V3_BASE_URL}/workspaces",
+}
+
- ``/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.
+def check_credentials(api_key: str, api_version: str) -> int | None:
+ """Probe the version's collections endpoint and return its HTTP status, or None on a network error.
+
+ The collections endpoint 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.
"""
+ url = _CREDENTIALS_PROBE_URLS[api_version]
try:
- response = make_tracked_session(headers=_headers(api_key), redact_values=(api_key,)).get(
- f"{APPFOLLOW_BASE_URL}/account/apps", timeout=10
- )
+ response = make_tracked_session(headers=_headers(api_key), redact_values=(api_key,)).get(url, timeout=10)
return response.status_code
except Exception:
return None
@@ -494,18 +524,149 @@ def _get_app_fanout(
manager.save_state(AppfollowResumeConfig(ext_id=remaining[i + 1].ext_id, cursor=1))
+def _iter_workspaces(session: requests.Session, logger: FilteringBoundLogger) -> Iterator[dict[str, Any]]:
+ """Yield v3 workspaces in creation order.
+
+ The response maps each `collectionCode` to its workspace, and `sortedCollections` gives the order.
+ A stable order keeps the reviews fan-out resume bookmark meaningful.
+ """
+ data = _fetch(session, f"{APPFOLLOW_V3_BASE_URL}/workspaces", {}, logger)
+ collections = data.get("collections") if isinstance(data, dict) else None
+ if not isinstance(collections, dict):
+ return
+ order = data.get("sortedCollections")
+ codes = [code for code in order if code in collections] if isinstance(order, list) else []
+ codes += [code for code in collections if code not in codes]
+ for code in codes:
+ workspace = collections[code]
+ if isinstance(workspace, dict):
+ yield workspace
+
+
+def _get_workspaces(session: requests.Session, logger: FilteringBoundLogger) -> Iterator[list[dict[str, Any]]]:
+ rows = list(_iter_workspaces(session, logger))
+ if rows:
+ yield rows
+
+
+def _get_workspace_apps(
+ session: requests.Session,
+ config: AppfollowEndpointConfig,
+ logger: FilteringBoundLogger,
+) -> Iterator[list[dict[str, Any]]]:
+ rows: list[dict[str, Any]] = []
+ for workspace in _iter_workspaces(session, logger):
+ collection_id = workspace.get("collectionId")
+ data = _fetch(session, f"{APPFOLLOW_V3_BASE_URL}{config.path}", {"appsId": collection_id}, logger)
+ for app in _extract_rows(data, config.data_key):
+ app["collectionId"] = collection_id
+ rows.append(app)
+ if rows:
+ yield rows
+
+
+def _flatten_v3_review(row: dict[str, Any]) -> None:
+ meta = row.pop("metaInformation", None) or {}
+ for key, value in meta.items():
+ row.setdefault(key, value)
+ row.setdefault("date", meta.get("created"))
+ row.setdefault("app_version", meta.get("version"))
+
+
+def _get_reviews_feed(
+ 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]]]:
+ collection_ids = [
+ workspace["collectionId"]
+ for workspace in _iter_workspaces(session, logger)
+ if workspace.get("collectionId") is not None
+ ]
+
+ resume = manager.load_state() if manager.can_resume() else None
+ resume_cursor: str | None = None
+ if resume is not None and resume.collection_id in collection_ids:
+ collection_ids = collection_ids[collection_ids.index(resume.collection_id) :]
+ resume_cursor = resume.page_cursor
+
+ 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()
+ for i, collection_id in enumerate(collection_ids):
+ page_cursor = resume_cursor if i == 0 else None
+ pages = 0
+ while True:
+ body: dict[str, Any] = {
+ "appsId": collection_id,
+ "from": from_date,
+ "to": to_date,
+ "limit": config.page_size,
+ "sort": "oldest",
+ }
+ if page_cursor:
+ body["cursor"] = page_cursor
+
+ data = _post(session, f"{APPFOLLOW_V3_BASE_URL}{config.path}", body, logger)
+ rows = _extract_rows(data, config.data_key)
+ pages += 1
+
+ next_cursor = data.get("nextCursor") if isinstance(data, dict) and rows else None
+ if next_cursor and pages >= MAX_REVIEW_FEED_PAGES_PER_WORKSPACE:
+ logger.warning(
+ f"AppFollow {config.name}: reached the {MAX_REVIEW_FEED_PAGES_PER_WORKSPACE} page cap for "
+ f"workspace {collection_id}; later pages were not fetched"
+ )
+ next_cursor = None
+
+ # Stage the bookmark for the page after this batch before yielding it, because the pipeline
+ # commits staged state together with the batch.
+ if next_cursor:
+ manager.save_state(AppfollowResumeConfig(collection_id=collection_id, page_cursor=next_cursor))
+ elif i + 1 < len(collection_ids):
+ manager.save_state(AppfollowResumeConfig(collection_id=collection_ids[i + 1]))
+
+ if rows:
+ for row in rows:
+ _flatten_v3_review(row)
+ yield rows
+
+ if not next_cursor:
+ break
+ page_cursor = next_cursor
+
+
def get_rows(
api_key: str,
endpoint: str,
+ api_version: 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]
+ config = endpoints_for_version(api_version)[endpoint]
session = make_tracked_session(headers=_headers(api_key), redact_values=(api_key,))
- if config.kind == "list":
+ if config.kind == "workspaces":
+ yield from _get_workspaces(session, logger)
+ elif config.kind == "workspace_apps":
+ yield from _get_workspace_apps(session, config, logger)
+ elif config.kind == "reviews_feed":
+ yield from _get_reviews_feed(
+ session,
+ config,
+ logger,
+ resumable_source_manager,
+ should_use_incremental_field,
+ db_incremental_field_last_value,
+ )
+ elif config.kind == "list":
yield from _get_list(session, config, logger)
elif config.kind == "apps":
yield from _get_apps(session, logger)
@@ -541,18 +702,20 @@ def get_rows(
def appfollow_source(
api_key: str,
endpoint: str,
+ api_version: 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]
+ config = endpoints_for_version(api_version)[endpoint]
return SourceResponse(
name=endpoint,
items=lambda: get_rows(
api_key=api_key,
endpoint=endpoint,
+ api_version=api_version,
logger=logger,
resumable_source_manager=resumable_source_manager,
should_use_incremental_field=should_use_incremental_field,
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.py
index 3c0117a057e6..a9095e1d3e50 100644
--- 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.py
@@ -46,7 +46,7 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
},
},
"reviews": {
- "description": "App Store and Google Play reviews for your tracked apps, incrementally synced on the review's last-modified timestamp.",
+ "description": "App Store and Google Play reviews for your tracked apps, incrementally synced on the review's last-modified timestamp (API v2) or its date (API v3).",
"docs_url": "https://docs.api.appfollow.io/reference/reviews_api_v2_reviews_get-1",
"columns": {
"id": "AppFollow's internal review identifier.",
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.md
index dfb5bc2385ab..a1e65a61d541 100644
--- 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.md
@@ -49,9 +49,12 @@ through the `X-AppFollow-API-Token` header.
<SyncModes />
-The `reviews` table syncs incrementally on each review's last-modified timestamp, and `ratings_history`
-and `reviews_stats` sync incrementally by date, so after the first backfill only new and changed rows
-are fetched. Every other table syncs as full refresh.
+The `reviews` table syncs incrementally, and `ratings_history` and `reviews_stats` sync incrementally by
+date, so after the first backfill only new rows are fetched. Every other table syncs as full refresh.
+
+New sources use AppFollow API v3, where the `reviews` table syncs on each review's date. API v3 has no
+way to ask for recently changed reviews, so an edit to a review older than the last sync is not picked up.
+Sources connected on API v2 keep syncing `reviews` on each review's last-modified timestamp.
The `rankings` and `keywords` tables are the exception worth knowing about. AppFollow returns rank and
keyword positions for a single day at a time, with no way to ask for a range, so each sync adds that
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.py
index 8e4851b6fbb8..e2a7efbe27e9 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/appfollow/settings.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/appfollow/settings.py
@@ -5,6 +5,9 @@ from posthog.dataclasses import frozen
from products.warehouse_sources.backend.types import IncrementalField, IncrementalFieldType
+APPFOLLOW_V2 = "v2"
+APPFOLLOW_V3 = "v3"
+
# 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 its endpoints across five request shapes:
@@ -21,7 +24,17 @@ from products.warehouse_sources.backend.types import IncrementalField, Increment
# - "app_fanout": the ASO and review-statistics endpoints, which all take one `ext_id` per request
# and differ only in how they page and how they take time. `paginated`, `requires_country`
# and `time_mode` below describe those differences declaratively.
-EndpointKind = Literal["list", "apps", "reviews", "ratings", "app_fanout"]
+#
+# API v3 replaces only the collection, app and review endpoints. Under a v3 pin those three tables move
+# to the v3 wire, and every other table stays on the v2 wire, which AppFollow still serves:
+#
+# - "workspaces": `app_collections` — `/workspaces`, rows are the values of the `collections` map.
+# - "workspace_apps": `app_lists` — fans out over every workspace, `/workspaces/apps?appsId=<id>`.
+# - "reviews_feed": `reviews` — fans out over every workspace with a POST to `/reviews/feed`,
+# cursor paginated, with a `from` date filter we drive incrementally off `date`.
+EndpointKind = Literal[
+ "list", "apps", "reviews", "ratings", "app_fanout", "workspaces", "workspace_apps", "reviews_feed"
+]
# How an "app_fanout" endpoint takes time:
# - "none": no time parameter at all, so the endpoint returns its whole history (full refresh).
@@ -185,8 +198,58 @@ APPFOLLOW_ENDPOINTS: dict[str, AppfollowEndpointConfig] = {
),
}
-ENDPOINTS = tuple(APPFOLLOW_ENDPOINTS.keys())
+_REVIEW_DATE_FIELD: IncrementalField = {
+ "label": "date",
+ "type": IncrementalFieldType.DateTime,
+ "field": "date",
+ "field_type": IncrementalFieldType.DateTime,
+}
+
+# v3 response schemas are published, so these keys and columns come from the v3 reference.
+APPFOLLOW_V3_ENDPOINTS: dict[str, AppfollowEndpointConfig] = {
+ **APPFOLLOW_ENDPOINTS,
+ "app_collections": AppfollowEndpointConfig(
+ name="app_collections",
+ path="/workspaces",
+ kind="workspaces",
+ primary_keys=["collectionId"],
+ partition_key="created",
+ ),
+ # `itemId` identifies an app within one workspace, so the key adds the workspace we stamp on.
+ "app_lists": AppfollowEndpointConfig(
+ name="app_lists",
+ path="/workspaces/apps",
+ kind="workspace_apps",
+ primary_keys=["collectionId", "itemId"],
+ data_key="apps",
+ ),
+ # The v3 feed has no last-modified filter, so the cursor is the review date. Edits to reviews
+ # older than the watermark are not re-synced. `date` and `app_version` are lifted from the nested
+ # `metaInformation` under their v2 names, because readers of this table key on those columns.
+ "reviews": AppfollowEndpointConfig(
+ name="reviews",
+ path="/reviews/feed",
+ kind="reviews_feed",
+ primary_keys=["itemId", "id"],
+ data_key="reviews",
+ partition_key="date",
+ default_incremental_field="date",
+ incremental_fields=[_REVIEW_DATE_FIELD],
+ ),
+}
-INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {
- name: config.incremental_fields for name, config in APPFOLLOW_ENDPOINTS.items()
+ENDPOINTS_BY_VERSION: dict[str, dict[str, AppfollowEndpointConfig]] = {
+ APPFOLLOW_V2: APPFOLLOW_ENDPOINTS,
+ APPFOLLOW_V3: APPFOLLOW_V3_ENDPOINTS,
}
+
+
+def endpoints_for_version(api_version: str) -> dict[str, AppfollowEndpointConfig]:
+ try:
+ return ENDPOINTS_BY_VERSION[api_version]
+ except KeyError:
+ raise ValueError(f"AppFollow: no endpoint catalog for API version {api_version!r}")
+
+
+# The table set is identical across versions, so a source keeps every table whichever version it is on.
+ENDPOINTS = tuple(APPFOLLOW_ENDPOINTS.keys())
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.py
index f866c2710451..21578fd7ec1c 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
@@ -13,9 +13,10 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.appfollow.
check_credentials,
)
from products.warehouse_sources.backend.temporal.data_imports.sources.appfollow.settings import (
- APPFOLLOW_ENDPOINTS,
+ APPFOLLOW_V2,
+ APPFOLLOW_V3,
ENDPOINTS,
- INCREMENTAL_FIELDS,
+ endpoints_for_version,
)
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 (
@@ -34,8 +35,8 @@ from products.warehouse_sources.backend.types import ExternalDataSourceType
@SourceRegistry.register
class AppfollowSource(ResumableSource[AppfollowSourceConfig, AppfollowResumeConfig]):
lists_tables_without_credentials = True # static endpoint catalog — safe for public docs
- supported_versions = ("v2",)
- default_version = "v2"
+ supported_versions = (APPFOLLOW_V2, APPFOLLOW_V3)
+ default_version = APPFOLLOW_V3
api_docs_url = "https://docs.api.appfollow.io/reference/overview"
@property
@@ -96,14 +97,16 @@ Note that AppFollow bills API usage against a credit balance (reviews and rating
force_refresh: bool = False,
api_version: str | None = None,
) -> list[SourceSchema]:
+ endpoints = endpoints_for_version(self.resolve_api_version(api_version))
+
def _build_schema(endpoint: str) -> SourceSchema:
- endpoint_config = APPFOLLOW_ENDPOINTS[endpoint]
- has_incremental = bool(INCREMENTAL_FIELDS.get(endpoint))
+ endpoint_config = endpoints[endpoint]
+ has_incremental = bool(endpoint_config.incremental_fields)
return SourceSchema(
name=endpoint,
supports_incremental=has_incremental,
supports_append=has_incremental,
- incremental_fields=INCREMENTAL_FIELDS.get(endpoint, []),
+ incremental_fields=endpoint_config.incremental_fields,
should_sync_default=endpoint_config.should_sync_default,
detected_primary_keys=endpoint_config.primary_keys,
)
@@ -121,7 +124,7 @@ Note that AppFollow bills API usage against a credit balance (reviews and rating
schema_name: Optional[str] = None,
api_version: str | None = None,
) -> tuple[bool, str | None]:
- status = check_credentials(config.api_key)
+ status = check_credentials(config.api_key, self.resolve_api_version(api_version))
if status is None:
return False, "Could not reach AppFollow. Please try again."
if status == 401:
@@ -146,6 +149,7 @@ Note that AppFollow bills API usage against a credit balance (reviews and rating
return appfollow_source(
api_key=config.api_key,
endpoint=inputs.schema_name,
+ api_version=self.resolve_api_version(inputs.api_version),
logger=inputs.logger,
resumable_source_manager=resumable_source_manager,
should_use_incremental_field=inputs.should_use_incremental_field,
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.py
index 414b3244cb47..103348749792 100644
--- 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.py
@@ -10,6 +10,7 @@ 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,
+ APPFOLLOW_V3_BASE_URL,
AppfollowResumeConfig,
_clamp_future_value_to_now,
_extract_rows,
@@ -21,7 +22,10 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.appfollow.
)
from products.warehouse_sources.backend.temporal.data_imports.sources.appfollow.settings import (
APPFOLLOW_ENDPOINTS,
+ APPFOLLOW_V2,
+ APPFOLLOW_V3,
DEFAULT_START_DATE,
+ endpoints_for_version,
)
@@ -78,13 +82,21 @@ class _CannedApi(Protocol):
def fetch(self, session: Any, url: str, params: dict[str, Any], logger: Any) -> Any: ...
-def _collect(endpoint: str, manager: _FakeManager, monkeypatch: Any, api: _CannedApi, **kwargs: Any) -> list[dict]:
+def _collect(
+ endpoint: str,
+ manager: _FakeManager,
+ monkeypatch: Any,
+ api: _CannedApi,
+ api_version: str = APPFOLLOW_V2,
+ **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,
+ api_version=api_version,
logger=mock.MagicMock(),
resumable_source_manager=manager, # type: ignore[arg-type]
**kwargs,
@@ -358,12 +370,14 @@ class TestFetchRetryClassification:
class TestSourceResponse:
+ @pytest.mark.parametrize("api_version", [APPFOLLOW_V2, APPFOLLOW_V3])
@pytest.mark.parametrize("endpoint", list(APPFOLLOW_ENDPOINTS))
- def test_source_response_matches_endpoint_config(self, endpoint):
- config = APPFOLLOW_ENDPOINTS[endpoint]
+ def test_source_response_matches_endpoint_config(self, endpoint, api_version):
+ config = endpoints_for_version(api_version)[endpoint]
response = appfollow_source(
api_key="tok",
endpoint=endpoint,
+ api_version=api_version,
logger=mock.MagicMock(),
resumable_source_manager=mock.MagicMock(),
)
@@ -475,6 +489,7 @@ class TestSnapshotFanOut:
get_rows(
api_key="tok",
endpoint="keywords",
+ api_version=APPFOLLOW_V2,
logger=logger,
resumable_source_manager=_FakeManager(), # type: ignore[arg-type]
)
@@ -559,3 +574,171 @@ class TestWindowedFanOut:
db_incremental_field_last_value=date(2027, 1, 1),
)
assert _calls_to(api, "/reviews/stats")[0]["from"] == "2026-06-15"
+
+
+class _FakeV3Api:
+ """Canned AppFollow v3 responses, shaped from the v3 reference, plus a record of every request."""
+
+ def __init__(
+ self,
+ workspaces: list[dict[str, Any]],
+ apps_by_workspace: dict[int, list[dict[str, Any]]] | None = None,
+ review_pages_by_workspace: dict[int, list[list[dict[str, Any]]]] | None = None,
+ ) -> None:
+ self.workspaces = workspaces
+ self.apps_by_workspace = apps_by_workspace or {}
+ self.review_pages_by_workspace = review_pages_by_workspace or {}
+ self.calls: list[tuple[str, str, dict[str, Any]]] = []
+
+ def fetch(self, session: Any, url: str, params: dict[str, Any], logger: Any) -> Any:
+ self.calls.append(("GET", url, params))
+ if url == f"{APPFOLLOW_V3_BASE_URL}/workspaces":
+ # Reverse the map order so only `sortedCollections` can produce creation order.
+ return {
+ "collections": {w["collectionCode"]: w for w in reversed(self.workspaces)},
+ "sortedCollections": [w["collectionCode"] for w in self.workspaces],
+ }
+ if url == f"{APPFOLLOW_V3_BASE_URL}/workspaces/apps":
+ return {"apps": [dict(app) for app in self.apps_by_workspace.get(params["appsId"], [])]}
+ raise AssertionError(f"unexpected GET {url}")
+
+ def post(self, session: Any, url: str, body: dict[str, Any], logger: Any) -> Any:
+ self.calls.append(("POST", url, body))
+ assert url == f"{APPFOLLOW_V3_BASE_URL}/reviews/feed", url
+ pages = self.review_pages_by_workspace.get(body["appsId"], [])
+ index = int(body.get("cursor", "0"))
+ rows = [dict(row) for row in pages[index]] if index < len(pages) else []
+ return {"reviews": rows, "nextCursor": str(index + 1) if index + 1 < len(pages) else None}
+
+ def requests_to(self, path: str) -> list[dict[str, Any]]:
+ return [payload for (_, url, payload) in self.calls if url == f"{APPFOLLOW_V3_BASE_URL}{path}"]
+
+
+def _v3_review(review_id: int, created: str, version: str = "1.0") -> dict[str, Any]:
+ return {
+ "id": review_id,
+ "reviewId": f"store-{review_id}",
+ "itemId": 7,
+ "content": "Great app",
+ "metaInformation": {"store": "as", "extId": "111", "rating": 5, "created": created, "version": version},
+ "tags": {"tagDetails": []},
+ }
+
+
+def _collect_v3(
+ endpoint: str, api: _FakeV3Api, monkeypatch: Any, manager: _FakeManager | None = None, **kwargs: Any
+) -> list[dict]:
+ monkeypatch.setattr(appfollow, "_post", api.post)
+ return _collect(endpoint, manager or _FakeManager(), monkeypatch, api, api_version=APPFOLLOW_V3, **kwargs)
+
+
+_WORKSPACES = [
+ {"collectionId": 10, "collectionCode": "first", "collectionName": "First"},
+ {"collectionId": 20, "collectionCode": "second", "collectionName": "Second"},
+]
+
+
+class TestV3Wire:
+ def test_app_collections_reads_the_workspace_map_in_creation_order(self, monkeypatch):
+ api = _FakeV3Api(_WORKSPACES)
+ rows = _collect_v3("app_collections", api, monkeypatch)
+ assert [r["collectionId"] for r in rows] == [10, 20]
+ assert not any(url.startswith(APPFOLLOW_BASE_URL) for (_, url, _) in api.calls)
+
+ def test_app_lists_fans_out_per_workspace_and_stamps_the_workspace_key(self, monkeypatch):
+ api = _FakeV3Api(
+ _WORKSPACES,
+ apps_by_workspace={10: [{"itemId": 1, "extId": "111"}], 20: [{"itemId": 1, "extId": "222"}]},
+ )
+ rows = _collect_v3("app_lists", api, monkeypatch)
+ assert [(r["collectionId"], r["itemId"], r["extId"]) for r in rows] == [(10, 1, "111"), (20, 1, "222")]
+ assert [p["appsId"] for p in api.requests_to("/workspaces/apps")] == [10, 20]
+
+ def test_reviews_follow_the_cursor_and_lift_the_v2_key_columns(self, monkeypatch):
+ api = _FakeV3Api(
+ _WORKSPACES[:1],
+ review_pages_by_workspace={
+ 10: [[_v3_review(1, "2024-01-02T00:00:00Z")], [_v3_review(2, "2024-01-03T00:00:00Z", "2.0")]]
+ },
+ )
+ rows = _collect_v3("reviews", api, monkeypatch, should_use_incremental_field=False)
+ assert [(r["id"], r["date"], r["app_version"], r["rating"]) for r in rows] == [
+ (1, "2024-01-02T00:00:00Z", "1.0", 5),
+ (2, "2024-01-03T00:00:00Z", "2.0", 5),
+ ]
+ assert all("metaInformation" not in r for r in rows)
+ bodies = api.requests_to("/reviews/feed")
+ assert [b.get("cursor") for b in bodies] == [None, "1"]
+ assert all(b["appsId"] == 10 and b["from"] == DEFAULT_START_DATE for b in bodies)
+
+ @time_machine.travel("2026-06-15T09:00:00Z", tick=False)
+ def test_incremental_reviews_move_from_to_the_watermark(self, monkeypatch):
+ api = _FakeV3Api(_WORKSPACES[:1], review_pages_by_workspace={10: [[_v3_review(1, "2026-06-12T00:00:00Z")]]})
+ _collect_v3(
+ "reviews",
+ api,
+ monkeypatch,
+ should_use_incremental_field=True,
+ db_incremental_field_last_value=datetime(2026, 6, 10, 8, tzinfo=UTC),
+ )
+ body = api.requests_to("/reviews/feed")[0]
+ assert (body["from"], body["to"]) == ("2026-06-10", "2026-06-15")
+
+ def test_reviews_resume_at_the_saved_workspace_and_cursor(self, monkeypatch):
+ api = _FakeV3Api(
+ _WORKSPACES,
+ review_pages_by_workspace={
+ 10: [[_v3_review(1, "2024-01-01T00:00:00Z")]],
+ 20: [[_v3_review(2, "2024-01-01T00:00:00Z")], [_v3_review(3, "2024-01-02T00:00:00Z")]],
+ },
+ )
+ manager = _FakeManager(AppfollowResumeConfig(collection_id=20, page_cursor="1"))
+ rows = _collect_v3("reviews", api, monkeypatch, manager=manager)
+ assert [r["id"] for r in rows] == [3]
+ assert [(b["appsId"], b.get("cursor")) for b in api.requests_to("/reviews/feed")] == [(20, "1")]
+
+ def test_reviews_stage_the_next_bookmark_before_each_batch(self, monkeypatch):
+ api = _FakeV3Api(
+ _WORKSPACES,
+ review_pages_by_workspace={
+ 10: [[_v3_review(1, "2024-01-01T00:00:00Z")], [_v3_review(2, "2024-01-02T00:00:00Z")]],
+ 20: [[_v3_review(3, "2024-01-01T00:00:00Z")]],
+ },
+ )
+ manager = _FakeManager()
+ monkeypatch.setattr(appfollow, "_post", api.post)
+ monkeypatch.setattr(appfollow, "_fetch", api.fetch)
+ monkeypatch.setattr(appfollow, "make_tracked_session", lambda **k: mock.MagicMock())
+ saved_before_batch = []
+ for _ in get_rows(
+ api_key="tok",
+ endpoint="reviews",
+ api_version=APPFOLLOW_V3,
+ logger=mock.MagicMock(),
+ resumable_source_manager=manager, # type: ignore[arg-type]
+ ):
+ saved_before_batch.append(manager.saved[-1] if manager.saved else None)
+ assert saved_before_batch == [
+ AppfollowResumeConfig(collection_id=10, page_cursor="1"),
+ AppfollowResumeConfig(collection_id=20),
+ AppfollowResumeConfig(collection_id=20),
+ ]
+
+ def test_reviews_paging_stops_at_the_cap(self, monkeypatch):
+ monkeypatch.setattr(appfollow, "MAX_REVIEW_FEED_PAGES_PER_WORKSPACE", 3)
+ api = _FakeV3Api(
+ _WORKSPACES[:1],
+ review_pages_by_workspace={10: [[_v3_review(n, "2024-01-01T00:00:00Z")] for n in range(50)]},
+ )
+ rows = _collect_v3("reviews", api, monkeypatch)
+ assert [r["id"] for r in rows] == [0, 1, 2]
+
+ def test_tables_without_a_v3_endpoint_stay_on_the_v2_wire(self, monkeypatch):
+ api = _one_app_api(ratings_pages={"111": [[{"date": "2024-01-01"}]]})
+ rows = _collect("ratings_history", _FakeManager(), monkeypatch, api, api_version=APPFOLLOW_V3)
+ assert len(rows) == 1
+ assert {url for (url, _) in api.calls} == {
+ f"{APPFOLLOW_BASE_URL}/account/apps",
+ f"{APPFOLLOW_BASE_URL}/account/apps/app",
+ f"{APPFOLLOW_BASE_URL}/meta/ratings/history",
+ }
diff --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.py
index de56b0cc567c..798e66feac6e 100644
--- 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.py
@@ -1,7 +1,11 @@
import pytest
from unittest import mock
-from products.warehouse_sources.backend.temporal.data_imports.sources.appfollow.settings import ENDPOINTS
+from products.warehouse_sources.backend.temporal.data_imports.sources.appfollow.settings import (
+ APPFOLLOW_V2,
+ APPFOLLOW_V3,
+ ENDPOINTS,
+)
from products.warehouse_sources.backend.temporal.data_imports.sources.appfollow.source import AppfollowSource
from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.appfollow import (
AppfollowSourceConfig,
@@ -18,30 +22,40 @@ class TestAppfollowSource:
# 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)
+ def test_new_sources_start_on_v3(self):
+ assert self.source.default_version == APPFOLLOW_V3
+ assert self.source.supported_versions == (APPFOLLOW_V2, APPFOLLOW_V3)
+
+ @pytest.mark.parametrize("api_version", [APPFOLLOW_V2, APPFOLLOW_V3, None])
+ def test_get_schemas_covers_all_endpoints(self, api_version):
+ schemas = self.source.get_schemas(self.config, self.team_id, api_version=api_version)
assert {s.name for s in schemas} == set(ENDPOINTS)
@pytest.mark.parametrize(
- "name,incremental,field",
+ "api_version,name,incremental,field",
[
- ("app_collections", False, None),
- ("app_lists", False, None),
- ("users", False, None),
- ("reviews", True, "updated"),
- ("ratings_history", True, "date"),
+ (APPFOLLOW_V2, "app_collections", False, None),
+ (APPFOLLOW_V2, "app_lists", False, None),
+ (APPFOLLOW_V2, "users", False, None),
+ (APPFOLLOW_V2, "reviews", True, "updated"),
+ (APPFOLLOW_V2, "ratings_history", True, "date"),
# Only reviews_stats among the ASO/statistics endpoints takes a from/to range; rankings,
# keywords and app_versions expose no server-side time filter at all.
- ("reviews_stats", True, "date"),
- ("rankings", False, None),
- ("keywords", False, None),
- ("app_versions", False, None),
+ (APPFOLLOW_V2, "reviews_stats", True, "date"),
+ (APPFOLLOW_V2, "rankings", False, None),
+ (APPFOLLOW_V2, "keywords", False, None),
+ (APPFOLLOW_V2, "app_versions", False, None),
+ # The v3 reviews feed has no last-modified filter, only a from/to range on the review date.
+ (APPFOLLOW_V3, "reviews", True, "date"),
+ (APPFOLLOW_V3, "app_collections", False, None),
+ (APPFOLLOW_V3, "ratings_history", True, "date"),
+ (None, "reviews", True, "date"),
],
)
- def test_incremental_capability_per_endpoint(self, name, incremental, field):
+ def test_incremental_capability_per_endpoint(self, api_version, 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)}
+ schemas = {s.name: s for s in self.source.get_schemas(self.config, self.team_id, api_version=api_version)}
assert schemas[name].supports_incremental is incremental
if incremental:
assert [f["field"] for f in schemas[name].incremental_fields] == [field]
@@ -68,22 +82,26 @@ class TestAppfollowSource:
assert schemas[name].should_sync_default is default_sync
@pytest.mark.parametrize(
- "name,primary_keys",
+ "api_version,name,primary_keys",
[
- ("app_collections", ["id"]),
- ("app_lists", ["app_collection_id", "app_id"]),
- ("users", ["id"]),
+ (APPFOLLOW_V2, "app_collections", ["id"]),
+ (APPFOLLOW_V2, "app_lists", ["app_collection_id", "app_id"]),
+ (APPFOLLOW_V2, "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"]),
- ("rankings", ["ext_id", "country", "device", "genre_id", "date"]),
- ("keywords", ["ext_id", "country", "device", "date", "keyword"]),
- ("app_versions", ["ext_id", "country", "version"]),
- ("reviews_stats", ["ext_id", "date"]),
+ (APPFOLLOW_V2, "reviews", ["ext_id", "review_id"]),
+ (APPFOLLOW_V2, "ratings_history", ["ext_id", "store", "date"]),
+ (APPFOLLOW_V2, "rankings", ["ext_id", "country", "device", "genre_id", "date"]),
+ (APPFOLLOW_V2, "keywords", ["ext_id", "country", "device", "date", "keyword"]),
+ (APPFOLLOW_V2, "app_versions", ["ext_id", "country", "version"]),
+ (APPFOLLOW_V2, "reviews_stats", ["ext_id", "date"]),
+ (APPFOLLOW_V3, "app_collections", ["collectionId"]),
+ (APPFOLLOW_V3, "app_lists", ["collectionId", "itemId"]),
+ (APPFOLLOW_V3, "reviews", ["itemId", "id"]),
+ (APPFOLLOW_V3, "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)}
+ def test_primary_keys_are_unique_table_wide(self, api_version, name, primary_keys):
+ schemas = {s.name: s for s in self.source.get_schemas(self.config, self.team_id, api_version=api_version)}
assert schemas[name].detected_primary_keys == primary_keys
def test_get_schemas_filtered_by_names(self):
@@ -111,6 +129,34 @@ class TestAppfollowSource:
ok, _ = self.source.validate_credentials(self.config, self.team_id)
assert ok is expected_ok
+ @pytest.mark.parametrize(
+ "api_version,probed_url",
+ [
+ (APPFOLLOW_V2, "https://api.appfollow.io/api/v2/account/apps"),
+ (APPFOLLOW_V3, "https://api.appfollow.io/api/v3/workspaces"),
+ (None, "https://api.appfollow.io/api/v3/workspaces"),
+ ],
+ )
+ def test_validate_credentials_probes_the_pinned_version(self, api_version, probed_url):
+ session = mock.MagicMock()
+ session.get.return_value.status_code = 200
+ with mock.patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.appfollow.appfollow.make_tracked_session",
+ return_value=session,
+ ):
+ ok, _ = self.source.validate_credentials(self.config, self.team_id, api_version=api_version)
+ assert ok is True
+ assert session.get.call_args.args[0] == probed_url
+
+ @pytest.mark.parametrize("pinned", [APPFOLLOW_V2, APPFOLLOW_V3])
+ def test_source_for_pipeline_dispatches_on_the_pin(self, pinned):
+ inputs = mock.MagicMock(api_version=pinned, schema_name="reviews", should_use_incremental_field=False)
+ 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, mock.MagicMock(), inputs)
+ assert appfollow_source.call_args.kwargs["api_version"] == pinned
+
@pytest.mark.parametrize(
"observed_error",
[