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): backend-driven account picker for tiktok ads (#70196)

Javier Bahamondesc3ce0e949d53
diff --git a/posthog/models/integration.py b/posthog/models/integration.py
index 99ad864875f9..3a0f243ece67 100644
--- a/posthog/models/integration.py
+++ b/posthog/models/integration.py
@@ -384,6 +384,9 @@ class Integration(models.Model):
@property
def display_name(self) -> str:
+ if self.kind == "tiktok-ads":
+ # The OAuth id is a list of advertiser ids, so prefer whoever authorized the connection.
+ return self.config.get("user_email") or self.config.get("user_display_name") or self.integration_id
if self.kind in OauthIntegration.supported_kinds:
oauth_config = OauthIntegration.oauth_config_for_kind(self.kind)
return dot_get(self.config, oauth_config.name_path, self.integration_id)
@@ -1169,6 +1172,23 @@ class OauthIntegration:
data = config.pop("data", {})
# Move other data fields to main config for TikTok
config.update(data)
+ # Best-effort: fetch who authorized this, so it isn't listed as a row of advertiser ids.
+ try:
+ user_res = requests.get(
+ "https://business-api.tiktok.com/open_api/v1.3/user/info/",
+ headers={"Access-Token": config["access_token"]},
+ timeout=10,
+ )
+ # TikTok answers 200 even when the call failed; the body `code` (0 = OK) is the outcome.
+ body = user_res.json()
+ if body.get("code") == 0:
+ user = body.get("data") or {}
+ if user.get("email"):
+ config["user_email"] = user["email"]
+ if user.get("display_name"):
+ config["user_display_name"] = user["display_name"]
+ except Exception:
+ logger.warning("Failed to fetch TikTok user info for display name")
sensitive_config: dict = {
"access_token": config.pop("access_token"),
diff --git a/posthog/models/test/test_integration_model.py b/posthog/models/test/test_integration_model.py
index be0d2ad981c9..b581a4a3a0c1 100644
--- a/posthog/models/test/test_integration_model.py
+++ b/posthog/models/test/test_integration_model.py
@@ -2856,6 +2856,31 @@ class TestS3CompatibleIntegrationModel(BaseTest):
S3CompatibleIntegration(integration)
+class TestTikTokAdsIntegrationDisplayName(BaseTest):
+ @parameterized.expand(
+ [
+ (
+ "email_wins_over_display_name",
+ {
+ "advertiser_ids": ["7554133187111469074"],
+ "user_email": "e***[email protected]",
+ "user_display_name": "user1140434302514",
+ },
+ ),
+ ("neither_fetched_falls_back_to_id", {"advertiser_ids": ["7554133187111469074"]}, "7554133187111469074"),
+ ]
+ )
+ def test_display_name_prefers_user_email(self, _name: str, config: dict, expected: str) -> None:
+ integration = Integration.objects.create(
+ team=self.team,
+ kind="tiktok-ads",
+ config=config,
+ integration_id=",".join(config["advertiser_ids"]),
+ )
+ assert integration.display_name == expected
+
+
@override_settings(REDDIT_ADS_CLIENT_ID="reddit-client-id", REDDIT_ADS_CLIENT_SECRET="reddit-client-secret")
class TestRedditAdsIntegrationDisplayName(BaseTest):
@parameterized.expand(
diff --git a/products/data_warehouse/backend/tests/api/test_external_data_source.py b/products/data_warehouse/backend/tests/api/test_external_data_source.py
index 14409ce9f3cf..500b1c73f0d1 100644
--- a/products/data_warehouse/backend/tests/api/test_external_data_source.py
+++ b/products/data_warehouse/backend/tests/api/test_external_data_source.py
@@ -109,6 +109,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.stripe.set
ENDPOINTS as STRIPE_ENDPOINTS,
)
from products.warehouse_sources.backend.temporal.data_imports.sources.stripe.source import StripeSource
+from products.warehouse_sources.backend.temporal.data_imports.sources.tiktok_ads.utils import TikTokAdsAPIError
def _configure_source_mock_versioning(mock_get_source) -> None:
@@ -11520,6 +11521,7 @@ class TestOAuthAccountsEndpoint(APIBaseTest):
)
_REDDIT_ADS_MODULE = "products.warehouse_sources.backend.temporal.data_imports.sources.reddit_ads.source"
_LINKEDIN_MODULE = "products.warehouse_sources.backend.temporal.data_imports.sources.linkedin_ads.source"
+ _TIKTOK_ADS_MODULE = "products.warehouse_sources.backend.temporal.data_imports.sources.tiktok_ads.source"
_SNAPCHAT_MODULE = "products.warehouse_sources.backend.temporal.data_imports.sources.snapchat_ads.source"
_META_ADS_MODULE = "products.warehouse_sources.backend.temporal.data_imports.sources.meta_ads.source"
@@ -11611,6 +11613,91 @@ class TestOAuthAccountsEndpoint(APIBaseTest):
response = self.client.get(self._url("Salesforce", 1))
assert response.status_code == status.HTTP_400_BAD_REQUEST, response.content
+ def _tiktok_integration(self) -> Integration:
+ return Integration.objects.create(
+ team=self.team,
+ kind="tiktok-ads",
+ config={},
+ sensitive_config={"access_token": "token"},
+ integration_id="tiktok_test",
+ created_by=self.user,
+ )
+
+ def test_tiktok_auth_error_returns_actionable_400(self):
+ integration = self._tiktok_integration()
+ error = TikTokAdsAPIError("TikTok advertiser/get failed (40105): invalid", api_code=40105)
+ with patch(f"{self._TIKTOK_ADS_MODULE}.list_advertisers", side_effect=error):
+ response = self.client.get(self._url("TikTokAds", integration.id))
+
+ assert response.status_code == status.HTTP_400_BAD_REQUEST, response.content
+ assert "reconnect" in str(response.json()).lower()
+
+ @parameterized.expand([(40016,), (40100,), (40101,), (40102,), (50000,), (51001,), (60001,)])
+ def test_tiktok_transient_error_returns_actionable_400_not_a_reconnect_prompt(self, api_code: int):
+ # 40100 ("requests made too frequently") used to be classified as an auth error, telling a
+ # throttled team to reconnect a perfectly healthy integration. None of these are credential
+ # problems, and none are our bug — they must not page us, nor prompt a pointless re-OAuth.
+ integration = self._tiktok_integration()
+ error = TikTokAdsAPIError(f"TikTok advertiser/get failed ({api_code}): busy", api_code=api_code)
+ with patch(f"{self._TIKTOK_ADS_MODULE}.list_advertisers", side_effect=error):
+ response = self.client.get(self._url("TikTokAds", integration.id))
+
+ assert response.status_code == status.HTTP_400_BAD_REQUEST, response.content
+ body = str(response.json()).lower()
+ assert "rate-limiting" in body
+ assert "reconnect" not in body
+
+ def test_tiktok_non_auth_api_error_is_not_swallowed(self):
+ integration = self._tiktok_integration()
+ error = TikTokAdsAPIError("TikTok advertiser/get failed (40002): bad request", api_code=40002)
+ with patch(f"{self._TIKTOK_ADS_MODULE}.list_advertisers", side_effect=error):
+ response = self.client.get(self._url("TikTokAds", integration.id))
+
+ assert response.status_code == status.HTTP_500_INTERNAL_SERVER_ERROR, response.content
+
+ def test_tiktok_missing_access_token_returns_actionable_400(self):
+ integration = Integration.objects.create(
+ team=self.team,
+ kind="tiktok-ads",
+ config={},
+ sensitive_config={},
+ integration_id="tiktok_no_token",
+ created_by=self.user,
+ )
+ response = self.client.get(self._url("TikTokAds", integration.id))
+
+ assert response.status_code == status.HTTP_400_BAD_REQUEST, response.content
+ assert "access token" in str(response.json()).lower()
+
+ def test_tiktok_ads_maps_advertisers_to_accounts(self):
+ integration = self._tiktok_integration()
+ advertisers = [
+ {"advertiser_id": "7554133187111469074", "advertiser_name": "Posthog0925"},
+ {"advertiser_id": "7554135782433308688", "advertiser_name": "Posthog Inc"},
+ ]
+ with patch(f"{self._TIKTOK_ADS_MODULE}.list_advertisers", return_value=advertisers):
+ response = self.client.get(self._url("TikTokAds", integration.id))
+
+ assert response.status_code == status.HTTP_200_OK, response.content
+ assert response.json()["accounts"] == [
+ {
+ "value": "7554133187111469074",
+ "display_name": "Posthog0925",
+ "is_primary": False,
+ "badges": [],
+ "group": None,
+ "secondary_text": None,
+ },
+ {
+ "value": "7554135782433308688",
+ "display_name": "Posthog Inc",
+ "is_primary": False,
+ "badges": [],
+ "group": None,
+ "secondary_text": None,
+ },
+ ]
+
def _snapchat_integration(self) -> Integration:
return Integration.objects.create(
team=self.team,
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/tiktok_ads/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/tiktok_ads/source.py
index 984c3d4c569c..0636b473911c 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/tiktok_ads/source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/tiktok_ads/source.py
@@ -1,12 +1,13 @@
from typing import Optional, cast
+from requests.exceptions import HTTPError, RequestException
+
from posthog.schema import (
DataWarehouseSourceCategory,
ExternalDataSourceType as SchemaExternalDataSourceType,
ReleaseStatus,
SourceConfig,
- SourceFieldInputConfig,
- SourceFieldInputConfigType,
+ SourceFieldOauthAccountSelectConfig,
SourceFieldOauthConfig,
SuggestedTable,
)
@@ -25,6 +26,10 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common.bas
from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (
CanonicalDescriptions,
)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.integration_accounts import (
+ IntegrationAccount,
+ IntegrationAccountListingError,
+)
from products.warehouse_sources.backend.temporal.data_imports.sources.common.mixins import OAuthMixin
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
@@ -36,7 +41,12 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.tiktok_ads
tiktok_ads_source,
)
from products.warehouse_sources.backend.temporal.data_imports.sources.tiktok_ads.utils import (
+ TIKTOK_AUTH_ERROR_CODES,
TIKTOK_NON_RETRYABLE_ERROR_PREFIX,
+ TIKTOK_TRANSIENT_ERROR_CODES,
+ TIKTOK_TRANSIENT_ERROR_MESSAGE,
+ TikTokAdsAPIError,
+ list_advertisers,
)
from products.warehouse_sources.backend.types import ExternalDataSourceType
@@ -87,20 +97,19 @@ class TikTokAdsSource(ResumableSource[TikTokAdsSourceConfig, TikTokAdsResumeConf
fields=cast(
list[FieldType],
[
- SourceFieldInputConfig(
- name="advertiser_id",
- label="TikTok Ads Advertiser ID",
- type=SourceFieldInputConfigType.TEXT,
- required=True,
- placeholder="Your TikTok Ads advertiser ID",
- secret=False,
- ),
SourceFieldOauthConfig(
name="tiktok_integration_id",
label="TikTok Ads account",
required=True,
kind="tiktok-ads",
),
+ SourceFieldOauthAccountSelectConfig(
+ name="advertiser_id",
+ label="TikTok Ads Advertiser ID",
+ integrationField="tiktok_integration_id",
+ integrationKind="tiktok-ads",
+ required=True,
+ ),
],
),
suggestedTables=[
@@ -115,6 +124,54 @@ class TikTokAdsSource(ResumableSource[TikTokAdsSourceConfig, TikTokAdsResumeConf
],
)
+ def get_oauth_accounts(
+ self, integration_id: int, team_id: int, search: str | None = None
+ ) -> list[IntegrationAccount]:
+ # A user authorizes few advertisers, so `search` is ignored here and the endpoint filters the list.
+ try:
+ integration = self.get_oauth_integration(integration_id, team_id)
+ except ValueError as e:
+ raise IntegrationAccountListingError(
+ "The linked TikTok Ads integration could not be found. Please reconnect your TikTok Ads integration."
+ ) from e
+
+ # TikTok's token response carries no refresh_token and no expires_in, so the token never
+ # expires from our side and there is nothing to refresh — an absent one means a broken row.
+ if not integration.access_token:
+ raise IntegrationAccountListingError("The TikTok Ads integration has no access token. Please reconnect it.")
+
+ try:
+ advertisers = list_advertisers(integration.access_token)
+ except HTTPError as e:
+ # TikTok's edge (not the API itself) returned a real 429/5xx — transient and TikTok-side.
+ status_code = e.response.status_code if e.response is not None else None
+ if status_code is None or (status_code < 500 and status_code != 429):
+ raise
+ raise IntegrationAccountListingError(TIKTOK_TRANSIENT_ERROR_MESSAGE) from e
+ except RequestException as e:
+ # DNS failure, connection reset, or timeout (no HTTP response at all). These raise a
+ # bare RequestException — not HTTPError — so they'd otherwise escape as a generic 500.
+ # Transient and TikTok/network-side: map to the same actionable "try again" message.
+ raise IntegrationAccountListingError(TIKTOK_TRANSIENT_ERROR_MESSAGE) from e
+ except TikTokAdsAPIError as e:
+ if e.api_code in TIKTOK_AUTH_ERROR_CODES:
+ raise IntegrationAccountListingError(
+ "TikTok rejected the credentials for this integration. Please reconnect your TikTok Ads "
+ "integration and make sure the connected account can access your advertiser accounts."
+ ) from e
+ if e.api_code in TIKTOK_TRANSIENT_ERROR_CODES:
+ raise IntegrationAccountListingError(TIKTOK_TRANSIENT_ERROR_MESSAGE) from e
+ # Not something the user can fix (e.g. app-config mismatch, malformed body) — surface it.
+ raise
+
+ return [
+ IntegrationAccount(
+ value=advertiser["advertiser_id"],
+ display_name=advertiser.get("advertiser_name") or "Unnamed account",
+ )
+ for advertiser in advertisers
+ ]
+
def validate_credentials(
self, config: TikTokAdsSourceConfig, team_id: int, schema_name: Optional[str] = None
) -> tuple[bool, str | None]:
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/tiktok_ads/test/test_tiktok_ads_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/tiktok_ads/test/test_tiktok_ads_source.py
index 20a499daa1ad..b690b5cf9996 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/tiktok_ads/test/test_tiktok_ads_source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/tiktok_ads/test/test_tiktok_ads_source.py
@@ -8,16 +8,27 @@ from unittest.mock import MagicMock, Mock, patch
import structlog
from parameterized import parameterized
+from requests.exceptions import (
+ ConnectionError as RequestsConnectionError,
+ RequestException,
+ Timeout,
+)
from posthog.schema import ReleaseStatus
from posthog.models.integration import Integration
from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import SourceInputs
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.integration_accounts import (
+ IntegrationAccountListingError,
+)
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 TikTokAdsSourceConfig
from products.warehouse_sources.backend.temporal.data_imports.sources.tiktok_ads.source import TikTokAdsSource
-from products.warehouse_sources.backend.temporal.data_imports.sources.tiktok_ads.utils import TikTokAdsPaginator
+from products.warehouse_sources.backend.temporal.data_imports.sources.tiktok_ads.utils import (
+ TIKTOK_TRANSIENT_ERROR_MESSAGE,
+ TikTokAdsPaginator,
+)
from products.warehouse_sources.backend.types import ExternalDataSourceType, IncrementalFieldType
@@ -104,6 +115,26 @@ class TestTikTokAdsSource:
patterns = self.source.get_non_retryable_errors()
assert not any(pattern in error_message for pattern in patterns)
+ @parameterized.expand(
+ [
+ ("connection_reset", RequestsConnectionError("Connection reset by peer")),
+ ("timeout", Timeout("Read timed out")),
+ ("base_request_exception", RequestException("DNS lookup failed")),
+ ]
+ )
+ def test_get_oauth_accounts_maps_transport_failure_to_transient(self, name, exception):
+ """A network failure (DNS/reset/timeout) raises a bare RequestException, not HTTPError,
+ so it must still map to the actionable transient message instead of escaping as a 500."""
+ _MODULE = "products.warehouse_sources.backend.temporal.data_imports.sources.tiktok_ads.source"
+ with (
+ patch.object(self.source, "get_oauth_integration", return_value=self.mock_integration),
+ patch(f"{_MODULE}.list_advertisers", side_effect=exception),
+ ):
+ with pytest.raises(IntegrationAccountListingError) as exc_info:
+ self.source.get_oauth_accounts(self.integration_id, self.team_id)
+
+ assert str(exc_info.value) == TIKTOK_TRANSIENT_ERROR_MESSAGE
+
def test_get_source_config(self):
"""Test source configuration generation."""
config = self.source.get_source_config
@@ -113,14 +144,16 @@ class TestTikTokAdsSource:
assert config.releaseStatus == ReleaseStatus.GA
assert len(config.fields) == 2
- advertiser_field = config.fields[0]
- assert advertiser_field.name == "advertiser_id"
- assert hasattr(advertiser_field, "required") and advertiser_field.required is True
-
- integration_field = config.fields[1]
+ # OAuth field comes first — the account selector below reads from it
+ integration_field = config.fields[0]
assert integration_field.name == "tiktok_integration_id"
assert hasattr(integration_field, "kind") and integration_field.kind == "tiktok-ads"
+ advertiser_field = config.fields[1]
+ assert advertiser_field.name == "advertiser_id"
+ assert hasattr(advertiser_field, "required") and advertiser_field.required is True
+ assert getattr(advertiser_field, "integrationField", None) == "tiktok_integration_id"
+
@parameterized.expand(
[
("missing_advertiser_id", "", 123, False, "Advertiser ID and TikTok Ads integration are required"),
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/tiktok_ads/test/test_tiktok_ads_utils.py b/products/warehouse_sources/backend/temporal/data_imports/sources/tiktok_ads/test/test_tiktok_ads_utils.py
index 0ad0b5445acd..f89e0d16b399 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/tiktok_ads/test/test_tiktok_ads_utils.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/tiktok_ads/test/test_tiktok_ads_utils.py
@@ -5,9 +5,12 @@ from enum import Enum
from typing import Any, cast
import pytest
-from unittest.mock import Mock
+from unittest.mock import Mock, patch
+
+from django.test import override_settings
from parameterized import parameterized
+from requests.exceptions import HTTPError
from products.warehouse_sources.backend.temporal.data_imports.sources.tiktok_ads.settings import (
TIKTOK_ADS_CONFIG,
@@ -18,6 +21,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.tiktok_ads
TikTokAdsPaginator,
TikTokDateRangeManager,
TikTokReportResource,
+ list_advertisers,
)
@@ -815,3 +819,70 @@ class TestHelperFunctions:
config = TIKTOK_ADS_CONFIG.get(endpoint_name)
assert config is not None, f"Endpoint {endpoint_name} not found in config"
assert config.endpoint_type == expected_endpoint_type
+
+
+class TestListAdvertisers:
+ _MODULE = "products.warehouse_sources.backend.temporal.data_imports.sources.tiktok_ads.utils"
+
+ @staticmethod
+ def _session_returning(body: dict) -> Mock:
+ response = Mock()
+ response.json.return_value = body
+ session = Mock()
+ session.get.return_value = response
+ return session
+
+ @override_settings(TIKTOK_ADS_CLIENT_ID="app", TIKTOK_ADS_CLIENT_SECRET="secret")
+ def test_returns_advertiser_list_on_success(self):
+ session = self._session_returning(
+ {"code": 0, "data": {"list": [{"advertiser_id": "1", "advertiser_name": "Acme"}]}}
+ )
+ with patch(f"{self._MODULE}.make_tracked_session", return_value=session):
+ result = list_advertisers("token")
+
+ assert result == [{"advertiser_id": "1", "advertiser_name": "Acme"}]
+ # app_id + secret go as query params alongside the user's Access-Token header
+ assert session.get.call_args.kwargs["params"] == {"app_id": "app", "secret": "secret"}
+ # A timeout must be set — this call runs in the oauth_accounts web worker and a hung
+ # TikTok connection would otherwise pin the worker indefinitely.
+ assert session.get.call_args.kwargs["timeout"] == 10
+
+ @override_settings(TIKTOK_ADS_CLIENT_ID="app", TIKTOK_ADS_CLIENT_SECRET="secret")
+ def test_non_zero_code_raises_with_api_code(self):
+ session = self._session_returning({"code": 40105, "message": "Access token is invalid"})
+ with patch(f"{self._MODULE}.make_tracked_session", return_value=session):
+ with pytest.raises(TikTokAdsAPIError) as excinfo:
+ list_advertisers("token")
+
+ assert excinfo.value.api_code == 40105
+
+ @override_settings(TIKTOK_ADS_CLIENT_ID="app", TIKTOK_ADS_CLIENT_SECRET="secret")
+ def test_body_without_code_raises_with_none_api_code(self):
+ # A malformed body must not be mistaken for one of the known code sets.
+ session = self._session_returning({"unexpected": "shape"})
+ with patch(f"{self._MODULE}.make_tracked_session", return_value=session):
+ with pytest.raises(TikTokAdsAPIError) as excinfo:
+ list_advertisers("token")
+
+ assert excinfo.value.api_code is None
+
+ @override_settings(TIKTOK_ADS_CLIENT_ID="app", TIKTOK_ADS_CLIENT_SECRET="secret")
+ def test_non_json_body_raises_tiktok_error_not_json_decode_error(self):
+ # A proxy answering HTML would otherwise surface as an opaque JSONDecodeError.
+ response = Mock()
+ response.json.side_effect = ValueError("Expecting value")
+ session = Mock()
+ session.get.return_value = response
+ with patch(f"{self._MODULE}.make_tracked_session", return_value=session):
+ with pytest.raises(TikTokAdsAPIError):
+ list_advertisers("token")
+
+ @override_settings(TIKTOK_ADS_CLIENT_ID="app", TIKTOK_ADS_CLIENT_SECRET="secret")
+ def test_http_error_status_is_raised(self):
+ response = Mock()
+ response.raise_for_status.side_effect = HTTPError("502 Bad Gateway", response=response)
+ session = Mock()
+ session.get.return_value = response
+ with patch(f"{self._MODULE}.make_tracked_session", return_value=session):
+ with pytest.raises(HTTPError):
+ list_advertisers("token")
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/tiktok_ads/utils.py b/products/warehouse_sources/backend/temporal/data_imports/sources/tiktok_ads/utils.py
index 6772c88d9e3a..bcaf4002e779 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/tiktok_ads/utils.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/tiktok_ads/utils.py
@@ -3,14 +3,18 @@ from collections.abc import Iterable
from datetime import UTC, date, datetime, timedelta
from typing import Any, Optional
+from django.conf import settings
+
import structlog
from dateutil import parser
from requests import PreparedRequest, Request, Response
from requests.exceptions import HTTPError, RequestException, Timeout
+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.rest_source.auth import AuthConfigBase
from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.paginators import BasePaginator
from products.warehouse_sources.backend.temporal.data_imports.sources.tiktok_ads.settings import (
+ BASE_URL,
MAX_TIKTOK_DAYS_FOR_REPORT_ENDPOINTS,
MAX_TIKTOK_DAYS_TO_QUERY,
EndpointType,
@@ -18,6 +22,63 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.tiktok_ads
logger = structlog.get_logger(__name__)
+# TikTok replies HTTP 200 even for failures, signalling the outcome in the body `code` (0 = OK).
+# These are the auth/permission codes that only re-authorizing can fix (invalid/revoked token,
+# missing permission). Note 40100 is NOT one of them — it means "requests made too frequently".
+TIKTOK_AUTH_ERROR_CODES = {40105, 40110}
+
+# Throttling (400xx) and TikTok-side outages (5xxxx/60001) also arrive as HTTP 200 + a body `code`,
+# so no HTTP-level retry ever fires on them. Neither is our bug and neither is fixed by reconnecting:
+# the caller just has to try again shortly.
+TIKTOK_TRANSIENT_ERROR_CODES = {
+ 40016, # Requests made too frequently
+ 40100, # Requests made too frequently
+ 40101, # Requests made too frequently
+ 40102, # Requests made too frequently for a certain field value
+ 50000, # System error
+ 51001, # Internal service timeout
+ 60001, # The system is in maintenance
+}
+
+TIKTOK_TRANSIENT_ERROR_MESSAGE = (
+ "TikTok is rate-limiting this connection or is temporarily unavailable. Please try again in a few minutes."
+)
+
+
+def list_advertisers(access_token: str) -> list[dict]:
+ """Every advertiser account the connected TikTok user authorized.
+
+ `oauth2/advertiser/get` returns `advertiser_id` + `advertiser_name` only — richer fields would
+ need `advertiser/info`, which our granted scope can't read.
+ """
+ # Mask the app secret (a query param) and the access token (a header) so neither lands in
+ # request telemetry / captured samples. `timeout` guards the oauth_accounts web worker: TikTok
+ # has no default timeout, so a hung connection would otherwise pin the worker indefinitely.
+ session = make_tracked_session(
+ headers={"Access-Token": access_token, "Content-Type": "application/json"},
+ redact_values=(settings.TIKTOK_ADS_CLIENT_SECRET, access_token),
+ )
+ response = session.get(
+ f"{BASE_URL}/oauth2/advertiser/get/",
+ params={"app_id": settings.TIKTOK_ADS_CLIENT_ID, "secret": settings.TIKTOK_ADS_CLIENT_SECRET},
+ timeout=10,
+ )
+ # A proxy/gateway failure answers with a non-2xx and an HTML body, which `.json()` can't parse.
+ response.raise_for_status()
+ try:
+ body = response.json()
+ except ValueError as e:
+ raise TikTokAdsAPIError("TikTok advertiser/get returned a non-JSON body", response=response) from e
+
+ # A malformed body leaves `code` as None, which is not in any of the code sets, so callers
+ # branching on `api_code` correctly treat it as an unexpected failure rather than a known one.
+ code = body.get("code") if isinstance(body, dict) else None
+ if code != 0:
+ message = body.get("message") if isinstance(body, dict) else None
+ raise TikTokAdsAPIError(f"TikTok advertiser/get failed ({code}): {message}", api_code=code, response=response)
+ return (body.get("data") or {}).get("list") or []
+
+
# Prefix for the ValueError raised when TikTok returns a client error code that
# is not in the retryable set (e.g. 40001 "advertiser doesn't exist or has been
# deleted"). Retrying these never succeeds, so `TikTokAdsSource.get_non_retryable_errors`
@@ -26,7 +87,13 @@ TIKTOK_NON_RETRYABLE_ERROR_PREFIX = "TikTok API client error (non-retryable):"
class TikTokAdsAPIError(Exception):
- """Custom exception for TikTok Ads API errors that should trigger retries."""
+ """A TikTok API failure, carrying the body `code` as `api_code` so callers can branch on it: the
+ pipeline retries all of these, while the account-listing endpoint maps the auth and transient
+ code sets above to actionable messages and lets the rest surface as bugs.
+
+ Deliberately not named `status_code`: drf-exceptions-hog reads that attribute off any escaping
+ exception and would render it as PostHog's HTTP response status.
+ """
def __init__(self, message: str, api_code: int | None = None, response: Optional[Response] = None):
super().__init__(message)