: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 appsflyer import source (#62956)
Tom Owers8f9dce5fee62
diff --git a/posthog/temporal/data_imports/sources/SOURCES.md b/posthog/temporal/data_imports/sources/SOURCES.mdindex 4aa5fecd925f..8c249fe33062 100644--- a/posthog/temporal/data_imports/sources/SOURCES.md+++ b/posthog/temporal/data_imports/sources/SOURCES.md@@ -48,6 +48,7 @@ the row lists both.| aircall | HTTP | requests | ✅ || airtable | HTTP | requests | ✅ || amplitude | HTTP | requests | ✅ |+| appsflyer | HTTP (CSV reports) | requests | ✅ || asana | HTTP | requests | ✅ || ashby | HTTP | requests | ✅ || attio | HTTP | requests + `rest_source.RESTClient` | ✅ |@@ -216,7 +217,6 @@ doesn't conflict with concurrent PRs.- amazon_selling_partner- apollo- apple_search_ads-- appsflyer- attentive- auth0- azure_blobdiff --git a/posthog/temporal/data_imports/sources/appsflyer/appsflyer.py b/posthog/temporal/data_imports/sources/appsflyer/appsflyer.pynew file mode 100644index 000000000000..746ffce3d1ac--- /dev/null+++ b/posthog/temporal/data_imports/sources/appsflyer/appsflyer.py@@ -0,0 +1,178 @@+import io+import re+import csv+from collections.abc import Iterator+from datetime import UTC, date, datetime, timedelta+from typing import Any+from urllib.parse import quote, urlencode++import requests+from structlog.types import FilteringBoundLogger+from tenacity import retry, retry_if_exception_type, stop_after_attempt, wait_exponential_jitter++from posthog.temporal.data_imports.pipelines.pipeline.typings import SourceResponse+from posthog.temporal.data_imports.sources.appsflyer.settings import APPSFLYER_ENDPOINTS+from posthog.temporal.data_imports.sources.common.http import make_tracked_session++APPSFLYER_BASE_URL = "https://hq1.appsflyer.com"+# Aggregate pull requests cap the date range at ~1000 days.+MAX_WINDOW_DAYS = 999+# AppsFlyer doesn't finalize data until ~48h after the UTC day; re-fetch the+# trailing days each incremental run (merge dedupes on the dimension key).+LOOKBACK_DAYS = 2+REQUEST_TIMEOUT_SECONDS = 300+MAX_RETRY_ATTEMPTS = 5+# Yield rows in chunks so huge reports don't build one giant list.+CHUNK_SIZE = 5000+++class AppsFlyerRetryableError(Exception):+ pass+++def _get_session(api_token: str) -> requests.Session:+ return make_tracked_session(headers={"Authorization": f"Bearer {api_token}"}, redact_values=(api_token,))+++def _validate_app_id(app_id: str) -> str:+ app_id = app_id.strip()+ if not re.fullmatch(r"[a-zA-Z0-9._-]+", app_id):+ raise ValueError(f"Invalid AppsFlyer app id: {app_id}")+ return app_id+++def _normalize_header(header: str) -> str:+ """CSV headers like 'Media Source (pid)' become stable snake_case columns."""+ return re.sub(r"[^0-9a-zA-Z]+", "_", header).strip("_").lower()+++def _to_date(value: Any) -> date:+ if isinstance(value, datetime):+ return (value if value.tzinfo else value.replace(tzinfo=UTC)).astimezone(UTC).date()+ if isinstance(value, date):+ return value+ return date.fromisoformat(str(value)[:10])+++def _parse_csv_rows(text: str, logger: FilteringBoundLogger | None = None) -> Iterator[dict[str, Any]]:+ reader = csv.reader(io.StringIO(text))+ headers: list[str] | None = None+ for row in reader:+ if headers is None:+ headers = [_normalize_header(header) for header in row]+ continue+ if not any(cell.strip() for cell in row):+ continue+ # zip would silently truncate a short row, leaving primary-key columns absent and+ # corrupting dedupe — drop the malformed row instead so the failure is explicit.+ if len(row) != len(headers):+ if logger is not None:+ logger.warning(+ "AppsFlyer CSV row length mismatch; skipping row",+ expected=len(headers),+ got=len(row),+ )+ continue+ yield dict(zip(headers, row))+++def validate_credentials(api_token: str, app_id: str) -> bool:+ """Confirm the token and app id are valid with a one-day report probe.++ Raises ``AppsFlyerRetryableError`` on rate-limit / 5xx responses and lets transport+ errors propagate so the caller can tell a transient failure apart from a bad credential.+ """+ try:+ app = _validate_app_id(app_id)+ except ValueError:+ return False+ today = datetime.now(UTC).strftime("%Y-%m-%d")+ response = _get_session(api_token).get(+ f"{APPSFLYER_BASE_URL}/api/agg-data/export/app/{quote(app)}/dailyreport/v5"+ f"?{urlencode({'from': today, 'to': today})}",+ timeout=30,+ )+ if response.status_code == 429 or response.status_code >= 500:+ raise AppsFlyerRetryableError(f"AppsFlyer API error (retryable): status={response.status_code}")+ return response.status_code == 200+++def get_rows(+ api_token: str,+ app_id: str,+ endpoint: str,+ logger: FilteringBoundLogger,+ should_use_incremental_field: bool = False,+ db_incremental_field_last_value: Any = None,+) -> Iterator[list[dict[str, Any]]]:+ config = APPSFLYER_ENDPOINTS[endpoint]+ session = _get_session(api_token)+ app = _validate_app_id(app_id)++ today = datetime.now(UTC).date()+ if should_use_incremental_field and db_incremental_field_last_value is not None:+ start = _to_date(db_incremental_field_last_value) - timedelta(days=LOOKBACK_DAYS)+ else:+ start = today - timedelta(days=MAX_WINDOW_DAYS)+ start = min(max(start, today - timedelta(days=MAX_WINDOW_DAYS)), today)++ @retry(+ retry=retry_if_exception_type((AppsFlyerRetryableError, requests.ReadTimeout, requests.ConnectionError)),+ stop=stop_after_attempt(MAX_RETRY_ATTEMPTS),+ wait=wait_exponential_jitter(initial=5, max=120),+ reraise=True,+ )+ def fetch_report() -> str:+ params = {"from": start.strftime("%Y-%m-%d"), "to": today.strftime("%Y-%m-%d")}+ url = f"{APPSFLYER_BASE_URL}/api/agg-data/export/app/{quote(app)}/{config.report}/v5?{urlencode(params)}"+ response = session.get(url, timeout=REQUEST_TIMEOUT_SECONDS)++ if response.status_code == 429 or response.status_code >= 500:+ raise AppsFlyerRetryableError(f"AppsFlyer API error (retryable): status={response.status_code}, url={url}")++ if not response.ok:+ logger.error(f"AppsFlyer API error: status={response.status_code}, body={response.text[:500]}, url={url}")+ response.raise_for_status()++ return response.text++ chunk: list[dict[str, Any]] = []+ for row in _parse_csv_rows(fetch_report(), logger):+ chunk.append(row)+ if len(chunk) >= CHUNK_SIZE:+ yield chunk+ chunk = []+ if chunk:+ yield chunk+++def appsflyer_source(+ api_token: str,+ app_id: str,+ endpoint: str,+ logger: FilteringBoundLogger,+ should_use_incremental_field: bool = False,+ db_incremental_field_last_value: Any = None,+) -> SourceResponse:+ config = APPSFLYER_ENDPOINTS[endpoint]++ return SourceResponse(+ name=endpoint,+ items=lambda: get_rows(+ api_token=api_token,+ app_id=app_id,+ endpoint=endpoint,+ logger=logger,+ 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",+ partition_format="month",+ partition_keys=["date"],+ sort_mode="asc",+ # Dimension keys can collide (e.g. blank campaign values).+ has_duplicate_primary_keys=True,+ )diff --git a/posthog/temporal/data_imports/sources/appsflyer/settings.py b/posthog/temporal/data_imports/sources/appsflyer/settings.pynew file mode 100644index 000000000000..0abe0d50e8b3--- /dev/null+++ b/posthog/temporal/data_imports/sources/appsflyer/settings.py@@ -0,0 +1,52 @@+from dataclasses import dataclass, field++from products.data_warehouse.backend.types import IncrementalField, IncrementalFieldType++_DATE_INCREMENTAL_FIELDS: list[IncrementalField] = [+ {+ "label": "date",+ "type": IncrementalFieldType.Date,+ "field": "date",+ "field_type": IncrementalFieldType.Date,+ },+]+++@dataclass+class AppsFlyerEndpointConfig:+ name: str+ # Report slug in /api/agg-data/export/app/{app_id}/{report}/v5.+ report: str+ # Aggregate reports have no row ids; the dimension columns (normalized+ # headers) form the key, and collisions are tolerated via the duplicate-pk+ # flag.+ primary_keys: list[str] = field(+ default_factory=lambda: ["date", "agency_pmd_af_prt", "media_source_pid", "campaign_c"]+ )+ incremental_fields: list[IncrementalField] = field(default_factory=lambda: list(_DATE_INCREMENTAL_FIELDS))+++# AppsFlyer's aggregate Pull API returns CSV per date window (max ~1000 days);+# headers are normalized to snake_case columns. Raw-data Pull APIs require+# separate subscriptions and are a follow-up.+APPSFLYER_ENDPOINTS: dict[str, AppsFlyerEndpointConfig] = {+ "daily_report": AppsFlyerEndpointConfig(+ name="daily_report",+ report="dailyreport",+ ),+ "geo_report": AppsFlyerEndpointConfig(+ name="geo_report",+ report="geo_by_date_report",+ primary_keys=["date", "agency_pmd_af_prt", "media_source_pid", "campaign_c", "country"],+ ),+ "partners_report": AppsFlyerEndpointConfig(+ name="partners_report",+ report="partners_by_date_report",+ ),+}++ENDPOINTS = tuple(APPSFLYER_ENDPOINTS.keys())++INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {+ name: config.incremental_fields for name, config in APPSFLYER_ENDPOINTS.items() if config.incremental_fields+}diff --git a/posthog/temporal/data_imports/sources/appsflyer/source.py b/posthog/temporal/data_imports/sources/appsflyer/source.pyindex af6aad7d06ba..206dbd97be19 100644--- a/posthog/temporal/data_imports/sources/appsflyer/source.py+++ b/posthog/temporal/data_imports/sources/appsflyer/source.py@@ -1,12 +1,25 @@-from typing import cast+from typing import Optional, cast++import requestsfrom posthog.schema import (ExternalDataSourceType as SchemaExternalDataSourceType,+ ReleaseStatus,SourceConfig,+ SourceFieldInputConfig,+ SourceFieldInputConfigType,)+from posthog.temporal.data_imports.pipelines.pipeline.typings import SourceInputs, SourceResponse+from posthog.temporal.data_imports.sources.appsflyer.appsflyer import (+ AppsFlyerRetryableError,+ appsflyer_source,+ validate_credentials as validate_appsflyer_credentials,+)+from posthog.temporal.data_imports.sources.appsflyer.settings import ENDPOINTS, INCREMENTAL_FIELDSfrom posthog.temporal.data_imports.sources.common.base import FieldType, SimpleSourcefrom posthog.temporal.data_imports.sources.common.registry import SourceRegistry+from posthog.temporal.data_imports.sources.common.schema import SourceSchemafrom posthog.temporal.data_imports.sources.generated_configs import AppsFlyerSourceConfigfrom products.data_warehouse.backend.types import ExternalDataSourceType@@ -18,12 +31,100 @@ class AppsFlyerSource(SimpleSource[AppsFlyerSourceConfig]):def source_type(self) -> ExternalDataSourceType:return ExternalDataSourceType.APPSFLYER+ @property+ def connection_host_fields(self) -> list[str]:+ # app_id selects which AppsFlyer app the stored token is used against; changing it must+ # require re-entering the secret so a preserved token can't be retargeted at another app.+ return ["app_id"]++ def get_non_retryable_errors(self) -> dict[str, str | None]:+ return {+ "401 Client Error: Unauthorized for url: https://hq1.appsflyer.com": "AppsFlyer authentication failed. Please check your API token (V2).",+ "403 Client Error: Forbidden for url: https://hq1.appsflyer.com": "AppsFlyer denied access. Please check that your account's subscription includes the aggregate Pull API and the app id is correct.",+ "404 Client Error: Not Found for url: https://hq1.appsflyer.com": "AppsFlyer app not found. Please check the app id.",+ }+@propertydef get_source_config(self) -> SourceConfig:return SourceConfig(name=SchemaExternalDataSourceType.APPS_FLYER,label="AppsFlyer",+ caption="""Enter your AppsFlyer credentials to pull aggregate performance reports into the PostHog Data warehouse.++You can find your API token (V2) in AppsFlyer under your account menu > Security center > AppsFlyer API tokens. The app id is your app's identifier as shown in the dashboard (e.g. `id123456789` for iOS or the package name for Android) — add one source per app.""",iconPath="/static/services/appsflyer.png",- fields=cast(list[FieldType], []),- unreleasedSource=True,+ docsUrl="https://posthog.com/docs/cdp/sources/appsflyer",+ releaseStatus=ReleaseStatus.ALPHA,+ fields=cast(+ list[FieldType],+ [+ SourceFieldInputConfig(+ name="app_id",+ label="App ID",+ type=SourceFieldInputConfigType.TEXT,+ required=True,+ placeholder="id123456789",+ secret=False,+ ),+ SourceFieldInputConfig(+ name="api_token",+ label="API token (V2)",+ type=SourceFieldInputConfigType.PASSWORD,+ required=True,+ placeholder="",+ secret=True,+ ),+ ],+ ),+ )++ def get_schemas(+ self,+ config: AppsFlyerSourceConfig,+ team_id: int,+ with_counts: bool = False,+ names: list[str] | None = None,+ force_refresh: bool = False,+ ) -> list[SourceSchema]:+ schemas = [+ SourceSchema(+ name=endpoint,+ supports_incremental=INCREMENTAL_FIELDS.get(endpoint) is not None,+ supports_append=INCREMENTAL_FIELDS.get(endpoint) is not None,+ incremental_fields=INCREMENTAL_FIELDS.get(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: AppsFlyerSourceConfig, team_id: int, schema_name: Optional[str] = None+ ) -> tuple[bool, str | None]:+ try:+ if validate_appsflyer_credentials(config.api_token, config.app_id):+ return True, None+ except (AppsFlyerRetryableError, requests.RequestException):+ # A rate-limit, 5xx, or network blip isn't a bad credential — don't mislabel it.+ return (+ False,+ "Could not reach AppsFlyer to validate credentials. This may be a temporary rate-limit or network issue — please try again.",+ )++ return False, "Invalid AppsFlyer API token or app id"++ def source_for_pipeline(self, config: AppsFlyerSourceConfig, inputs: SourceInputs) -> SourceResponse:+ return appsflyer_source(+ api_token=config.api_token,+ app_id=config.app_id,+ endpoint=inputs.schema_name,+ logger=inputs.logger,+ 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/posthog/temporal/data_imports/sources/appsflyer/tests/test_appsflyer.py b/posthog/temporal/data_imports/sources/appsflyer/tests/test_appsflyer.pynew file mode 100644index 000000000000..95bd97a108a3--- /dev/null+++ b/posthog/temporal/data_imports/sources/appsflyer/tests/test_appsflyer.py@@ -0,0 +1,188 @@+from datetime import UTC, date, datetime+from urllib.parse import parse_qs, urlparse++import pytest+from unittest import mock++from posthog.temporal.data_imports.sources.appsflyer.appsflyer import (+ CHUNK_SIZE,+ LOOKBACK_DAYS,+ MAX_WINDOW_DAYS,+ AppsFlyerRetryableError,+ _normalize_header,+ _parse_csv_rows,+ _to_date,+ _validate_app_id,+ appsflyer_source,+ get_rows,+ validate_credentials,+)+from posthog.temporal.data_imports.sources.appsflyer.settings import APPSFLYER_ENDPOINTS, ENDPOINTS++_MODULE = "posthog.temporal.data_imports.sources.appsflyer.appsflyer"++_CSV = (+ "Date,Agency/PMD (af_prt),Media Source (pid),Campaign (c),Impressions,Clicks\n"+ "2024-01-01,agency,google,brand,100,10\n"+ "2024-01-02,agency,meta,retargeting,200,20\n"+)+++def _response(text: str, status: int = 200) -> mock.MagicMock:+ resp = mock.MagicMock()+ resp.text = text+ resp.status_code = status+ resp.ok = status < 400+ return resp+++class TestHelpers:+ @pytest.mark.parametrize(+ "header, expected",+ [+ ("Date", "date"),+ ("Media Source (pid)", "media_source_pid"),+ ("Agency/PMD (af_prt)", "agency_pmd_af_prt"),+ ("Campaign (c)", "campaign_c"),+ ("Click-Through Rate", "click_through_rate"),+ ],+ )+ def test_normalize_header(self, header, expected):+ assert _normalize_header(header) == expected++ def test_parse_csv_rows(self):+ rows = list(_parse_csv_rows(_CSV))+ assert rows[0]["date"] == "2024-01-01"+ assert rows[0]["media_source_pid"] == "google"+ assert rows[1]["campaign_c"] == "retargeting"++ def test_parse_csv_skips_blank_lines(self):+ rows = list(_parse_csv_rows(_CSV + ",,,,,\n"))+ assert len(rows) == 2++ def test_parse_csv_skips_rows_with_mismatched_length(self):+ # A short row would let zip silently drop primary-key columns; it must be skipped.+ logger = mock.MagicMock()+ rows = list(_parse_csv_rows(_CSV + "2024-01-03,agency,google\n", logger))+ assert len(rows) == 2+ logger.warning.assert_called_once()++ @pytest.mark.parametrize(+ "value, expected",+ [+ ("2024-01-02", date(2024, 1, 2)),+ ("2024-01-02T03:04:05Z", date(2024, 1, 2)),+ (date(2024, 1, 2), date(2024, 1, 2)),+ (datetime(2024, 1, 2, 3, tzinfo=UTC), date(2024, 1, 2)),+ ],+ )+ def test_to_date(self, value, expected):+ assert _to_date(value) == expected++ @pytest.mark.parametrize("value", ["", "bad app", "app?id"])+ def test_invalid_app_ids_raise(self, value):+ with pytest.raises(ValueError):+ _validate_app_id(value)+++class TestValidateCredentials:+ @pytest.mark.parametrize(+ "status_code, expected",+ [+ (200, True),+ (401, False),+ (403, False),+ (404, False),+ ],+ )+ @mock.patch(f"{_MODULE}.make_tracked_session")+ def test_validate_credentials_status_mapping(self, mock_session, status_code, expected):+ mock_session.return_value.get.return_value = _response("", status=status_code)++ assert validate_credentials("token", "id123") is expected++ @mock.patch(f"{_MODULE}.make_tracked_session")+ def test_validate_rejects_bad_app_id_without_request(self, mock_session):+ assert validate_credentials("token", "bad app!") is False+ mock_session.return_value.get.assert_not_called()++ @pytest.mark.parametrize("status_code", [429, 500, 503])+ @mock.patch(f"{_MODULE}.make_tracked_session")+ def test_validate_raises_on_transient_status(self, mock_session, status_code):+ # Rate-limit / 5xx are transient; the caller must be able to tell them from a bad token.+ mock_session.return_value.get.return_value = _response("", status=status_code)++ with pytest.raises(AppsFlyerRetryableError):+ validate_credentials("token", "id123")+++class TestGetRows:+ @mock.patch(f"{_MODULE}.make_tracked_session")+ def test_full_pull_uses_max_window(self, mock_session):+ mock_session.return_value.get.return_value = _response(_CSV)++ batches = list(get_rows("token", "id123", "daily_report", mock.MagicMock()))++ flat = [row for batch in batches for row in batch]+ assert len(flat) == 2+ url = mock_session.return_value.get.call_args.args[0]+ query = parse_qs(urlparse(url).query)+ window = date.fromisoformat(query["to"][0]) - date.fromisoformat(query["from"][0])+ assert window.days == MAX_WINDOW_DAYS+ assert urlparse(url).path == "/api/agg-data/export/app/id123/dailyreport/v5"++ @mock.patch(f"{_MODULE}.make_tracked_session")+ def test_incremental_starts_at_watermark_minus_lookback(self, mock_session):+ mock_session.return_value.get.return_value = _response(_CSV)+ watermark = datetime.now(UTC).date()++ list(+ get_rows(+ "token",+ "id123",+ "daily_report",+ mock.MagicMock(),+ should_use_incremental_field=True,+ db_incremental_field_last_value=watermark,+ )+ )++ url = mock_session.return_value.get.call_args.args[0]+ query = parse_qs(urlparse(url).query)+ expected_from = watermark.toordinal() - LOOKBACK_DAYS+ assert date.fromisoformat(query["from"][0]).toordinal() == expected_from++ @mock.patch(f"{_MODULE}.make_tracked_session")+ def test_rows_are_chunked(self, mock_session):+ header = "Date,Agency/PMD (af_prt),Media Source (pid),Campaign (c)\n"+ body = "".join(f"2024-01-01,a,m,c{i}\n" for i in range(CHUNK_SIZE + 1))+ mock_session.return_value.get.return_value = _response(header + body)++ batches = list(get_rows("token", "id123", "daily_report", mock.MagicMock()))++ assert [len(batch) for batch in batches] == [CHUNK_SIZE, 1]++ @mock.patch(f"{_MODULE}.make_tracked_session")+ def test_empty_report_yields_nothing(self, mock_session):+ mock_session.return_value.get.return_value = _response("Date,Media Source (pid)\n")++ assert list(get_rows("token", "id123", "daily_report", mock.MagicMock())) == []+++class TestAppsFlyerSourceResponse:+ @pytest.mark.parametrize("endpoint", list(ENDPOINTS))+ def test_response_metadata_per_endpoint(self, endpoint):+ config = APPSFLYER_ENDPOINTS[endpoint]+ response = appsflyer_source("token", "id123", endpoint, mock.MagicMock())++ assert response.name == endpoint+ assert response.primary_keys == config.primary_keys+ assert response.sort_mode == "asc"+ assert response.partition_mode == "datetime"+ assert response.partition_keys == ["date"]+ # Dimension keys can collide (blank campaigns etc).+ assert response.has_duplicate_primary_keys is True++ def test_geo_report_key_includes_country(self):+ response = appsflyer_source("token", "id123", "geo_report", mock.MagicMock())+ assert "country" in (response.primary_keys or [])diff --git a/posthog/temporal/data_imports/sources/appsflyer/tests/test_appsflyer_source.py b/posthog/temporal/data_imports/sources/appsflyer/tests/test_appsflyer_source.pynew file mode 100644index 000000000000..f855e0429781--- /dev/null+++ b/posthog/temporal/data_imports/sources/appsflyer/tests/test_appsflyer_source.py@@ -0,0 +1,150 @@+import pytest+from unittest import mock++import requests++from posthog.schema import ReleaseStatus, SourceFieldInputConfig, SourceFieldInputConfigType++from posthog.temporal.data_imports.sources.appsflyer.appsflyer import AppsFlyerRetryableError+from posthog.temporal.data_imports.sources.appsflyer.settings import ENDPOINTS, INCREMENTAL_FIELDS+from posthog.temporal.data_imports.sources.appsflyer.source import AppsFlyerSource+from posthog.temporal.data_imports.sources.generated_configs import AppsFlyerSourceConfig++from products.data_warehouse.backend.types import ExternalDataSourceType+++class TestAppsFlyerSource:+ def setup_method(self):+ self.source = AppsFlyerSource()+ self.team_id = 123+ self.config = AppsFlyerSourceConfig(app_id="id123", api_token="token")++ def test_source_type(self):+ assert self.source.source_type == ExternalDataSourceType.APPSFLYER++ def test_connection_host_fields_includes_app_id(self):+ # Changing app_id retargets the stored token, so editing it must require re-entering secrets.+ assert self.source.connection_host_fields == ["app_id"]++ def test_get_source_config(self):+ config = self.source.get_source_config++ assert config.name.value == "AppsFlyer"+ assert config.label == "AppsFlyer"+ assert config.releaseStatus == ReleaseStatus.ALPHA+ assert config.unreleasedSource is None+ assert config.iconPath == "/static/services/appsflyer.png"++ field_names = [f.name for f in config.fields if isinstance(f, SourceFieldInputConfig)]+ assert field_names == ["app_id", "api_token"]++ def test_api_token_field_is_secret_password(self):+ config = self.source.get_source_config+ token_field = next(f for f in config.fields if isinstance(f, SourceFieldInputConfig) and f.name == "api_token")+ assert token_field.type == SourceFieldInputConfigType.PASSWORD+ assert token_field.secret is True+ assert token_field.required is True++ @pytest.mark.parametrize(+ "observed_error",+ [+ "401 Client Error: Unauthorized for url: https://hq1.appsflyer.com/api/agg-data/export/app/id123/dailyreport/v5",+ "403 Client Error: Forbidden for url: https://hq1.appsflyer.com/api/agg-data/export/app/id123/geo_by_date_report/v5",+ "404 Client Error: Not Found for url: https://hq1.appsflyer.com/api/agg-data/export/app/nope/dailyreport/v5",+ ],+ )+ def test_non_retryable_errors_match_auth_failures(self, observed_error):+ non_retryable_errors = self.source.get_non_retryable_errors()+ assert any(key in observed_error for key in non_retryable_errors)++ @pytest.mark.parametrize(+ "other_vendor_error",+ [+ "401 Client Error: Unauthorized for url: https://api.stripe.com/v1/customers",+ "500 Server Error for url: https://hq1.appsflyer.com/api/agg-data/export/app/id123/dailyreport/v5",+ ],+ )+ def test_non_retryable_errors_does_not_match_unrelated(self, other_vendor_error):+ non_retryable_errors = self.source.get_non_retryable_errors()+ assert not any(key in other_vendor_error for key in non_retryable_errors)++ def test_get_schemas(self):+ schemas = self.source.get_schemas(self.config, self.team_id)++ assert {schema.name for schema in schemas} == set(ENDPOINTS)+ # Every aggregate report takes a server-side from/to date window.+ assert all(schema.supports_incremental for schema in schemas)+ assert all(schema.supports_append for schema in schemas)++ def test_schemas_advertise_date_cursor(self):+ schemas = {schema.name: schema for schema in self.source.get_schemas(self.config, self.team_id)}++ assert schemas["daily_report"].incremental_fields == INCREMENTAL_FIELDS["daily_report"]+ assert [f["field"] for f in schemas["daily_report"].incremental_fields] == ["date"]++ def test_get_schemas_filtered_by_names(self):+ schemas = self.source.get_schemas(self.config, self.team_id, names=["daily_report"])+ assert len(schemas) == 1+ assert schemas[0].name == "daily_report"++ 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(+ "mock_return, expected_valid, expected_message",+ [+ (True, True, None),+ (False, False, "Invalid AppsFlyer API token or app id"),+ ],+ )+ @mock.patch("posthog.temporal.data_imports.sources.appsflyer.source.validate_appsflyer_credentials")+ def test_validate_credentials(self, mock_validate, mock_return, expected_valid, expected_message):+ mock_validate.return_value = mock_return++ is_valid, error_message = self.source.validate_credentials(self.config, self.team_id)++ assert is_valid is expected_valid+ assert error_message == expected_message+ mock_validate.assert_called_once_with("token", "id123")++ @pytest.mark.parametrize(+ "raised",+ [AppsFlyerRetryableError("status=429"), requests.ConnectionError(), requests.ReadTimeout()],+ )+ @mock.patch("posthog.temporal.data_imports.sources.appsflyer.source.validate_appsflyer_credentials")+ def test_validate_credentials_reports_transient_failures_distinctly(self, mock_validate, raised):+ mock_validate.side_effect = raised++ is_valid, error_message = self.source.validate_credentials(self.config, self.team_id)++ assert is_valid is False+ assert error_message is not None+ assert "temporary" in error_message++ @mock.patch("posthog.temporal.data_imports.sources.appsflyer.source.appsflyer_source")+ def test_source_for_pipeline_plumbs_arguments(self, mock_af_source):+ inputs = mock.MagicMock()+ inputs.schema_name = "daily_report"+ inputs.should_use_incremental_field = True+ inputs.db_incremental_field_last_value = "2024-05-01"++ self.source.source_for_pipeline(self.config, inputs)++ mock_af_source.assert_called_once()+ kwargs = mock_af_source.call_args.kwargs+ assert kwargs["api_token"] == "token"+ assert kwargs["app_id"] == "id123"+ assert kwargs["endpoint"] == "daily_report"+ assert kwargs["should_use_incremental_field"] is True+ assert kwargs["db_incremental_field_last_value"] == "2024-05-01"++ @mock.patch("posthog.temporal.data_imports.sources.appsflyer.source.appsflyer_source")+ def test_source_for_pipeline_omits_last_value_on_full_refresh(self, mock_af_source):+ inputs = mock.MagicMock()+ inputs.schema_name = "daily_report"+ inputs.should_use_incremental_field = False+ inputs.db_incremental_field_last_value = "2024-05-01"++ self.source.source_for_pipeline(self.config, inputs)++ assert mock_af_source.call_args.kwargs["db_incremental_field_last_value"] is Nonediff --git a/posthog/temporal/data_imports/sources/generated_configs.py b/posthog/temporal/data_imports/sources/generated_configs.pyindex cb6a1bcf80d2..b3949fb4835c 100644--- a/posthog/temporal/data_imports/sources/generated_configs.py+++ b/posthog/temporal/data_imports/sources/generated_configs.py@@ -189,7 +189,8 @@ class AppleSearchAdsSourceConfig(config.Config):@config.configclass AppsFlyerSourceConfig(config.Config):- pass+ app_id: str+ api_token: str@config.config