: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 outbrain import source (#63011)
Tom Owersb7666aaa58b6
diff --git a/posthog/temporal/data_imports/sources/SOURCES.md b/posthog/temporal/data_imports/sources/SOURCES.mdindex d24483d0cd25..81d0ea690883 100644--- a/posthog/temporal/data_imports/sources/SOURCES.md+++ b/posthog/temporal/data_imports/sources/SOURCES.md@@ -134,6 +134,7 @@ the row lists both.| notion | HTTP | requests | ✅ || omnisend | HTTP | requests | ✅ || ortto | HTTP | requests | ✅ |+| outbrain | HTTP | requests | ✅ || paddle | HTTP | requests | ✅ || optimizely | HTTP | requests | ✅ || pagerduty | HTTP | requests | ✅ |@@ -285,7 +286,6 @@ doesn't conflict with concurrent PRs.- oracle- oracle_ebs- oracle_fusion-- outbrain- outreach- pagerduty- pardotdiff --git a/posthog/temporal/data_imports/sources/common/http/sampling.py b/posthog/temporal/data_imports/sources/common/http/sampling.pyindex dd149798dc27..76ff650578b2 100644--- a/posthog/temporal/data_imports/sources/common/http/sampling.py+++ b/posthog/temporal/data_imports/sources/common/http/sampling.py@@ -71,7 +71,16 @@ MAX_CONFIG_TTL_SECONDS = 24 * 60 * 60_REDACTED_HEADER = "REDACTED"_REDACTED_FORM_VALUE = "REDACTED"_AUTH_HEADER_NAMES: frozenset[str] = frozenset(- {"authorization", "x-api-key", "x-sn-apikey", "x-auth-token", "cookie", "set-cookie", "proxy-authorization"}+ {+ "authorization",+ "x-api-key",+ "x-sn-apikey",+ "x-auth-token",+ "ob-token-v1",+ "cookie",+ "set-cookie",+ "proxy-authorization",+ })__all__ = ["CaptureConfig", "CaptureRule", "maybe_capture"]diff --git a/posthog/temporal/data_imports/sources/generated_configs.py b/posthog/temporal/data_imports/sources/generated_configs.pyindex 1080dd8f747f..c1bf1430bc6a 100644--- a/posthog/temporal/data_imports/sources/generated_configs.py+++ b/posthog/temporal/data_imports/sources/generated_configs.py@@ -977,7 +977,8 @@ class OrttoSourceConfig(config.Config):@config.configclass OutbrainSourceConfig(config.Config):- pass+ username: str+ password: str@config.configdiff --git a/posthog/temporal/data_imports/sources/outbrain/outbrain.py b/posthog/temporal/data_imports/sources/outbrain/outbrain.pynew file mode 100644index 000000000000..9befe7eff06d--- /dev/null+++ b/posthog/temporal/data_imports/sources/outbrain/outbrain.py@@ -0,0 +1,287 @@+import hashlib+import dataclasses+from collections.abc import Iterator+from datetime import UTC, date, datetime, timedelta+from typing import Any, Optional+from urllib.parse import quote, urlencode++from django.core.cache import cache++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.common.http import make_tracked_session+from posthog.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from posthog.temporal.data_imports.sources.outbrain.settings import (+ OUTBRAIN_BASE_URL,+ OUTBRAIN_ENDPOINTS,+ REPORT_DEFAULT_BACKFILL_DAYS,+ REPORT_LOOKBACK_DAYS,+)++REQUEST_TIMEOUT_SECONDS = 60+MAX_RETRY_ATTEMPTS = 5+PAGE_SIZE = 100+# Periodic reports return one row per day; 500 covers the full default backfill.+REPORT_ROW_LIMIT = 500+# Tokens are valid 30 days but /login is capped at 2 requests/hour, so the+# token is cached across runs and only re-minted when it expires.+TOKEN_CACHE_TTL_SECONDS = 29 * 24 * 60 * 60+++class OutbrainRetryableError(Exception):+ pass+++class OutbrainResumeConfig:+ # Index of the next fan-out parent (marketer or campaign) to process.+ next_index: int+++def _get_session(password: str, token: Optional[str] = None) -> requests.Session:+ secrets = tuple(value for value in (password, token) if value)+ return make_tracked_session(redact_values=secrets)+++def _token_cache_key(username: str, password: str) -> str:+ digest = hashlib.sha256(f"{username}:{password}".encode()).hexdigest()[:32]+ return f"data_imports_outbrain_token_{digest}"+++def _login(username: str, password: str) -> str:+ # The login response body returns OB-TOKEN-V1 in plaintext, and the token is+ # not known until the response arrives, so it cannot be value-redacted from a+ # captured HTTP sample. The login host is the fixed, trusted Outbrain API+ # (no user-supplied host, so no SSRF concern), so issue it on an untracked+ # session to keep the token out of HTTP sample capture entirely.+ # nosemgrep: data-imports-http-transport-requests-verb — untracked on purpose so the token-bearing login response is never sampled+ response = requests.get(+ f"{OUTBRAIN_BASE_URL}/login",+ auth=(username, password),+ timeout=REQUEST_TIMEOUT_SECONDS,+ )+ response.raise_for_status()+ token = response.json().get("OB-TOKEN-V1")+ if not token:+ raise ValueError("Outbrain login returned no OB-TOKEN-V1 token")+ return token+++def _get_token(username: str, password: str, force_refresh: bool = False) -> str:+ cache_key = _token_cache_key(username, password)+ if not force_refresh:+ cached = cache.get(cache_key)+ if cached:+ return cached++ token = _login(username, password)+ cache.set(cache_key, token, TOKEN_CACHE_TTL_SECONDS)+ return token+++def validate_credentials(username: str, password: str) -> bool:+ """Confirm the credentials are valid via the cached-token login flow."""+ try:+ _get_token(username, password)+ return True+ except Exception:+ return False+++def get_rows(+ username: str,+ password: str,+ endpoint: str,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[OutbrainResumeConfig],+ should_use_incremental_field: bool = False,+ db_incremental_field_last_value: Any = None,+) -> Iterator[list[dict[str, Any]]]:+ config = OUTBRAIN_ENDPOINTS[endpoint]+ token = _get_token(username, password)+ # Build the session with the token in redact_values so it is masked from+ # logged URLs and captured HTTP samples on every data request.+ session = _get_session(password, token)++ @retry(+ retry=retry_if_exception_type((OutbrainRetryableError, requests.ReadTimeout, requests.ConnectionError)),+ stop=stop_after_attempt(MAX_RETRY_ATTEMPTS),+ wait=wait_exponential_jitter(initial=5, max=120),+ reraise=True,+ )+ def fetch(url: str) -> dict[str, Any]:+ nonlocal token, session+ response = session.get(url, headers={"OB-TOKEN-V1": token}, timeout=REQUEST_TIMEOUT_SECONDS)++ # Tokens last 30 days; if the cached one has expired mid-sync, re-mint+ # once (the fresh token replaces it in the cache). Rebuild the session so+ # the new token value is registered in redact_values.+ if response.status_code == 401:+ token = _get_token(username, password, force_refresh=True)+ session = _get_session(password, token)+ response = session.get(url, headers={"OB-TOKEN-V1": token}, timeout=REQUEST_TIMEOUT_SECONDS)++ if response.status_code == 429 or response.status_code >= 500:+ raise OutbrainRetryableError(f"Outbrain API error (retryable): status={response.status_code}, url={url}")++ if not response.ok:+ logger.error(f"Outbrain API error: status={response.status_code}, body={response.text[:500]}, url={url}")+ response.raise_for_status()++ return response.json()++ def rows_of(data: Any, key: str) -> list[dict[str, Any]]:+ items = data.get(key) if isinstance(data, dict) else None+ return [row for row in items if isinstance(row, dict)] if isinstance(items, list) else []++ def fetch_paginated(path: str) -> Iterator[list[dict[str, Any]]]:+ offset = 0+ while True:+ params = {"limit": PAGE_SIZE, "offset": offset} if config.paginated else {}+ url = f"{OUTBRAIN_BASE_URL}{path}"+ if params:+ url = f"{url}?{urlencode(params)}"+ rows = rows_of(fetch(url), config.data_key)+ if rows:+ yield rows+ if not config.paginated or len(rows) < PAGE_SIZE:+ return+ offset += len(rows)++ def list_marketer_ids() -> list[str]:+ marketers = rows_of(fetch(f"{OUTBRAIN_BASE_URL}/marketers"), "marketers")+ return [str(m["id"]) for m in marketers if m.get("id")]++ resume_config = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None+ start_index = resume_config.next_index if resume_config is not None else 0+ if resume_config is not None:+ logger.debug(f"Outbrain: resuming {endpoint} from index {start_index}")++ if config.kind == "marketers":+ yield from fetch_paginated(config.path)+ return++ if config.kind in ("per_marketer", "per_campaign"):+ if config.kind == "per_marketer":+ parents = [+ ("_marketer_id", marketer_id, {"marketer_id": marketer_id}) for marketer_id in list_marketer_ids()+ ]+ else:+ campaign_ids: list[str] = []+ for marketer_id in list_marketer_ids():+ campaigns_config = OUTBRAIN_ENDPOINTS["campaigns"]+ offset = 0+ while True:+ url = (+ f"{OUTBRAIN_BASE_URL}/marketers/{quote(marketer_id)}/campaigns?"+ f"{urlencode({'limit': PAGE_SIZE, 'offset': offset})}"+ )+ batch = rows_of(fetch(url), campaigns_config.data_key)+ campaign_ids.extend(str(c["id"]) for c in batch if c.get("id"))+ if len(batch) < PAGE_SIZE:+ break+ offset += len(batch)+ parents = [("_campaign_id", campaign_id, {"campaign_id": campaign_id}) for campaign_id in campaign_ids]++ for index in range(start_index, len(parents)):+ id_field, parent_id, path_params = parents[index]+ path = config.path.format(**{k: quote(v) for k, v in path_params.items()})+ for page in fetch_paginated(path):+ yield [{**row, id_field: parent_id} for row in page]+ # Save state AFTER yielding so a crash re-yields the in-flight+ # parent (merge dedupes on primary key).+ resumable_source_manager.save_state(OutbrainResumeConfig(next_index=index + 1))+ return++ # Report streams: one date-windowed request per marketer.+ today = datetime.now(tz=UTC).date()+ if config.kind == "snapshot_report":+ window_start = today - timedelta(days=REPORT_LOOKBACK_DAYS)+ else:+ window_start = today - timedelta(days=REPORT_DEFAULT_BACKFILL_DAYS)+ if should_use_incremental_field:+ watermark = _to_date(db_incremental_field_last_value)+ if watermark is not None:+ # Conversions restate for ~30 days — re-pull the lookback window.+ window_start = watermark - timedelta(days=REPORT_LOOKBACK_DAYS)++ marketer_ids = list_marketer_ids()+ for index in range(start_index, len(marketer_ids)):+ marketer_id = marketer_ids[index]+ params = urlencode(+ {+ "from": window_start.isoformat(),+ "to": today.isoformat(),+ "breakdown": "daily",+ "limit": REPORT_ROW_LIMIT,+ }+ if config.kind == "periodic_report"+ else {"from": window_start.isoformat(), "to": today.isoformat(), "limit": REPORT_ROW_LIMIT}+ )+ path = config.path.format(marketer_id=quote(marketer_id))+ rows = rows_of(fetch(f"{OUTBRAIN_BASE_URL}{path}?{params}"), config.data_key)++ out: list[dict[str, Any]] = []+ for row in rows:+ enriched = {**row, "_marketer_id": marketer_id}+ if config.kind == "periodic_report":+ metadata_value = row.get("metadata")+ metadata = metadata_value if isinstance(metadata_value, dict) else {}+ row_date = metadata.get("fromDate") or metadata.get("id")+ if not row_date:+ continue+ enriched["_date"] = row_date+ out.append(enriched)+ if out:+ yield out++ # Save state AFTER yielding so a crash re-yields the in-flight marketer.+ resumable_source_manager.save_state(OutbrainResumeConfig(next_index=index + 1))+++def _to_date(value: Any) -> Optional[date]:+ if isinstance(value, datetime):+ return value.date()+ if isinstance(value, date):+ return value+ if isinstance(value, str):+ try:+ return datetime.fromisoformat(value.replace("Z", "+00:00")).date()+ except ValueError:+ return None+ return None+++def outbrain_source(+ username: str,+ password: str,+ endpoint: str,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[OutbrainResumeConfig],+ should_use_incremental_field: bool = False,+ db_incremental_field_last_value: Optional[Any] = None,+) -> SourceResponse:+ config = OUTBRAIN_ENDPOINTS[endpoint]++ return SourceResponse(+ name=endpoint,+ items=lambda: get_rows(+ username=username,+ password=password,+ 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=list(config.primary_keys) if config.primary_keys else None,+ partition_count=1,+ partition_size=1,+ # The periodic report walks marketers sequentially and each marketer's+ # rows cover the same window, so the date watermark is only safe to+ # commit once a run completes.+ sort_mode="desc" if config.incremental_fields else "asc",+ )diff --git a/posthog/temporal/data_imports/sources/outbrain/settings.py b/posthog/temporal/data_imports/sources/outbrain/settings.pynew file mode 100644index 000000000000..476a77e63840--- /dev/null+++ b/posthog/temporal/data_imports/sources/outbrain/settings.py@@ -0,0 +1,95 @@+from dataclasses import dataclass, field+from typing import Literal++from products.data_warehouse.backend.types import IncrementalField, IncrementalFieldType++OUTBRAIN_BASE_URL = "https://api.outbrain.com/amplify/v0.1"++# Conversion metrics restate for up to ~30 days (attribution), so incremental+# report syncs re-pull a trailing window and merge on (_marketer_id, _date).+REPORT_LOOKBACK_DAYS = 30+# Default history pulled on the first sync of the periodic report stream.+REPORT_DEFAULT_BACKFILL_DAYS = 365++OutbrainEndpointKind = Literal["marketers", "per_marketer", "per_campaign", "periodic_report", "snapshot_report"]++_DATE_INCREMENTAL_FIELDS: list[IncrementalField] = [+ {+ "label": "_date",+ "type": IncrementalFieldType.Date,+ "field": "_date",+ "field_type": IncrementalFieldType.Date,+ },+]+++@dataclass+class OutbrainEndpointConfig:+ name: str+ kind: OutbrainEndpointKind+ # Path template under the Amplify base URL; `{marketer_id}`/`{campaign_id}`+ # are filled per fan-out parent.+ path: str+ # Key holding the row list in the response body.+ data_key: str+ primary_keys: list[str] | None = field(default_factory=lambda: ["id"])+ incremental_fields: list[IncrementalField] = field(default_factory=list)+ # Entity endpoints paginate with limit/offset.+ paginated: bool = False+++OUTBRAIN_ENDPOINTS: dict[str, OutbrainEndpointConfig] = {+ # Entity endpoints have no updated-since filter — honest full refresh.+ "marketers": OutbrainEndpointConfig(+ name="marketers",+ kind="marketers",+ path="/marketers",+ data_key="marketers",+ ),+ "campaigns": OutbrainEndpointConfig(+ name="campaigns",+ kind="per_marketer",+ path="/marketers/{marketer_id}/campaigns",+ data_key="campaigns",+ paginated=True,+ ),+ "budgets": OutbrainEndpointConfig(+ name="budgets",+ kind="per_marketer",+ path="/marketers/{marketer_id}/budgets",+ data_key="budgets",+ paginated=True,+ ),+ "promoted_links": OutbrainEndpointConfig(+ name="promoted_links",+ kind="per_campaign",+ path="/campaigns/{campaign_id}/promotedLinks",+ data_key="promotedLinks",+ paginated=True,+ ),+ # Daily periodic performance per marketer; rows carry the day in+ # metadata, injected as `_date` for the incremental cursor.+ "marketer_performance_daily": OutbrainEndpointConfig(+ name="marketer_performance_daily",+ kind="periodic_report",+ path="/reports/marketers/{marketer_id}/periodic",+ data_key="results",+ primary_keys=["_marketer_id", "_date"],+ incremental_fields=list(_DATE_INCREMENTAL_FIELDS),+ ),+ # Per-campaign totals for a trailing window; rows carry no date, so this+ # is a snapshot (full refresh).+ "campaign_performance": OutbrainEndpointConfig(+ name="campaign_performance",+ kind="snapshot_report",+ path="/reports/marketers/{marketer_id}/campaigns",+ data_key="results",+ primary_keys=None,+ ),+}++ENDPOINTS = tuple(OUTBRAIN_ENDPOINTS.keys())++INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {+ name: config.incremental_fields for name, config in OUTBRAIN_ENDPOINTS.items() if config.incremental_fields+}diff --git a/posthog/temporal/data_imports/sources/outbrain/source.py b/posthog/temporal/data_imports/sources/outbrain/source.pyindex 4dca7e1f6132..188a98440e15 100644--- a/posthog/temporal/data_imports/sources/outbrain/source.py+++ b/posthog/temporal/data_imports/sources/outbrain/source.py@@ -1,29 +1,124 @@-from typing import cast+from typing import Optional, castfrom posthog.schema import (ExternalDataSourceType as SchemaExternalDataSourceType,+ ReleaseStatus,SourceConfig,+ SourceFieldInputConfig,+ SourceFieldInputConfigType,)-from posthog.temporal.data_imports.sources.common.base import FieldType, SimpleSource+from posthog.temporal.data_imports.pipelines.pipeline.typings import SourceInputs, SourceResponse+from posthog.temporal.data_imports.sources.common.base import FieldType, ResumableSourcefrom posthog.temporal.data_imports.sources.common.registry import SourceRegistry+from posthog.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from posthog.temporal.data_imports.sources.common.schema import SourceSchemafrom posthog.temporal.data_imports.sources.generated_configs import OutbrainSourceConfig+from posthog.temporal.data_imports.sources.outbrain.outbrain import (+ OutbrainResumeConfig,+ outbrain_source,+ validate_credentials as validate_outbrain_credentials,+)+from posthog.temporal.data_imports.sources.outbrain.settings import ENDPOINTS, INCREMENTAL_FIELDSfrom products.data_warehouse.backend.types import ExternalDataSourceType@SourceRegistry.register-class OutbrainSource(SimpleSource[OutbrainSourceConfig]):+class OutbrainSource(ResumableSource[OutbrainSourceConfig, OutbrainResumeConfig]):@propertydef source_type(self) -> ExternalDataSourceType:return ExternalDataSourceType.OUTBRAIN+ def get_non_retryable_errors(self) -> dict[str, str | None]:+ return {+ "401 Client Error: Unauthorized for url: https://api.outbrain.com/amplify/v0.1/login": "Outbrain authentication failed. Please check your username and password.",+ "403 Client Error: Forbidden for url: https://api.outbrain.com": "Outbrain denied access. Please check that your account has Amplify API access (requested via your account manager).",+ }+@propertydef get_source_config(self) -> SourceConfig:return SourceConfig(name=SchemaExternalDataSourceType.OUTBRAIN,label="Outbrain",+ caption="""Connect your Outbrain Amplify account to pull your advertising data into the PostHog Data warehouse.++Uses your Outbrain login credentials. Amplify API access must be enabled for your account — request it through your Outbrain account manager if API calls are rejected.""",iconPath="/static/services/outbrain.png",- fields=cast(list[FieldType], []),- unreleasedSource=True,+ docsUrl="https://posthog.com/docs/cdp/sources/outbrain",+ releaseStatus=ReleaseStatus.ALPHA,+ fields=cast(+ list[FieldType],+ [+ SourceFieldInputConfig(+ name="username",+ label="Username",+ type=SourceFieldInputConfigType.TEXT,+ required=True,+ placeholder="[email protected]",+ secret=False,+ ),+ SourceFieldInputConfig(+ name="password",+ label="Password",+ type=SourceFieldInputConfigType.PASSWORD,+ required=True,+ placeholder="",+ secret=True,+ ),+ ],+ ),+ )++ def get_schemas(+ self,+ config: OutbrainSourceConfig,+ 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: OutbrainSourceConfig, team_id: int, schema_name: Optional[str] = None+ ) -> tuple[bool, str | None]:+ if validate_outbrain_credentials(config.username, config.password):+ return True, None++ return False, "Invalid Outbrain credentials"++ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[OutbrainResumeConfig]:+ return ResumableSourceManager[OutbrainResumeConfig](inputs, OutbrainResumeConfig)++ def source_for_pipeline(+ self,+ config: OutbrainSourceConfig,+ resumable_source_manager: ResumableSourceManager[OutbrainResumeConfig],+ inputs: SourceInputs,+ ) -> SourceResponse:+ return outbrain_source(+ username=config.username,+ password=config.password,+ 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/posthog/temporal/data_imports/sources/outbrain/tests/test_outbrain.py b/posthog/temporal/data_imports/sources/outbrain/tests/test_outbrain.pynew file mode 100644index 000000000000..cdfe52bf3ed8--- /dev/null+++ b/posthog/temporal/data_imports/sources/outbrain/tests/test_outbrain.py@@ -0,0 +1,236 @@+from typing import Any++import pytest+from unittest import mock++from posthog.temporal.data_imports.sources.outbrain.outbrain import (+ PAGE_SIZE,+ OutbrainResumeConfig,+ _token_cache_key,+ get_rows,+ outbrain_source,+ validate_credentials,+)+from posthog.temporal.data_imports.sources.outbrain.settings import ENDPOINTS, OUTBRAIN_ENDPOINTS++_MODULE = "posthog.temporal.data_imports.sources.outbrain.outbrain"+++def _make_manager(resume_state: OutbrainResumeConfig | None = None) -> mock.MagicMock:+ manager = mock.MagicMock()+ manager.can_resume.return_value = resume_state is not None+ manager.load_state.return_value = resume_state+ return manager+++def _response(body: Any, status_code: int = 200) -> mock.MagicMock:+ resp = mock.MagicMock()+ resp.json.return_value = body+ resp.status_code = status_code+ resp.ok = status_code < 400+ return resp+++def _no_cache() -> mock.MagicMock:+ cache = mock.MagicMock()+ cache.get.return_value = None+ return cache+++class TestTokenCaching:+ def test_cache_key_is_stable_and_credential_scoped(self):+ assert _token_cache_key("u", "p") == _token_cache_key("u", "p")+ assert _token_cache_key("u", "p") != _token_cache_key("u", "other")++ @mock.patch(f"{_MODULE}.cache")+ @mock.patch(f"{_MODULE}.requests.get")+ def test_login_mints_and_caches_token(self, mock_get, mock_cache):+ mock_cache.get.return_value = None+ mock_get.return_value = _response({"OB-TOKEN-V1": "tok-1"})++ assert validate_credentials("u", "p") is True+ login_call = mock_get.call_args+ assert login_call.args[0] == "https://api.outbrain.com/amplify/v0.1/login"+ assert login_call.kwargs["auth"] == ("u", "p")+ mock_cache.set.assert_called_once()+ assert mock_cache.set.call_args.args[1] == "tok-1"++ @mock.patch(f"{_MODULE}.cache")+ @mock.patch(f"{_MODULE}.requests.get")+ def test_cached_token_skips_login(self, mock_get, mock_cache):+ # /login is capped at 2 requests/hour, so the cache must short-circuit.+ mock_cache.get.return_value = "tok-cached"++ assert validate_credentials("u", "p") is True+ mock_get.assert_not_called()++ @mock.patch(f"{_MODULE}.cache")+ @mock.patch(f"{_MODULE}.requests.get")+ def test_login_without_token_in_response_fails(self, mock_get, mock_cache):+ mock_cache.get.return_value = None+ mock_get.return_value = _response({"message": "nope"})++ assert validate_credentials("u", "p") is False++[email protected](f"{_MODULE}.cache")+class TestEntityStreams:+ @mock.patch(f"{_MODULE}.make_tracked_session")+ def test_marketers_single_fetch(self, mock_session, mock_cache):+ mock_cache.get.return_value = "tok"+ mock_session.return_value.get.return_value = _response({"marketers": [{"id": "m1"}, {"id": "m2"}]})++ batches = list(get_rows("u", "p", "marketers", mock.MagicMock(), _make_manager()))++ assert [row["id"] for batch in batches for row in batch] == ["m1", "m2"]+ url = mock_session.return_value.get.call_args.args[0]+ assert url == "https://api.outbrain.com/amplify/v0.1/marketers"+ assert mock_session.return_value.get.call_args.kwargs["headers"] == {"OB-TOKEN-V1": "tok"}++ @mock.patch(f"{_MODULE}.make_tracked_session")+ def test_campaigns_fan_out_per_marketer_with_offset_pagination(self, mock_session, mock_cache):+ mock_cache.get.return_value = "tok"+ full_page = [{"id": f"c{i}"} for i in range(PAGE_SIZE)]+ mock_session.return_value.get.side_effect = [+ _response({"marketers": [{"id": "m1"}]}),+ _response({"campaigns": full_page}),+ _response({"campaigns": [{"id": "c-last"}]}),+ ]++ manager = _make_manager()+ batches = list(get_rows("u", "p", "campaigns", mock.MagicMock(), manager))++ assert [len(batch) for batch in batches] == [PAGE_SIZE, 1]+ assert all(row["_marketer_id"] == "m1" for batch in batches for row in batch)+ second_page_url = mock_session.return_value.get.call_args_list[2].args[0]+ assert f"offset={PAGE_SIZE}" in second_page_url+ assert [call.args[0].next_index for call in manager.save_state.call_args_list] == [1]++ @mock.patch(f"{_MODULE}.make_tracked_session")+ def test_promoted_links_fan_out_per_campaign(self, mock_session, mock_cache):+ mock_cache.get.return_value = "tok"+ mock_session.return_value.get.side_effect = [+ _response({"marketers": [{"id": "m1"}]}),+ _response({"campaigns": [{"id": "c1"}]}),+ _response({"promotedLinks": [{"id": "pl1"}]}),+ ]++ batches = list(get_rows("u", "p", "promoted_links", mock.MagicMock(), _make_manager()))++ flat = [row for batch in batches for row in batch]+ assert [(r["id"], r["_campaign_id"]) for r in flat] == [("pl1", "c1")]+ links_url = mock_session.return_value.get.call_args_list[2].args[0]+ assert "/campaigns/c1/promotedLinks" in links_url++ @mock.patch(f"{_MODULE}.make_tracked_session")+ def test_resumes_from_saved_parent_index(self, mock_session, mock_cache):+ mock_cache.get.return_value = "tok"+ mock_session.return_value.get.side_effect = [+ _response({"marketers": [{"id": "m1"}, {"id": "m2"}]}),+ _response({"budgets": [{"id": "b2"}]}),+ ]++ manager = _make_manager(OutbrainResumeConfig(next_index=1))+ batches = list(get_rows("u", "p", "budgets", mock.MagicMock(), manager))++ flat = [row for batch in batches for row in batch]+ assert [r["_marketer_id"] for r in flat] == ["m2"]++ @mock.patch(f"{_MODULE}.requests.get")+ @mock.patch(f"{_MODULE}.make_tracked_session")+ def test_mid_sync_401_re_mints_token(self, mock_session, mock_get, mock_cache):+ mock_cache.get.return_value = "tok-stale"+ # The data requests run on the tracked session; the mid-sync re-mint+ # logs in on an untracked session (requests.get).+ mock_session.return_value.get.side_effect = [+ _response({}, status_code=401),+ _response({"marketers": [{"id": "m1"}]}),+ ]+ mock_get.return_value = _response({"OB-TOKEN-V1": "tok-fresh"})++ batches = list(get_rows("u", "p", "marketers", mock.MagicMock(), _make_manager()))++ assert [row["id"] for batch in batches for row in batch] == ["m1"]+ retry_headers = mock_session.return_value.get.call_args_list[1].kwargs["headers"]+ assert retry_headers == {"OB-TOKEN-V1": "tok-fresh"}++[email protected](f"{_MODULE}.cache")+class TestReportStreams:+ @mock.patch(f"{_MODULE}.make_tracked_session")+ def test_periodic_report_injects_date_and_marketer(self, mock_session, mock_cache):+ mock_cache.get.return_value = "tok"+ mock_session.return_value.get.side_effect = [+ _response({"marketers": [{"id": "m1"}]}),+ _response(+ {+ "results": [+ {"metadata": {"fromDate": "2024-01-01"}, "metrics": {"clicks": 5}},+ {"metadata": {"fromDate": "2024-01-02"}, "metrics": {"clicks": 7}},+ {"metrics": {"clicks": 0}}, # no date — dropped+ ]+ }+ ),+ ]++ manager = _make_manager()+ batches = list(get_rows("u", "p", "marketer_performance_daily", mock.MagicMock(), manager))++ flat = [row for batch in batches for row in batch]+ assert [(r["_date"], r["_marketer_id"]) for r in flat] == [("2024-01-01", "m1"), ("2024-01-02", "m1")]+ report_url = mock_session.return_value.get.call_args_list[1].args[0]+ assert "breakdown=daily" in report_url+ assert "from=" in report_url and "to=" in report_url+ assert [call.args[0].next_index for call in manager.save_state.call_args_list] == [1]++ @mock.patch(f"{_MODULE}.make_tracked_session")+ def test_incremental_starts_lookback_before_watermark(self, mock_session, mock_cache):+ mock_cache.get.return_value = "tok"+ mock_session.return_value.get.side_effect = [+ _response({"marketers": [{"id": "m1"}]}),+ _response({"results": []}),+ ]++ list(+ get_rows(+ "u",+ "p",+ "marketer_performance_daily",+ mock.MagicMock(),+ _make_manager(),+ should_use_incremental_field=True,+ db_incremental_field_last_value="2024-06-01",+ )+ )++ report_url = mock_session.return_value.get.call_args_list[1].args[0]+ # 30-day lookback before the watermark.+ assert "from=2024-05-02" in report_url++ @mock.patch(f"{_MODULE}.make_tracked_session")+ def test_campaign_performance_is_trailing_window_snapshot(self, mock_session, mock_cache):+ mock_cache.get.return_value = "tok"+ mock_session.return_value.get.side_effect = [+ _response({"marketers": [{"id": "m1"}]}),+ _response({"results": [{"campaignId": "c1", "metrics": {"spend": 12.5}}]}),+ ]++ batches = list(get_rows("u", "p", "campaign_performance", mock.MagicMock(), _make_manager()))++ flat = [row for batch in batches for row in batch]+ assert flat[0]["_marketer_id"] == "m1"+ assert "_date" not in flat[0]+ report_url = mock_session.return_value.get.call_args_list[1].args[0]+ assert "breakdown" not in report_url+++class TestOutbrainSourceResponse:+ @pytest.mark.parametrize("endpoint", list(ENDPOINTS))+ def test_response_metadata_per_endpoint(self, endpoint):+ config = OUTBRAIN_ENDPOINTS[endpoint]+ response = outbrain_source("u", "p", endpoint, mock.MagicMock(), _make_manager())++ assert response.name == endpoint+ assert response.primary_keys == config.primary_keys+ expected_sort = "desc" if config.incremental_fields else "asc"+ assert response.sort_mode == expected_sortdiff --git a/posthog/temporal/data_imports/sources/outbrain/tests/test_outbrain_source.py b/posthog/temporal/data_imports/sources/outbrain/tests/test_outbrain_source.pynew file mode 100644index 000000000000..f9636a4c77e9--- /dev/null+++ b/posthog/temporal/data_imports/sources/outbrain/tests/test_outbrain_source.py@@ -0,0 +1,142 @@+import pytest+from unittest import mock++from posthog.schema import ReleaseStatus, SourceFieldInputConfig, SourceFieldInputConfigType++from posthog.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from posthog.temporal.data_imports.sources.generated_configs import OutbrainSourceConfig+from posthog.temporal.data_imports.sources.outbrain.outbrain import OutbrainResumeConfig+from posthog.temporal.data_imports.sources.outbrain.settings import ENDPOINTS, INCREMENTAL_FIELDS+from posthog.temporal.data_imports.sources.outbrain.source import OutbrainSource++from products.data_warehouse.backend.types import ExternalDataSourceType+++class TestOutbrainSource:+ def setup_method(self):+ self.source = OutbrainSource()+ self.team_id = 123+ self.config = OutbrainSourceConfig(username="[email protected]", password="pw")++ def test_source_type(self):+ assert self.source.source_type == ExternalDataSourceType.OUTBRAIN++ def test_get_source_config(self):+ config = self.source.get_source_config++ assert config.name.value == "Outbrain"+ assert config.label == "Outbrain"+ assert config.releaseStatus == ReleaseStatus.ALPHA+ assert config.unreleasedSource is None+ assert config.iconPath == "/static/services/outbrain.png"++ field_names = [f.name for f in config.fields]+ assert field_names == ["username", "password"]++ def test_password_field_is_secret(self):+ config = self.source.get_source_config+ password_field = next(+ f for f in config.fields if isinstance(f, SourceFieldInputConfig) and f.name == "password"+ )+ assert password_field.type == SourceFieldInputConfigType.PASSWORD+ assert password_field.secret is True+ assert password_field.required is True++ @pytest.mark.parametrize(+ "observed_error",+ [+ "401 Client Error: Unauthorized for url: https://api.outbrain.com/amplify/v0.1/login",+ "403 Client Error: Forbidden for url: https://api.outbrain.com/amplify/v0.1/marketers",+ ],+ )+ 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://api.outbrain.com/amplify/v0.1/marketers",+ # Mid-sync 401s on data endpoints are handled by token re-mint.+ "401 Client Error: Unauthorized for url: https://api.outbrain.com/amplify/v0.1/marketers",+ ],+ )+ 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(self):+ schemas = {schema.name: schema for schema in self.source.get_schemas(self.config, self.team_id)}++ assert set(schemas) == set(ENDPOINTS)+ # Only the daily periodic report has a real server-side date filter+ # with a per-row date.+ incremental = {name for name, schema in schemas.items() if schema.supports_incremental}+ assert incremental == {"marketer_performance_daily"}+ assert (+ schemas["marketer_performance_daily"].incremental_fields == INCREMENTAL_FIELDS["marketer_performance_daily"]+ )+ assert schemas["campaigns"].incremental_fields == []++ def test_get_schemas_filtered_by_names(self):+ schemas = self.source.get_schemas(self.config, self.team_id, names=["marketers"])+ assert len(schemas) == 1+ assert schemas[0].name == "marketers"++ 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",+ [+ (True, True),+ (False, False),+ ],+ )+ @mock.patch("posthog.temporal.data_imports.sources.outbrain.source.validate_outbrain_credentials")+ def test_validate_credentials(self, mock_validate, mock_return, expected_valid):+ 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+ if not expected_valid:+ assert error_message == "Invalid Outbrain credentials"+ mock_validate.assert_called_once_with("[email protected]", "pw")++ def test_get_resumable_source_manager_binds_resume_config(self):+ inputs = mock.MagicMock()+ manager = self.source.get_resumable_source_manager(inputs)++ assert isinstance(manager, ResumableSourceManager)+ assert manager._data_class is OutbrainResumeConfig++ @mock.patch("posthog.temporal.data_imports.sources.outbrain.source.outbrain_source")+ def test_source_for_pipeline_plumbs_arguments(self, mock_outbrain_source):+ inputs = mock.MagicMock()+ inputs.schema_name = "marketer_performance_daily"+ inputs.should_use_incremental_field = True+ inputs.db_incremental_field_last_value = "2024-06-01"+ manager = mock.MagicMock()++ self.source.source_for_pipeline(self.config, manager, inputs)++ mock_outbrain_source.assert_called_once()+ kwargs = mock_outbrain_source.call_args.kwargs+ assert kwargs["username"] == "[email protected]"+ assert kwargs["password"] == "pw"+ assert kwargs["endpoint"] == "marketer_performance_daily"+ assert kwargs["resumable_source_manager"] is manager+ assert kwargs["should_use_incremental_field"] is True+ assert kwargs["db_incremental_field_last_value"] == "2024-06-01"++ @mock.patch("posthog.temporal.data_imports.sources.outbrain.source.outbrain_source")+ def test_source_for_pipeline_omits_last_value_on_full_refresh(self, mock_outbrain_source):+ inputs = mock.MagicMock()+ inputs.schema_name = "marketers"+ inputs.should_use_incremental_field = False+ inputs.db_incremental_field_last_value = "2024-06-01"++ self.source.source_for_pipeline(self.config, mock.MagicMock(), inputs)++ assert mock_outbrain_source.call_args.kwargs["db_incremental_field_last_value"] is None