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(data-warehouse): implement appfigures import source (#66737)

Tom Owersdabb32b92523
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
index b239fb8ffff5..807e5035e720 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
@@ -54,6 +54,7 @@ the row lists both.
| amplitude | HTTP | requests | ✅ |
| apify_dataset | HTTP | requests | ✅ |
| apollo | HTTP | requests | ✅ |
+| appfigures | HTTP | requests | ✅ |
| appsflyer | HTTP (CSV reports) | requests | ✅ |
| asana | HTTP | requests | ✅ |
| ashby | HTTP | requests | ✅ |
@@ -318,7 +319,6 @@ doesn't conflict with concurrent PRs.
- amazon_sns
- amazon_sqs
- appcues
-- appfigures
- appfollow
- apple_search_ads
- appstack
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/appfigures/appfigures.py b/products/warehouse_sources/backend/temporal/data_imports/sources/appfigures/appfigures.py
new file mode 100644
index 000000000000..ee7f1a3060cf
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/appfigures/appfigures.py
@@ -0,0 +1,278 @@
+import dataclasses
+from collections.abc import Iterator
+from datetime import UTC, date, datetime, timedelta
+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.appfigures.settings import (
+ APPFIGURES_ENDPOINTS,
+ AppfiguresEndpointConfig,
+)
+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
+
+APPFIGURES_BASE_URL = "https://api.appfigures.com/v2"
+
+# Report endpoints (group_by=dates) have no "fetch everything" mode that's safe to stream — omitting
+# the window returns the entire account history in one un-paginated response, and daily granularity is
+# capped at 30 days per request. So the first sync backfills this many days, then incremental syncs
+# advance from the stored date watermark.
+REPORT_BACKFILL_DAYS = 365
+
+
+class AppfiguresRetryableError(Exception):
+ pass
+
+
+class AppfiguresResumeConfig:
+ # "paged" endpoints (reviews): the next page number to fetch (1-based).
+ next_page: int | None = None
+ # "report" endpoints: the next date window's start (yyyy-mm-dd) to fetch.
+ window_start: str | None = None
+
+
+def _headers(token: str) -> dict[str, str]:
+ # Personal Access Tokens and OAuth 2.0 tokens both ride the standard bearer header; the PAT also
+ # carries the API client identity, so no separate client-key header is needed.
+ return {"Authorization": f"Bearer {token}", "Accept": "application/json"}
+
+
+def _to_date_str(value: Any) -> str | None:
+ """Format a datetime/date/ISO-string incremental value as the yyyy-mm-dd Appfigures expects."""
+ 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()
+ # Already a string — take the date portion (handles "2024-01-02T03:04:05" and "2024-01-02").
+ text = str(value)[:10]
+ try:
+ date.fromisoformat(text)
+ except ValueError as e:
+ # Surface a descriptive error here rather than letting the partial fragment blow up deep in
+ # _iter_report's date.fromisoformat call.
+ raise ValueError(f"Could not derive a yyyy-mm-dd date from incremental value {value!r}") from e
+ return text
+
+
+@retry(
+ retry=retry_if_exception_type((AppfiguresRetryableError, requests.ReadTimeout, requests.ConnectionError)),
+ 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,
+) -> dict[str, Any]:
+ response = session.get(url, params=params, timeout=60)
+
+ # Quota is a monthly credit model rather than per-second, so 429 is rare, but treat it and
+ # transient 5xx as retryable. Everything else (including 401/403) raises for the caller.
+ if response.status_code == 429 or response.status_code >= 500:
+ raise AppfiguresRetryableError(f"Appfigures API error (retryable): status={response.status_code}, url={url}")
+
+ if not response.ok:
+ logger.error(f"Appfigures API error: status={response.status_code}, body={response.text}, url={url}")
+ response.raise_for_status()
+
+ return response.json()
+
+
+def check_credentials(token: str, path: str = "/products/mine") -> int | None:
+ """Probe an endpoint and return its HTTP status, or None on a network failure.
+
+ The source layer maps the status: 200 = valid, 401 = bad token, 403 = valid token missing the
+ scope for that endpoint.
+ """
+ try:
+ response = make_tracked_session(headers=_headers(token), redact_values=(token,)).get(
+ f"{APPFIGURES_BASE_URL}{path}", params={"count": 1}, timeout=10
+ )
+ return response.status_code
+ except Exception:
+ return None
+
+
+def _iter_object(
+ session: requests.Session,
+ config: AppfiguresEndpointConfig,
+ logger: FilteringBoundLogger,
+) -> Iterator[list[dict[str, Any]]]:
+ """Single-request endpoints whose body is a JSON object keyed by id (e.g. /products/mine)."""
+ data = _fetch(session, f"{APPFIGURES_BASE_URL}{config.path}", {}, logger)
+ rows = list(data.values()) if isinstance(data, dict) else data
+ if rows:
+ yield rows
+
+
+def _iter_paged(
+ session: requests.Session,
+ config: AppfiguresEndpointConfig,
+ logger: FilteringBoundLogger,
+ manager: ResumableSourceManager[AppfiguresResumeConfig],
+ should_use_incremental_field: bool,
+ db_incremental_field_last_value: Any,
+) -> Iterator[list[dict[str, Any]]]:
+ """Page/count paginated endpoints with a flat list under `data_key` (e.g. /reviews)."""
+ resume = manager.load_state() if manager.can_resume() else None
+ page = resume.next_page if resume and resume.next_page else 1
+
+ params: dict[str, Any] = {"count": config.page_size, "page": page}
+ if config.sort:
+ params["sort"] = config.sort
+ if should_use_incremental_field and config.start_param:
+ start = _to_date_str(db_incremental_field_last_value)
+ if start:
+ params[config.start_param] = start
+
+ url = f"{APPFIGURES_BASE_URL}{config.path}"
+ while True:
+ data = _fetch(session, url, params, logger)
+ rows = data.get(config.data_key, []) if config.data_key else []
+ total_pages = data.get("pages", 1) or 1
+ this_page = data.get("this_page", page) or page
+
+ if rows:
+ yield rows
+
+ if not rows or this_page >= total_pages:
+ break
+
+ page += 1
+ params["page"] = page
+ # Save AFTER yielding so a crash re-fetches the page we were on rather than skipping it;
+ # merge dedupes the re-pulled rows on the primary key.
+ manager.save_state(AppfiguresResumeConfig(next_page=page))
+
+
+def _flatten_report(data: Any) -> list[dict[str, Any]]:
+ """Turn a group_by=dates report body ({"2024-01-01": {..metrics..}, ...}) into dated rows.
+
+ Only dict-valued entries are kept (defensive against any non-date envelope keys), and `date` is
+ injected so the row is uniquely keyed and partitionable. Sorted ascending so the watermark advances.
+ """
+ if not isinstance(data, dict):
+ return []
+ rows: list[dict[str, Any]] = []
+ for day in sorted(data.keys()):
+ metrics = data[day]
+ if isinstance(metrics, dict):
+ rows.append({"date": day, **metrics})
+ return rows
+
+
+def _iter_report(
+ session: requests.Session,
+ config: AppfiguresEndpointConfig,
+ logger: FilteringBoundLogger,
+ manager: ResumableSourceManager[AppfiguresResumeConfig],
+ should_use_incremental_field: bool,
+ db_incremental_field_last_value: Any,
+) -> Iterator[list[dict[str, Any]]]:
+ """Reports/* endpoints walked in fixed date windows (daily granularity caps at 30 days/request)."""
+ today = datetime.now(UTC).date()
+ window_days = config.window_days or 30
+
+ resume = manager.load_state() if manager.can_resume() else None
+ if resume and resume.window_start:
+ window_start = date.fromisoformat(resume.window_start)
+ elif should_use_incremental_field and db_incremental_field_last_value:
+ last = _to_date_str(db_incremental_field_last_value)
+ window_start = date.fromisoformat(last) if last else today - timedelta(days=REPORT_BACKFILL_DAYS)
+ else:
+ window_start = today - timedelta(days=REPORT_BACKFILL_DAYS)
+
+ url = f"{APPFIGURES_BASE_URL}{config.path}"
+ while window_start <= today:
+ window_end = min(window_start + timedelta(days=window_days - 1), today)
+ params: dict[str, Any] = {
+ "group_by": config.group_by,
+ "granularity": config.granularity,
+ "start_date": window_start.isoformat(),
+ "end_date": window_end.isoformat(),
+ }
+ rows = _flatten_report(_fetch(session, url, params, logger))
+ if rows:
+ yield rows
+
+ if window_end >= today:
+ break
+
+ window_start = window_end + timedelta(days=1)
+ # Save AFTER yielding the window so a crash re-fetches it rather than skipping; merge dedupes
+ # the re-pulled dates on the `date` primary key.
+ manager.save_state(AppfiguresResumeConfig(window_start=window_start.isoformat()))
+
+
+def get_rows(
+ token: str,
+ endpoint: str,
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[AppfiguresResumeConfig],
+ should_use_incremental_field: bool = False,
+ db_incremental_field_last_value: Any = None,
+) -> Iterator[list[dict[str, Any]]]:
+ config = APPFIGURES_ENDPOINTS[endpoint]
+ session = make_tracked_session(headers=_headers(token), redact_values=(token,))
+
+ if config.kind == "object":
+ yield from _iter_object(session, config, logger)
+ elif config.kind == "paged":
+ yield from _iter_paged(
+ session,
+ config,
+ logger,
+ resumable_source_manager,
+ should_use_incremental_field,
+ db_incremental_field_last_value,
+ )
+ else: # "report"
+ yield from _iter_report(
+ session,
+ config,
+ logger,
+ resumable_source_manager,
+ should_use_incremental_field,
+ db_incremental_field_last_value,
+ )
+
+
+def appfigures_source(
+ token: str,
+ endpoint: str,
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[AppfiguresResumeConfig],
+ should_use_incremental_field: bool = False,
+ db_incremental_field_last_value: Optional[Any] = None,
+) -> SourceResponse:
+ config = APPFIGURES_ENDPOINTS[endpoint]
+
+ return SourceResponse(
+ name=endpoint,
+ items=lambda: get_rows(
+ token=token,
+ 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,
+ # Reviews are paged ascending by `date`; reports are emitted oldest-window-first. Both arrive
+ # in ascending order so the incremental watermark checkpoints correctly.
+ sort_mode="asc",
+ )
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/appfigures/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/appfigures/canonical_descriptions.py
new file mode 100644
index 000000000000..7844f584279d
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/appfigures/canonical_descriptions.py
@@ -0,0 +1,72 @@
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (
+ CanonicalDescriptions,
+)
+
+# Descriptions taken from the Appfigures v2 API docs (https://docs.appfigures.com/api/reference/v2).
+CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
+ "products": {
+ "description": "Apps, games, books, and other content in your Appfigures account, each with an Appfigures-assigned product id that is consistent across stores.",
+ "docs_url": "https://docs.appfigures.com/api/reference/v2/products",
+ "columns": {
+ "id": "The product's unique, Appfigures-assigned id.",
+ "name": "Full product name.",
+ "developer": "Developer name.",
+ "icon": "URL of the product's store icon.",
+ "vendor_identifier": "The ref_no or sku the store uses to uniquely identify this product.",
+ "ref_no": "Store id of the product (currently Apple only).",
+ "sku": "Developer-assigned SKU or package name.",
+ "store_id": "Numeric id of the store the product belongs to.",
+ "store": "Name of the store (e.g. apple, google_play, amazon_appstore).",
+ "release_date": "Date the product was released to the store.",
+ "added_date": "Date the product was added by Appfigures.",
+ "updated_date": "Date the product was last updated.",
+ "version": "Current version of the product.",
+ "type": "Product type: app, inapp, or book.",
+ "active": "Whether the product is currently active in the store.",
+ "parent_id": "Product id of the parent product, for in-app purchases and child products.",
+ },
+ },
+ "reviews": {
+ "description": "App reviews across supported stores, filterable by product, country, stars, and creation date.",
+ "docs_url": "https://docs.appfigures.com/api/reference/v2/reviews",
+ "columns": {
+ "id": "Unique review id.",
+ "title": "Review title (translated when a language is requested).",
+ "review": "Full review text (translated when a language is requested).",
+ "original_title": "Pre-translation review title, if translated.",
+ "original_review": "Pre-translation review text, if translated.",
+ "author": "Review author name.",
+ "version": "App version the review was left on, if the store provides it.",
+ "date": "Date and time the review was left.",
+ "stars": "Star rating given in the review.",
+ "iso": "Country code of the review (iOS/Mac only; Google Play reviews are set to ZZ).",
+ "product": "Appfigures product id the review belongs to.",
+ "has_response": "Whether the developer responded to the review through Appfigures.",
+ "predicted_langs": "Algorithm-predicted language(s) of the review.",
+ },
+ },
+ "sales_report": {
+ "description": "Daily sales report aggregated across the account — downloads, updates, re-downloads, and related unit counts, one row per day.",
+ "docs_url": "https://docs.appfigures.com/api/reference/v2/sales",
+ "columns": {
+ "date": "Calendar day the metrics cover (yyyy-mm-dd).",
+ "downloads": "Total downloads on the day.",
+ "net_downloads": "Downloads net of returns.",
+ "updates": "App updates on the day.",
+ "re_downloads": "Re-downloads on the day.",
+ "uninstalls": "Uninstalls on the day, where reported.",
+ "revenue": "Revenue recognized on the day.",
+ "returns": "Number of returns on the day.",
+ },
+ },
+ "revenue_report": {
+ "description": "Daily revenue report aggregated across the account, one row per day.",
+ "docs_url": "https://docs.appfigures.com/api/reference/v2/revenue",
+ "columns": {
+ "date": "Calendar day the metrics cover (yyyy-mm-dd).",
+ "revenue": "Total revenue recognized on the day.",
+ "app_revenue": "Revenue from paid app downloads.",
+ "gross_revenue": "Revenue before store commission.",
+ },
+ },
+}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/appfigures/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/appfigures/settings.py
new file mode 100644
index 000000000000..bc6a3462868c
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/appfigures/settings.py
@@ -0,0 +1,118 @@
+from dataclasses import dataclass, field
+from typing import Literal, Optional
+
+from products.warehouse_sources.backend.types import IncrementalField, IncrementalFieldType
+
+# Three response/pagination shapes Appfigures exposes:
+# - "paged": /reviews — page/count pagination, flat list under a body key, server-side `start`
+# date filter on the row creation date. Incremental-capable.
+# - "object": /products/mine — a single response that's a JSON object keyed by product id (no
+# pagination, no server-side time filter). Full refresh only.
+# - "report": /reports/* — a single response that's a JSON object keyed by date (group_by=dates),
+# with a `start_date`/`end_date` server-side window and per-granularity range caps, so
+# we walk it in fixed-size date windows. Incremental by date window.
+EndpointKind = Literal["paged", "object", "report"]
+
+
+@dataclass
+class AppfiguresEndpointConfig:
+ name: str
+ path: str
+ kind: EndpointKind
+ primary_keys: list[str]
+ 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-seen field.
+ partition_key: Optional[str] = None
+ should_sync_default: bool = True
+
+ # "paged" endpoints (reviews)
+ # Body key the page's rows live under (e.g. {"total":..,"reviews":[...]}).
+ data_key: Optional[str] = None
+ # Query param name for the server-side creation-date lower bound (yyyy-mm-dd), if any.
+ start_param: Optional[str] = None
+ # Sort param value to force a stable ascending order so the incremental watermark advances.
+ sort: Optional[str] = None
+ page_size: int = 500
+
+ # "report" endpoints (reports/*)
+ group_by: Optional[str] = None
+ granularity: Optional[str] = None
+ # Max days fetched per request — daily granularity is capped at 30 days by Appfigures.
+ window_days: Optional[int] = None
+
+
+# `date` on reviews is a full timestamp (e.g. 2017-05-19T17:05:00); on reports it's a day string.
+_REVIEW_DATE_FIELD: IncrementalField = {
+ "label": "date",
+ "type": IncrementalFieldType.DateTime,
+ "field": "date",
+ "field_type": IncrementalFieldType.DateTime,
+}
+
+_REPORT_DATE_FIELD: IncrementalField = {
+ "label": "date",
+ "type": IncrementalFieldType.Date,
+ "field": "date",
+ "field_type": IncrementalFieldType.Date,
+}
+
+
+APPFIGURES_ENDPOINTS: dict[str, AppfiguresEndpointConfig] = {
+ # The account's product catalog — a small dimension table. Object keyed by product id.
+ "products": AppfiguresEndpointConfig(
+ name="products",
+ path="/products/mine",
+ kind="object",
+ primary_keys=["id"],
+ partition_key="added_date",
+ ),
+ # App reviews across stores. Paged, with a server-side creation-date filter we drive incrementally.
+ "reviews": AppfiguresEndpointConfig(
+ name="reviews",
+ path="/reviews",
+ kind="paged",
+ primary_keys=["id"],
+ data_key="reviews",
+ start_param="start",
+ # Appfigures docs: bare `date` sorts ascending (oldest first), `-date` reverses it. Ascending
+ # keeps newly-arriving reviews at the tail of the page sequence so earlier pages don't shift
+ # mid-backfill (which would otherwise drop the boundary row).
+ sort="date",
+ partition_key="date",
+ default_incremental_field="date",
+ incremental_fields=[_REVIEW_DATE_FIELD],
+ ),
+ # Daily sales (downloads/units) aggregated across the account, one row per day.
+ "sales_report": AppfiguresEndpointConfig(
+ name="sales_report",
+ path="/reports/sales",
+ kind="report",
+ primary_keys=["date"],
+ group_by="dates",
+ granularity="daily",
+ window_days=30,
+ partition_key="date",
+ default_incremental_field="date",
+ incremental_fields=[_REPORT_DATE_FIELD],
+ ),
+ # Daily revenue aggregated across the account, one row per day.
+ "revenue_report": AppfiguresEndpointConfig(
+ name="revenue_report",
+ path="/reports/revenue",
+ kind="report",
+ primary_keys=["date"],
+ group_by="dates",
+ granularity="daily",
+ window_days=30,
+ partition_key="date",
+ default_incremental_field="date",
+ incremental_fields=[_REPORT_DATE_FIELD],
+ ),
+}
+
+ENDPOINTS = tuple(APPFIGURES_ENDPOINTS.keys())
+
+INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {
+ name: config.incremental_fields for name, config in APPFIGURES_ENDPOINTS.items()
+}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/appfigures/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/appfigures/source.py
index b2f6551c97b0..c6cc95ae3721 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/appfigures/source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/appfigures/source.py
@@ -1,19 +1,43 @@
-from typing import cast
+from typing import Optional, cast
from 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.appfigures.appfigures import (
+ AppfiguresResumeConfig,
+ appfigures_source,
+ check_credentials,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.appfigures.settings import (
+ APPFIGURES_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 SourceSchema
from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs import AppfiguresSourceConfig
from products.warehouse_sources.backend.types import ExternalDataSourceType
@SourceRegistry.register
-class AppfiguresSource(SimpleSource[AppfiguresSourceConfig]):
+class AppfiguresSource(ResumableSource[AppfiguresSourceConfig, AppfiguresResumeConfig]):
+ lists_tables_without_credentials = True # static endpoint catalog — safe for public docs
+
@property
def source_type(self) -> ExternalDataSourceType:
return ExternalDataSourceType.APPFIGURES
@@ -24,7 +48,113 @@ class AppfiguresSource(SimpleSource[AppfiguresSourceConfig]):
name=SchemaExternalDataSourceType.APPFIGURES,
category=DataWarehouseSourceCategory.ANALYTICS,
label="Appfigures",
- iconPath="/static/services/appfigures.png",
- fields=cast(list[FieldType], []),
+ releaseStatus=ReleaseStatus.ALPHA,
unreleasedSource=True,
+ caption="""Enter an Appfigures Personal Access Token to pull your app-store analytics into the PostHog Data warehouse.
+
+Create an API client and Personal Access Token at [appfigures.com/developers/keys](https://appfigures.com/developers/keys). When creating the client, grant the data sets you want to sync:
+- `products:read` — Products
+- `public:read` — Reviews
+- `private:read` — Sales and Revenue reports
+""",
+ iconPath="/static/services/appfigures.png",
+ docsUrl="https://posthog.com/docs/cdp/sources/appfigures",
+ fields=cast(
+ list[FieldType],
+ [
+ SourceFieldInputConfig(
+ name="personal_access_token",
+ label="Personal access token",
+ type=SourceFieldInputConfigType.PASSWORD,
+ required=True,
+ placeholder="pat_...",
+ secret=True,
+ ),
+ ],
+ ),
+ )
+
+ def get_canonical_descriptions(self) -> CanonicalDescriptions:
+ from products.warehouse_sources.backend.temporal.data_imports.sources.appfigures.canonical_descriptions import (
+ CANONICAL_DESCRIPTIONS,
+ )
+
+ return CANONICAL_DESCRIPTIONS
+
+ def get_non_retryable_errors(self) -> dict[str, str | None]:
+ # A bad/expired token (401) or a token missing the endpoint's scope (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.appfigures.com": "Your Appfigures personal access token is invalid or expired. Create a new token in your Appfigures developer settings, then reconnect.",
+ "403 Client Error: Forbidden for url: https://api.appfigures.com": "Your Appfigures personal access token is missing the scope needed to sync this data. Grant the required data sets to your API client, then reconnect.",
+ }
+
+ def get_schemas(
+ self,
+ config: AppfiguresSourceConfig,
+ 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 = APPFIGURES_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: AppfiguresSourceConfig, team_id: int, schema_name: Optional[str] = None
+ ) -> tuple[bool, str | None]:
+ # Probe the endpoint the requested schema actually hits (so per-table scope checks are
+ # accurate), or the cheap products catalog at source-create.
+ path = "/products/mine"
+ if schema_name and schema_name in APPFIGURES_ENDPOINTS:
+ path = APPFIGURES_ENDPOINTS[schema_name].path
+
+ status = check_credentials(config.personal_access_token, path)
+ if status is None:
+ return False, "Could not reach Appfigures. Please try again."
+ if status == 401:
+ return False, "Invalid Appfigures personal access token"
+ if status == 403:
+ # A valid token may simply lack this endpoint's scope. Don't block source-create over it;
+ # only fail when validating a specific schema the user chose to sync.
+ if schema_name:
+ return False, f"Your token is missing the scope required to sync '{schema_name}'"
+ return True, None
+ if status == 200:
+ return True, None
+ return False, f"Appfigures returned status {status}"
+
+ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[AppfiguresResumeConfig]:
+ return ResumableSourceManager[AppfiguresResumeConfig](inputs, AppfiguresResumeConfig)
+
+ def source_for_pipeline(
+ self,
+ config: AppfiguresSourceConfig,
+ resumable_source_manager: ResumableSourceManager[AppfiguresResumeConfig],
+ inputs: SourceInputs,
+ ) -> SourceResponse:
+ return appfigures_source(
+ token=config.personal_access_token,
+ 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/appfigures/tests/test_appfigures.py b/products/warehouse_sources/backend/temporal/data_imports/sources/appfigures/tests/test_appfigures.py
new file mode 100644
index 000000000000..25d5d63a0100
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/appfigures/tests/test_appfigures.py
@@ -0,0 +1,252 @@
+from datetime import UTC, date, datetime
+from typing import Any
+
+import pytest
+from freezegun import freeze_time
+from unittest import mock
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.appfigures import appfigures
+from products.warehouse_sources.backend.temporal.data_imports.sources.appfigures.appfigures import (
+ AppfiguresResumeConfig,
+ _flatten_report,
+ _headers,
+ _to_date_str,
+ appfigures_source,
+ check_credentials,
+ get_rows,
+)
+
+_MODULE = "products.warehouse_sources.backend.temporal.data_imports.sources.appfigures.appfigures"
+
+
+def _manager(resume: AppfiguresResumeConfig | None = None) -> mock.MagicMock:
+ manager = mock.MagicMock()
+ manager.can_resume.return_value = resume is not None
+ manager.load_state.return_value = resume
+ return manager
+
+
+class TestHeaders:
+ def test_bearer_header(self):
+ headers = _headers("pat_123")
+ assert headers["Authorization"] == "Bearer pat_123"
+ assert headers["Accept"] == "application/json"
+
+
+class TestToDateStr:
+ @pytest.mark.parametrize(
+ "value,expected",
+ [
+ (None, None),
+ (datetime(2024, 3, 4, 2, 58, 14, tzinfo=UTC), "2024-03-04"),
+ (datetime(2024, 3, 4, 23, 0, 0), "2024-03-04"),
+ (date(2024, 3, 4), "2024-03-04"),
+ ("2024-03-04T05:06:07", "2024-03-04"),
+ ("2024-03-04", "2024-03-04"),
+ ],
+ )
+ def test_to_date_str(self, value: Any, expected: str | None):
+ assert _to_date_str(value) == expected
+
+ @pytest.mark.parametrize("value", ["2024-01", "not-a-date", "garbage123"])
+ def test_to_date_str_raises_on_unparseable_fragment(self, value: str):
+ with pytest.raises(ValueError, match="Could not derive a yyyy-mm-dd date"):
+ _to_date_str(value)
+
+
+class TestFlattenReport:
+ def test_keyed_by_date_becomes_sorted_rows_with_date_injected(self):
+ body = {
+ "2024-01-02": {"downloads": 5, "revenue": 1.0},
+ "2024-01-01": {"downloads": 3, "revenue": 0.5},
+ }
+ rows = _flatten_report(body)
+ assert rows == [
+ {"date": "2024-01-01", "downloads": 3, "revenue": 0.5},
+ {"date": "2024-01-02", "downloads": 5, "revenue": 1.0},
+ ]
+
+ def test_non_dict_values_are_skipped(self):
+ assert _flatten_report({"2024-01-01": {"downloads": 1}, "meta": "ignored"}) == [
+ {"date": "2024-01-01", "downloads": 1}
+ ]
+
+ def test_non_dict_input_returns_empty(self):
+ assert _flatten_report([1, 2, 3]) == []
+
+
+class TestIterObject:
+ def test_products_object_flattened_to_list_of_values(self):
+ body = {"42": {"id": 42, "name": "App A"}, "7": {"id": 7, "name": "App B"}}
+ with mock.patch(f"{_MODULE}._fetch", return_value=body):
+ batches = list(
+ get_rows(token="pat", endpoint="products", logger=mock.MagicMock(), resumable_source_manager=_manager())
+ )
+ assert len(batches) == 1
+ assert {row["id"] for row in batches[0]} == {42, 7}
+
+
+class TestIterPaged:
+ def test_walks_all_pages_using_pages_and_this_page(self):
+ pages = [
+ {"total": 3, "pages": 2, "this_page": 1, "reviews": [{"id": "a"}, {"id": "b"}]},
+ {"total": 3, "pages": 2, "this_page": 2, "reviews": [{"id": "c"}]},
+ ]
+ # The transport mutates one params dict across pages, so snapshot the `page` per call.
+ seen_pages: list[int] = []
+
+ def fake_fetch(_session, _url, params, _logger):
+ seen_pages.append(params["page"])
+ return pages[len(seen_pages) - 1]
+
+ manager = _manager()
+ with mock.patch(f"{_MODULE}._fetch", side_effect=fake_fetch) as fetch:
+ batches = list(
+ get_rows(
+ token="pat",
+ endpoint="reviews",
+ logger=mock.MagicMock(),
+ resumable_source_manager=manager,
+ )
+ )
+ assert [r["id"] for batch in batches for r in batch] == ["a", "b", "c"]
+ assert seen_pages == [1, 2]
+ # First request uses the configured sort and page size.
+ first_params = fetch.call_args_list[0].args[2]
+ assert first_params["sort"] == "date"
+ assert first_params["count"] == 500
+ # State saved after yielding the first page, pointing at the next page to fetch.
+ manager.save_state.assert_called_once_with(AppfiguresResumeConfig(next_page=2))
+
+ def test_incremental_sets_start_param_from_watermark(self):
+ body = {"total": 0, "pages": 1, "this_page": 1, "reviews": []}
+ with mock.patch(f"{_MODULE}._fetch", return_value=body) as fetch:
+ list(
+ get_rows(
+ token="pat",
+ endpoint="reviews",
+ logger=mock.MagicMock(),
+ resumable_source_manager=_manager(),
+ should_use_incremental_field=True,
+ db_incremental_field_last_value=datetime(2024, 5, 1, 12, 0, tzinfo=UTC),
+ )
+ )
+ assert fetch.call_args_list[0].args[2]["start"] == "2024-05-01"
+
+ def test_resume_starts_from_saved_page(self):
+ body = {"total": 1, "pages": 3, "this_page": 3, "reviews": [{"id": "z"}]}
+ with mock.patch(f"{_MODULE}._fetch", return_value=body) as fetch:
+ list(
+ get_rows(
+ token="pat",
+ endpoint="reviews",
+ logger=mock.MagicMock(),
+ resumable_source_manager=_manager(AppfiguresResumeConfig(next_page=3)),
+ )
+ )
+ assert fetch.call_args_list[0].args[2]["page"] == 3
+
+
+class TestIterReport:
+ @freeze_time("2024-02-15")
+ def test_windows_date_range_into_chunks(self):
+ body_by_window: dict[str, dict] = {
+ "2024-01-01": {"2024-01-01": {"downloads": 1}},
+ "2024-01-31": {"2024-01-31": {"downloads": 2}},
+ }
+
+ def fake_fetch(_session, _url, params, _logger):
+ return body_by_window[params["start_date"]]
+
+ manager = _manager()
+ with mock.patch(f"{_MODULE}._fetch", side_effect=fake_fetch) as fetch:
+ batches = list(
+ get_rows(
+ token="pat",
+ endpoint="sales_report",
+ logger=mock.MagicMock(),
+ resumable_source_manager=manager,
+ should_use_incremental_field=True,
+ db_incremental_field_last_value=date(2024, 1, 1),
+ )
+ )
+ windows = [(c.args[2]["start_date"], c.args[2]["end_date"]) for c in fetch.call_args_list]
+ # 30-day windows: [01-01..01-30], then [01-31..02-15] (clamped to today).
+ assert windows == [("2024-01-01", "2024-01-30"), ("2024-01-31", "2024-02-15")]
+ assert [r["date"] for batch in batches for r in batch] == ["2024-01-01", "2024-01-31"]
+ # State saved after the first window, pointing at the next window's start.
+ manager.save_state.assert_called_once_with(AppfiguresResumeConfig(window_start="2024-01-31"))
+
+ @freeze_time("2024-02-15")
+ def test_report_request_sets_group_by_and_granularity(self):
+ with mock.patch(f"{_MODULE}._fetch", return_value={}) as fetch:
+ list(
+ get_rows(
+ token="pat",
+ endpoint="sales_report",
+ logger=mock.MagicMock(),
+ resumable_source_manager=_manager(),
+ should_use_incremental_field=True,
+ db_incremental_field_last_value=date(2024, 2, 1),
+ )
+ )
+ params = fetch.call_args_list[0].args[2]
+ assert params["group_by"] == "dates"
+ assert params["granularity"] == "daily"
+
+ @freeze_time("2024-02-15")
+ def test_resume_starts_from_saved_window(self):
+ with mock.patch(f"{_MODULE}._fetch", return_value={}) as fetch:
+ list(
+ get_rows(
+ token="pat",
+ endpoint="sales_report",
+ logger=mock.MagicMock(),
+ resumable_source_manager=_manager(AppfiguresResumeConfig(window_start="2024-02-10")),
+ )
+ )
+ assert fetch.call_args_list[0].args[2]["start_date"] == "2024-02-10"
+
+
+class TestCheckCredentials:
+ @pytest.mark.parametrize("status", [200, 401, 403, 500])
+ def test_returns_status_code(self, status):
+ session = mock.MagicMock()
+ session.get.return_value = mock.MagicMock(status_code=status)
+ with mock.patch(f"{_MODULE}.make_tracked_session", return_value=session):
+ assert check_credentials("pat", "/products/mine") == status
+
+ def test_network_failure_returns_none(self):
+ session = mock.MagicMock()
+ session.get.side_effect = Exception("boom")
+ with mock.patch(f"{_MODULE}.make_tracked_session", return_value=session):
+ assert check_credentials("pat") is None
+
+
+class TestAppfiguresSourceResponse:
+ @pytest.mark.parametrize(
+ "endpoint,primary_keys,partition_key",
+ [
+ ("products", ["id"], "added_date"),
+ ("reviews", ["id"], "date"),
+ ("sales_report", ["date"], "date"),
+ ("revenue_report", ["date"], "date"),
+ ],
+ )
+ def test_response_shape(self, endpoint, primary_keys, partition_key):
+ response = appfigures_source(
+ token="pat",
+ endpoint=endpoint,
+ logger=mock.MagicMock(),
+ resumable_source_manager=_manager(),
+ )
+ assert response.name == endpoint
+ assert response.primary_keys == primary_keys
+ assert response.partition_mode == "datetime"
+ assert response.partition_keys == [partition_key]
+ assert response.sort_mode == "asc"
+
+
+class TestRetryableError:
+ def test_retryable_error_is_exception(self):
+ assert issubclass(appfigures.AppfiguresRetryableError, Exception)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/appfigures/tests/test_appfigures_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/appfigures/tests/test_appfigures_source.py
new file mode 100644
index 000000000000..408124fc179d
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/appfigures/tests/test_appfigures_source.py
@@ -0,0 +1,174 @@
+import pytest
+from unittest import mock
+
+from posthog.schema import (
+ DataWarehouseSourceCategory,
+ ReleaseStatus,
+ SourceFieldInputConfig,
+ SourceFieldInputConfigType,
+)
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.appfigures.appfigures import (
+ AppfiguresResumeConfig,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.appfigures.settings import ENDPOINTS
+from products.warehouse_sources.backend.temporal.data_imports.sources.appfigures.source import AppfiguresSource
+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 AppfiguresSourceConfig
+from products.warehouse_sources.backend.types import ExternalDataSourceType
+
+
+class TestAppfiguresSource:
+ def setup_method(self):
+ self.source = AppfiguresSource()
+ self.team_id = 123
+ self.config = AppfiguresSourceConfig(personal_access_token="pat_test")
+
+ def test_source_type(self):
+ assert self.source.source_type == ExternalDataSourceType.APPFIGURES
+
+ def test_get_source_config(self):
+ config = self.source.get_source_config
+ assert config.name.value == "Appfigures"
+ assert config.label == "Appfigures"
+ assert config.category == DataWarehouseSourceCategory.ANALYTICS
+ assert config.releaseStatus == ReleaseStatus.ALPHA
+ assert config.unreleasedSource is True
+ assert config.iconPath == "/static/services/appfigures.png"
+ assert config.docsUrl == "https://posthog.com/docs/cdp/sources/appfigures"
+
+ def test_token_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 == "personal_access_token"
+ )
+ 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)
+
+ def test_products_is_full_refresh_reports_and_reviews_incremental(self):
+ schemas = {s.name: s for s in self.source.get_schemas(self.config, self.team_id)}
+ assert schemas["products"].supports_incremental is False
+ assert schemas["products"].incremental_fields == []
+ for name in ("reviews", "sales_report", "revenue_report"):
+ assert schemas[name].supports_incremental is True
+ assert [f["field"] for f in schemas[name].incremental_fields] == ["date"]
+
+ 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"
+
+ def test_get_schemas_filtered_unknown_name_returns_empty(self):
+ assert self.source.get_schemas(self.config, self.team_id, names=["nope"]) == []
+
+ @pytest.mark.parametrize(
+ "status,schema_name,expected_ok",
+ [
+ (200, None, True),
+ (200, "reviews", True),
+ (401, None, False),
+ (401, "reviews", False),
+ # 403 at source-create is a valid token missing an unrelated scope — accept it.
+ (403, None, True),
+ # 403 for a specific schema means the token can't sync that table — reject.
+ (403, "reviews", False),
+ (500, None, False),
+ (None, None, False),
+ ],
+ )
+ def test_validate_credentials(self, status, schema_name, expected_ok):
+ with mock.patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.appfigures.source.check_credentials",
+ return_value=status,
+ ):
+ ok, _ = self.source.validate_credentials(self.config, self.team_id, schema_name=schema_name)
+ assert ok is expected_ok
+
+ def test_validate_credentials_probes_schema_specific_path(self):
+ with mock.patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.appfigures.source.check_credentials",
+ return_value=200,
+ ) as probe:
+ self.source.validate_credentials(self.config, self.team_id, schema_name="reviews")
+ probe.assert_called_once_with("pat_test", "/reviews")
+
+ def test_validate_credentials_defaults_to_products_path(self):
+ with mock.patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.appfigures.source.check_credentials",
+ return_value=200,
+ ) as probe:
+ self.source.validate_credentials(self.config, self.team_id)
+ probe.assert_called_once_with("pat_test", "/products/mine")
+
+ @pytest.mark.parametrize(
+ "observed_error",
+ [
+ "401 Client Error: Unauthorized for url: https://api.appfigures.com/v2/reviews?count=1",
+ "403 Client Error: Forbidden for url: https://api.appfigures.com/v2/reports/sales",
+ ],
+ )
+ def test_non_retryable_errors_match_auth_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.appfigures.com/v2/reviews",
+ ],
+ )
+ def test_non_retryable_errors_ignore_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):
+ inputs = mock.MagicMock()
+ manager = self.source.get_resumable_source_manager(inputs)
+ assert isinstance(manager, ResumableSourceManager)
+ assert manager._data_class is AppfiguresResumeConfig
+
+ 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.appfigures.source.appfigures_source"
+ ) as appfigures_source:
+ self.source.source_for_pipeline(self.config, manager, inputs)
+ appfigures_source.assert_called_once()
+ kwargs = appfigures_source.call_args.kwargs
+ assert kwargs["token"] == "pat_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 = "products"
+ 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.appfigures.source.appfigures_source"
+ ) as appfigures_source:
+ self.source.source_for_pipeline(self.config, manager, inputs)
+ assert appfigures_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(ENDPOINTS)
+ # The four shipped endpoints are all documented.
+ assert set(descriptions.keys()) == set(ENDPOINTS)
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.py
index ff7719a473e0..c5cad75892a1 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
@@ -290,7 +290,7 @@ class AppcuesSourceConfig(config.Config):
@config.config
class AppfiguresSourceConfig(config.Config):
- pass
+ personal_access_token: str
@config.config