: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 amazon ads import source (#62960)
Tom Owersdfdab064f36f
diff --git a/posthog/temporal/data_imports/sources/SOURCES.md b/posthog/temporal/data_imports/sources/SOURCES.mdindex 8ae55ca505dd..a72ec1590906 100644--- a/posthog/temporal/data_imports/sources/SOURCES.md+++ b/posthog/temporal/data_imports/sources/SOURCES.md@@ -47,6 +47,7 @@ the row lists both.| adroll | HTTP | requests | ✅ || aircall | HTTP | requests | ✅ || airtable | HTTP | requests | ✅ |+| amazon_ads | HTTP | requests | ✅ || amplitude | HTTP | requests | ✅ || appsflyer | HTTP (CSV reports) | requests | ✅ || asana | HTTP | requests | ✅ |@@ -213,7 +214,6 @@ doesn't conflict with concurrent PRs.- adobe_commerce- adp_workforce_now- adyen-- amazon_ads- amazon_s3- amazon_selling_partner- apollodiff --git a/posthog/temporal/data_imports/sources/amazon_ads/amazon_ads.py b/posthog/temporal/data_imports/sources/amazon_ads/amazon_ads.pynew file mode 100644index 000000000000..152534fc36c3--- /dev/null+++ b/posthog/temporal/data_imports/sources/amazon_ads/amazon_ads.py@@ -0,0 +1,179 @@+from collections.abc import Iterator+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 posthog.temporal.data_imports.pipelines.pipeline.typings import SourceResponse+from posthog.temporal.data_imports.sources.amazon_ads.settings import AMAZON_ADS_ENDPOINTS+from posthog.temporal.data_imports.sources.common.http import make_tracked_session++AMAZON_ADS_HOSTS = {+ "na": "https://advertising-api.amazon.com",+ "eu": "https://advertising-api-eu.amazon.com",+ "fe": "https://advertising-api-fe.amazon.com",+}+# Login with Amazon token endpoint is global.+LWA_TOKEN_URL = "https://api.amazon.com/auth/o2/token"+PAGE_SIZE = 500+REQUEST_TIMEOUT_SECONDS = 120+MAX_RETRY_ATTEMPTS = 5+++class AmazonAdsRetryableError(Exception):+ pass+++def _get_session(client_secret: str, refresh_token: str, client_id: str) -> requests.Session:+ return make_tracked_session(+ headers={"Amazon-Advertising-API-ClientId": client_id},+ redact_values=(client_secret, refresh_token),+ )+++def _base_url(region: str) -> str:+ host = AMAZON_ADS_HOSTS.get(region)+ if host is None:+ raise ValueError(f"Invalid Amazon Ads region: {region}")+ return host+++def _mint_token(session: requests.Session, client_id: str, client_secret: str, refresh_token: str) -> str:+ """Exchange the LWA refresh token for a ~1h access token."""+ response = session.post(+ LWA_TOKEN_URL,+ data={+ "grant_type": "refresh_token",+ "refresh_token": refresh_token,+ "client_id": client_id,+ "client_secret": client_secret,+ },+ timeout=REQUEST_TIMEOUT_SECONDS,+ )+ response.raise_for_status()+ return response.json()["access_token"]+++def validate_credentials(region: str, client_id: str, client_secret: str, refresh_token: str) -> bool:+ """Confirm the LWA credentials are valid by minting a token and listing profiles."""+ try:+ _base_url(region)+ session = _get_session(client_secret, refresh_token, client_id)+ token = _mint_token(session, client_id, client_secret, refresh_token)+ response = session.get(+ f"{_base_url(region)}/v2/profiles",+ headers={"Authorization": f"Bearer {token}"},+ timeout=15,+ )+ return response.status_code == 200+ except Exception:+ return False+++def get_rows(+ region: str,+ client_id: str,+ client_secret: str,+ refresh_token: str,+ endpoint: str,+ logger: FilteringBoundLogger,+) -> Iterator[list[dict[str, Any]]]:+ config = AMAZON_ADS_ENDPOINTS[endpoint]+ session = _get_session(client_secret, refresh_token, client_id)+ base_url = _base_url(region)+ token = _mint_token(session, client_id, client_secret, refresh_token)++ @retry(+ retry=retry_if_exception_type((AmazonAdsRetryableError, requests.ReadTimeout, requests.ConnectionError)),+ stop=stop_after_attempt(MAX_RETRY_ATTEMPTS),+ wait=wait_exponential_jitter(initial=2, max=120),+ reraise=True,+ )+ def request(+ method: str, path: str, profile_id: Optional[str] = None, body: Optional[dict[str, Any]] = None+ ) -> requests.Response:+ nonlocal token+ url = f"{base_url}{path}"++ def _do() -> requests.Response:+ headers: dict[str, str] = {"Authorization": f"Bearer {token}"}+ if profile_id is not None:+ headers["Amazon-Advertising-API-Scope"] = profile_id+ if config.media_type is not None and method == "POST":+ headers["Content-Type"] = config.media_type+ headers["Accept"] = config.media_type+ if method == "POST":+ return session.post(url, json=body or {}, headers=headers, timeout=REQUEST_TIMEOUT_SECONDS)+ return session.get(url, headers=headers, timeout=REQUEST_TIMEOUT_SECONDS)++ response = _do()+ # Access tokens last ~1h; re-mint once if the sync outlives one.+ if response.status_code == 401:+ token = _mint_token(session, client_id, client_secret, refresh_token)+ response = _do()++ if response.status_code == 429 or response.status_code >= 500:+ raise AmazonAdsRetryableError(f"Amazon Ads API error (retryable): status={response.status_code}, url={url}")++ if not response.ok:+ logger.error(f"Amazon Ads API error: status={response.status_code}, body={response.text}, url={url}")+ response.raise_for_status()++ return response++ def list_profiles() -> list[dict[str, Any]]:+ body = request("GET", "/v2/profiles").json()+ return body if isinstance(body, list) else []++ if endpoint == "profiles":+ profiles = list_profiles()+ if profiles:+ yield profiles+ return++ # Sponsored Products v3 list endpoints, fanned out per profile.+ profile_ids = [str(profile["profileId"]) for profile in list_profiles()]++ for profile_id in profile_ids:+ next_token: Optional[str] = None+ while True:+ body: dict[str, Any] = {"maxResults": PAGE_SIZE}+ if next_token:+ body["nextToken"] = next_token+ data = request("POST", config.path, profile_id=profile_id, body=body).json()+ items = [{**item, "_profile_id": profile_id} for item in (data.get(config.data_key, []) or [])]++ if items:+ yield items++ next_token = data.get("nextToken")+ if not next_token or not items:+ break+++def amazon_ads_source(+ region: str,+ client_id: str,+ client_secret: str,+ refresh_token: str,+ endpoint: str,+ logger: FilteringBoundLogger,+) -> SourceResponse:+ config = AMAZON_ADS_ENDPOINTS[endpoint]++ return SourceResponse(+ name=endpoint,+ items=lambda: get_rows(+ region=region,+ client_id=client_id,+ client_secret=client_secret,+ refresh_token=refresh_token,+ endpoint=endpoint,+ logger=logger,+ ),+ primary_keys=[config.primary_key],+ partition_count=1,+ partition_size=1,+ sort_mode="asc",+ )diff --git a/posthog/temporal/data_imports/sources/amazon_ads/settings.py b/posthog/temporal/data_imports/sources/amazon_ads/settings.pynew file mode 100644index 000000000000..a116975b4e52--- /dev/null+++ b/posthog/temporal/data_imports/sources/amazon_ads/settings.py@@ -0,0 +1,46 @@+from dataclasses import dataclass+from typing import Optional+++@dataclass+class AmazonAdsEndpointConfig:+ name: str+ # Path under the regional advertising host.+ path: str+ primary_key: str+ # Sponsored Products v3 list endpoints are POSTs with vendor media types+ # and are scoped to a profile via the Amazon-Advertising-API-Scope header.+ profile_scoped: bool = False+ media_type: Optional[str] = None+ # Key the rows live under in the response body (None = bare array).+ data_key: Optional[str] = None+++# Entity lists only — Amazon Ads performance metrics ship via the async+# reporting API (create report → poll → download gzip), a follow-up. Entity+# endpoints have no updated-since filter, so every stream is a full refresh.+AMAZON_ADS_ENDPOINTS: dict[str, AmazonAdsEndpointConfig] = {+ "profiles": AmazonAdsEndpointConfig(+ name="profiles",+ path="/v2/profiles",+ primary_key="profileId",+ ),+ "sp_campaigns": AmazonAdsEndpointConfig(+ name="sp_campaigns",+ path="/sp/campaigns/list",+ primary_key="campaignId",+ profile_scoped=True,+ media_type="application/vnd.spCampaign.v3+json",+ data_key="campaigns",+ ),+ "sp_ad_groups": AmazonAdsEndpointConfig(+ name="sp_ad_groups",+ path="/sp/adGroups/list",+ primary_key="adGroupId",+ profile_scoped=True,+ media_type="application/vnd.spAdGroup.v3+json",+ data_key="adGroups",+ ),+}++ENDPOINTS = tuple(AMAZON_ADS_ENDPOINTS.keys())diff --git a/posthog/temporal/data_imports/sources/amazon_ads/source.py b/posthog/temporal/data_imports/sources/amazon_ads/source.pyindex 22eaa7bdaf5c..1b643b0e72c8 100644--- a/posthog/temporal/data_imports/sources/amazon_ads/source.py+++ b/posthog/temporal/data_imports/sources/amazon_ads/source.py@@ -1,12 +1,24 @@-from typing import cast+from typing import Optional, castfrom posthog.schema import (ExternalDataSourceType as SchemaExternalDataSourceType,+ ReleaseStatus,SourceConfig,+ SourceFieldInputConfig,+ SourceFieldInputConfigType,+ SourceFieldSelectConfig,+ SourceFieldSelectConfigOption,)+from posthog.temporal.data_imports.pipelines.pipeline.typings import SourceInputs, SourceResponse+from posthog.temporal.data_imports.sources.amazon_ads.amazon_ads import (+ amazon_ads_source,+ validate_credentials as validate_amazon_ads_credentials,+)+from posthog.temporal.data_imports.sources.amazon_ads.settings import ENDPOINTSfrom 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 AmazonAdsSourceConfigfrom products.data_warehouse.backend.types import ExternalDataSourceType@@ -18,12 +30,106 @@ class AmazonAdsSource(SimpleSource[AmazonAdsSourceConfig]):def source_type(self) -> ExternalDataSourceType:return ExternalDataSourceType.AMAZONADS+ def get_non_retryable_errors(self) -> dict[str, str | None]:+ return {+ "400 Client Error: Bad Request for url: https://api.amazon.com/auth/o2/token": "Amazon Ads authentication failed. Your refresh token may be invalid or revoked — please check your Login with Amazon credentials.",+ "401 Client Error: Unauthorized for url: https://api.amazon.com/auth/o2/token": "Amazon Ads authentication failed. Please check your Login with Amazon client ID and secret.",+ "403 Client Error: Forbidden for url: https://advertising-api": "Amazon Ads denied access. Please check that your Login with Amazon application has Advertising API access and the right region.",+ }+@propertydef get_source_config(self) -> SourceConfig:return SourceConfig(name=SchemaExternalDataSourceType.AMAZON_ADS,label="Amazon Ads",+ caption="""Connect your Amazon Ads account to pull your advertising entity data into the PostHog Data warehouse.++You need a Login with Amazon (LWA) application with Advertising API access: enter its client ID and secret plus a refresh token authorized for your advertiser account. Pick the region that matches your advertising profiles (North America, Europe, or Far East). Sponsored Products campaigns and ad groups are synced from every profile the token can access.""",iconPath="/static/services/amazon_ads.png",- fields=cast(list[FieldType], []),- unreleasedSource=True,+ docsUrl="https://posthog.com/docs/cdp/sources/amazon-ads",+ releaseStatus=ReleaseStatus.ALPHA,+ fields=cast(+ list[FieldType],+ [+ SourceFieldSelectConfig(+ name="region",+ label="Region",+ required=True,+ defaultValue="na",+ options=[+ SourceFieldSelectConfigOption(label="North America", value="na"),+ SourceFieldSelectConfigOption(label="Europe", value="eu"),+ SourceFieldSelectConfigOption(label="Far East", value="fe"),+ ],+ ),+ SourceFieldInputConfig(+ name="client_id",+ label="LWA client ID",+ type=SourceFieldInputConfigType.TEXT,+ required=True,+ placeholder="amzn1.application-oa2-client...",+ secret=False,+ ),+ SourceFieldInputConfig(+ name="client_secret",+ label="LWA client secret",+ type=SourceFieldInputConfigType.PASSWORD,+ required=True,+ placeholder="",+ secret=True,+ ),+ SourceFieldInputConfig(+ name="refresh_token",+ label="Refresh token",+ type=SourceFieldInputConfigType.PASSWORD,+ required=True,+ placeholder="Atzr|...",+ secret=True,+ ),+ ],+ ),+ )++ def get_schemas(+ self,+ config: AmazonAdsSourceConfig,+ team_id: int,+ with_counts: bool = False,+ names: list[str] | None = None,+ force_refresh: bool = False,+ ) -> list[SourceSchema]:+ # Entity lists have no updated-since filter; performance metrics ship+ # via the async reporting API (a follow-up).+ schemas = [+ SourceSchema(+ name=endpoint,+ supports_incremental=False,+ supports_append=False,+ incremental_fields=[],+ )+ 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: AmazonAdsSourceConfig, team_id: int, schema_name: Optional[str] = None+ ) -> tuple[bool, str | None]:+ if validate_amazon_ads_credentials(config.region, config.client_id, config.client_secret, config.refresh_token):+ return True, None++ return False, "Invalid Amazon Ads credentials"++ def source_for_pipeline(self, config: AmazonAdsSourceConfig, inputs: SourceInputs) -> SourceResponse:+ return amazon_ads_source(+ region=config.region,+ client_id=config.client_id,+ client_secret=config.client_secret,+ refresh_token=config.refresh_token,+ endpoint=inputs.schema_name,+ logger=inputs.logger,)diff --git a/posthog/temporal/data_imports/sources/amazon_ads/tests/test_amazon_ads.py b/posthog/temporal/data_imports/sources/amazon_ads/tests/test_amazon_ads.pynew file mode 100644index 000000000000..a944b958b134--- /dev/null+++ b/posthog/temporal/data_imports/sources/amazon_ads/tests/test_amazon_ads.py@@ -0,0 +1,148 @@+from typing import Any+from urllib.parse import urlparse++import pytest+from unittest import mock++import requests++from posthog.temporal.data_imports.sources.amazon_ads.amazon_ads import (+ PAGE_SIZE,+ _base_url,+ amazon_ads_source,+ get_rows,+ validate_credentials,+)+from posthog.temporal.data_imports.sources.amazon_ads.settings import AMAZON_ADS_ENDPOINTS, ENDPOINTS++_MODULE = "posthog.temporal.data_imports.sources.amazon_ads.amazon_ads"+++def _token_response() -> mock.MagicMock:+ resp = mock.MagicMock()+ resp.json.return_value = {"access_token": "the-token", "expires_in": 3600}+ resp.status_code = 200+ resp.ok = True+ return resp+++def _json_response(body: Any) -> mock.MagicMock:+ resp = mock.MagicMock()+ resp.json.return_value = body+ resp.status_code = 200+ resp.ok = True+ return resp+++class TestBaseUrl:+ @pytest.mark.parametrize(+ "region, expected_host",+ [+ ("na", "https://advertising-api.amazon.com"),+ ("eu", "https://advertising-api-eu.amazon.com"),+ ("fe", "https://advertising-api-fe.amazon.com"),+ ],+ )+ def test_regional_hosts(self, region, expected_host):+ assert _base_url(region) == expected_host++ def test_invalid_region_raises(self):+ with pytest.raises(ValueError):+ _base_url("evil")+++class TestValidateCredentials:+ @mock.patch(f"{_MODULE}.make_tracked_session")+ def test_valid_when_token_mints_and_profiles_list(self, mock_session):+ mock_session.return_value.post.return_value = _token_response()+ mock_session.return_value.get.return_value = _json_response([{"profileId": 1}])++ assert validate_credentials("na", "cid", "sec", "rt") is True++ @mock.patch(f"{_MODULE}.make_tracked_session")+ def test_invalid_when_token_mint_fails(self, mock_session):+ resp = mock.MagicMock()+ resp.raise_for_status.side_effect = requests.HTTPError("400 Client Error", response=mock.MagicMock())+ mock_session.return_value.post.return_value = resp++ assert validate_credentials("na", "cid", "sec", "rt") is False++ @mock.patch(f"{_MODULE}.make_tracked_session")+ def test_invalid_when_profiles_forbidden(self, mock_session):+ mock_session.return_value.post.return_value = _token_response()+ forbidden = mock.MagicMock()+ forbidden.status_code = 403+ mock_session.return_value.get.return_value = forbidden++ assert validate_credentials("na", "cid", "sec", "rt") is False++ @mock.patch(f"{_MODULE}.make_tracked_session")+ def test_invalid_region_rejected_without_request(self, mock_session):+ assert validate_credentials("evil", "cid", "sec", "rt") is False+ mock_session.return_value.post.assert_not_called()+++class TestGetRows:+ @mock.patch(f"{_MODULE}.make_tracked_session")+ def test_profiles_single_fetch(self, mock_session):+ mock_session.return_value.post.return_value = _token_response()+ mock_session.return_value.get.return_value = _json_response([{"profileId": 1}, {"profileId": 2}])++ batches = list(get_rows("na", "cid", "sec", "rt", "profiles", mock.MagicMock()))++ assert batches == [[{"profileId": 1}, {"profileId": 2}]]++ @mock.patch(f"{_MODULE}.make_tracked_session")+ def test_sp_campaigns_fan_out_per_profile_with_scope_header(self, mock_session):+ mock_session.return_value.post.side_effect = [+ _token_response(),+ _json_response({"campaigns": [{"campaignId": 11}], "nextToken": "tok"}),+ _json_response({"campaigns": [{"campaignId": 12}]}),+ ]+ mock_session.return_value.get.return_value = _json_response([{"profileId": 1}])++ batches = list(get_rows("na", "cid", "sec", "rt", "sp_campaigns", mock.MagicMock()))++ flat = [item for batch in batches for item in batch]+ assert [(c["campaignId"], c["_profile_id"]) for c in flat] == [(11, "1"), (12, "1")]+ first_list_call = mock_session.return_value.post.call_args_list[1]+ assert urlparse(first_list_call.args[0]).path == "/sp/campaigns/list"+ assert first_list_call.kwargs["headers"]["Amazon-Advertising-API-Scope"] == "1"+ assert first_list_call.kwargs["headers"]["Content-Type"] == "application/vnd.spCampaign.v3+json"+ assert first_list_call.kwargs["json"] == {"maxResults": PAGE_SIZE}+ second_list_call = mock_session.return_value.post.call_args_list[2]+ assert second_list_call.kwargs["json"] == {"maxResults": PAGE_SIZE, "nextToken": "tok"}++ @mock.patch(f"{_MODULE}.make_tracked_session")+ def test_remints_token_on_401(self, mock_session):+ expired = mock.MagicMock()+ expired.status_code = 401+ expired.ok = False+ mock_session.return_value.post.return_value = _token_response()+ mock_session.return_value.get.side_effect = [expired, _json_response([{"profileId": 1}])]++ batches = list(get_rows("na", "cid", "sec", "rt", "profiles", mock.MagicMock()))++ assert batches == [[{"profileId": 1}]]+ # One mint at start + one re-mint after the 401.+ assert mock_session.return_value.post.call_count == 2++ @mock.patch(f"{_MODULE}.make_tracked_session")+ def test_no_profiles_yields_nothing(self, mock_session):+ mock_session.return_value.post.return_value = _token_response()+ mock_session.return_value.get.return_value = _json_response([])++ assert list(get_rows("na", "cid", "sec", "rt", "sp_campaigns", mock.MagicMock())) == []+++class TestAmazonAdsSourceResponse:+ @pytest.mark.parametrize("endpoint", list(ENDPOINTS))+ def test_response_metadata_per_endpoint(self, endpoint):+ config = AMAZON_ADS_ENDPOINTS[endpoint]+ response = amazon_ads_source("na", "cid", "sec", "rt", endpoint, mock.MagicMock())++ assert response.name == endpoint+ assert response.primary_keys == [config.primary_key]+ assert response.sort_mode == "asc"+ assert response.partition_mode is None+ assert response.partition_keys is Nonediff --git a/posthog/temporal/data_imports/sources/amazon_ads/tests/test_amazon_ads_source.py b/posthog/temporal/data_imports/sources/amazon_ads/tests/test_amazon_ads_source.pynew file mode 100644index 000000000000..a4b3b32eb69b--- /dev/null+++ b/posthog/temporal/data_imports/sources/amazon_ads/tests/test_amazon_ads_source.py@@ -0,0 +1,120 @@+import pytest+from unittest import mock++from posthog.schema import ReleaseStatus, SourceFieldInputConfig, SourceFieldInputConfigType, SourceFieldSelectConfig++from posthog.temporal.data_imports.sources.amazon_ads.settings import ENDPOINTS+from posthog.temporal.data_imports.sources.amazon_ads.source import AmazonAdsSource+from posthog.temporal.data_imports.sources.generated_configs import AmazonAdsSourceConfig++from products.data_warehouse.backend.types import ExternalDataSourceType+++class TestAmazonAdsSource:+ def setup_method(self):+ self.source = AmazonAdsSource()+ self.team_id = 123+ self.config = AmazonAdsSourceConfig(region="na", client_id="cid", client_secret="sec", refresh_token="rt")++ def test_source_type(self):+ assert self.source.source_type == ExternalDataSourceType.AMAZONADS++ def test_get_source_config(self):+ config = self.source.get_source_config++ assert config.name.value == "AmazonAds"+ assert config.label == "Amazon Ads"+ assert config.releaseStatus == ReleaseStatus.ALPHA+ assert config.unreleasedSource is None+ assert config.iconPath == "/static/services/amazon_ads.png"++ field_names = [f.name for f in config.fields]+ assert field_names == ["region", "client_id", "client_secret", "refresh_token"]++ def test_region_field_is_a_select_with_default(self):+ config = self.source.get_source_config+ region_field = next(f for f in config.fields if f.name == "region")+ assert isinstance(region_field, SourceFieldSelectConfig)+ assert region_field.defaultValue == "na"+ assert {option.value for option in region_field.options} == {"na", "eu", "fe"}++ @pytest.mark.parametrize("field_name", ["client_secret", "refresh_token"])+ def test_secret_fields_are_secret_passwords(self, field_name):+ config = self.source.get_source_config+ secret_field = next(f for f in config.fields if isinstance(f, SourceFieldInputConfig) and f.name == field_name)+ assert secret_field.type == SourceFieldInputConfigType.PASSWORD+ assert secret_field.secret is True+ assert secret_field.required is True++ @pytest.mark.parametrize(+ "observed_error",+ [+ "400 Client Error: Bad Request for url: https://api.amazon.com/auth/o2/token",+ "401 Client Error: Unauthorized for url: https://api.amazon.com/auth/o2/token",+ "403 Client Error: Forbidden for url: https://advertising-api.amazon.com/v2/profiles",+ "403 Client Error: Forbidden for url: https://advertising-api-eu.amazon.com/sp/campaigns/list",+ ],+ )+ 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_error",+ [+ "500 Server Error for url: https://advertising-api.amazon.com/v2/profiles",+ # Mid-sync 401s on the API host are handled by token re-mint.+ "401 Client Error: Unauthorized for url: https://advertising-api.amazon.com/v2/profiles",+ ],+ )+ def test_non_retryable_errors_does_not_match_unrelated(self, other_error):+ non_retryable_errors = self.source.get_non_retryable_errors()+ assert not any(key in other_error for key in non_retryable_errors)++ def test_get_schemas_are_full_refresh_only(self):+ schemas = self.source.get_schemas(self.config, self.team_id)++ assert {schema.name for schema in schemas} == set(ENDPOINTS)+ assert all(not schema.supports_incremental for schema in schemas)+ assert all(not schema.supports_append for schema in schemas)+ assert all(schema.incremental_fields == [] for schema in schemas)++ def test_get_schemas_filtered_by_names(self):+ schemas = self.source.get_schemas(self.config, self.team_id, names=["sp_campaigns"])+ assert len(schemas) == 1+ assert schemas[0].name == "sp_campaigns"++ 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 Amazon Ads credentials"),+ ],+ )+ @mock.patch("posthog.temporal.data_imports.sources.amazon_ads.source.validate_amazon_ads_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("na", "cid", "sec", "rt")++ @mock.patch("posthog.temporal.data_imports.sources.amazon_ads.source.amazon_ads_source")+ def test_source_for_pipeline_plumbs_arguments(self, mock_aa_source):+ inputs = mock.MagicMock()+ inputs.schema_name = "sp_campaigns"++ self.source.source_for_pipeline(self.config, inputs)++ mock_aa_source.assert_called_once()+ kwargs = mock_aa_source.call_args.kwargs+ assert kwargs["region"] == "na"+ assert kwargs["client_id"] == "cid"+ assert kwargs["client_secret"] == "sec"+ assert kwargs["refresh_token"] == "rt"+ assert kwargs["endpoint"] == "sp_campaigns"diff --git a/posthog/temporal/data_imports/sources/generated_configs.py b/posthog/temporal/data_imports/sources/generated_configs.pyindex e8ee76e5992f..3b49759bed39 100644--- a/posthog/temporal/data_imports/sources/generated_configs.py+++ b/posthog/temporal/data_imports/sources/generated_configs.py@@ -157,7 +157,10 @@ class AirtableSourceConfig(config.Config):@config.configclass AmazonAdsSourceConfig(config.Config):- pass+ client_id: str+ client_secret: str+ refresh_token: str+ region: Literal["na", "eu", "fe"] = config.value(default="na")@config.config