: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 awin import source (#67813)
Tom Owersd8c169f40261
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.mdindex 2f8692fc1660..d3a21b5a946b 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md@@ -62,6 +62,7 @@ the row lists both.| attentive | HTTP (webhook-first) | requests (webhook management) | ✅ || attio | HTTP | requests + `rest_source.RESTClient` | ✅ || aviationstack | HTTP | requests | ✅ |+| awin | HTTP | requests | ✅ || azure_devops | HTTP | requests | ✅ || bamboohr | HTTP | requests | ✅ || beamer | HTTP | requests | ✅ |@@ -358,7 +359,6 @@ doesn't conflict with concurrent PRs.- appstack- apptivo- auth0-- awin- aws_cloudtrail- azure_blob- azure_table_storagediff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/awin/awin.py b/products/warehouse_sources/backend/temporal/data_imports/sources/awin/awin.pynew file mode 100644index 000000000000..334a87648f9e--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/awin/awin.py@@ -0,0 +1,292 @@+import dataclasses+from collections.abc import Iterator+from datetime import UTC, date, datetime, timedelta+from typing import Any, Optional+from urllib.parse import urlencode++import requests+from structlog.types import FilteringBoundLogger+from tenacity import retry, retry_if_exception_type, stop_after_attempt, wait_exponential_jitter++from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import SourceResponse+from products.warehouse_sources.backend.temporal.data_imports.sources.awin.settings import (+ AWIN_ENDPOINTS,+ DEFAULT_BACKFILL_DAYS,+ MAX_WINDOW_DAYS,+ AwinEndpointConfig,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.http import make_tracked_session+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager++AWIN_BASE_URL = "https://api.awin.com"++# Awin windows are always expressed against a named timezone param rather than an offset baked into+# the timestamp string. We pin everything to UTC so cursors and windows stay consistent.+AWIN_TIMEZONE = "UTC"++REQUEST_TIMEOUT_SECONDS = 60+++class AwinRetryableError(Exception):+ """Transient Awin API failure (429 throttling or 5xx) worth retrying."""+++class AwinResumeConfig:+ # The publisher account currently being processed. A stable account-ID bookmark (not a positional+ # index) so accounts added/removed between a crash and the retry can't resume us into the wrong one.+ account_id: Optional[int] = None+ # ISO start of the date window last yielded for `account_id`. `None` for non-windowed endpoints.+ window_start: Optional[str] = None+++def _get_headers(api_token: str) -> dict[str, str]:+ return {+ "Authorization": f"Bearer {api_token}",+ "Accept": "application/json",+ }+++@retry(+ retry=retry_if_exception_type(+ (+ AwinRetryableError,+ requests.ReadTimeout,+ requests.ConnectionError,+ requests.exceptions.ChunkedEncodingError,+ )+ ),+ stop=stop_after_attempt(6),+ # Awin throttles at 20 calls/minute/user, so back off generously (up to a minute) on a 429.+ wait=wait_exponential_jitter(initial=2, max=60),+ reraise=True,+)+def _fetch(+ session: requests.Session,+ path: str,+ headers: dict[str, str],+ params: dict[str, Any],+ logger: FilteringBoundLogger,+) -> Any:+ url = f"{AWIN_BASE_URL}{path}"+ if params:+ url = f"{url}?{urlencode(params)}"++ response = session.get(url, headers=headers, timeout=REQUEST_TIMEOUT_SECONDS)++ if response.status_code == 429 or response.status_code >= 500:+ raise AwinRetryableError(f"Awin API error (retryable): status={response.status_code}, url={url}")++ if not response.ok:+ logger.error(f"Awin API error: status={response.status_code}, body={response.text}, url={url}")+ response.raise_for_status()++ return response.json()+++def validate_credentials(api_token: str) -> bool:+ try:+ session = make_tracked_session(redact_values=(api_token,))+ response = session.get(f"{AWIN_BASE_URL}/accounts", headers=_get_headers(api_token), timeout=10)+ return response.status_code == 200+ except Exception:+ return False+++def _discover_publisher_ids(+ session: requests.Session, headers: dict[str, str], logger: FilteringBoundLogger+) -> list[int]:+ """Return the publisher account ids the token can access, sorted for deterministic fan-out order.++ Awin exposes both publisher and advertiser accounts through /accounts; every endpoint this source+ implements is publisher-scoped, so we keep only the publisher accounts.+ """+ data = _fetch(session, "/accounts", headers, {}, logger)+ accounts = data.get("accounts", []) if isinstance(data, dict) else []+ publisher_ids = [+ account["accountId"]+ for account in accounts+ if account.get("accountType") == "publisher" and account.get("accountId") is not None+ ]+ return sorted(set(publisher_ids))+++def _to_datetime(value: Any) -> Optional[datetime]:+ if value is None:+ return None+ if isinstance(value, datetime):+ return value if value.tzinfo is not None else value.replace(tzinfo=UTC)+ if isinstance(value, date):+ return datetime.combine(value, datetime.min.time(), tzinfo=UTC)+ if isinstance(value, str):+ try:+ parsed = datetime.fromisoformat(value.replace("Z", "+00:00"))+ return parsed if parsed.tzinfo is not None else parsed.replace(tzinfo=UTC)+ except ValueError:+ return None+ return None+++def _iter_windows(start: datetime, end: datetime, max_days: int) -> Iterator[tuple[datetime, datetime]]:+ """Yield ascending (start, end) windows no wider than `max_days`, covering [start, end]."""+ cursor = start+ step = timedelta(days=max_days)+ while cursor < end:+ window_end = min(cursor + step, end)+ yield cursor, window_end+ cursor = window_end+++def _build_window_params(+ config: AwinEndpointConfig, window_start: datetime, window_end: datetime, incremental_field: Optional[str]+) -> dict[str, str]:+ params: dict[str, str] = {+ "startDate": window_start.strftime(config.date_format),+ "endDate": window_end.strftime(config.date_format),+ "timezone": AWIN_TIMEZONE,+ }+ if config.date_type_by_field:+ default_date_type = next(iter(config.date_type_by_field.values()))+ params["dateType"] = config.date_type_by_field.get(incremental_field or "", default_date_type)+ params.update(config.extra_params)+ return params+++def _windows_for_account(+ config: AwinEndpointConfig,+ should_use_incremental_field: bool,+ db_incremental_field_last_value: Any,+) -> list[Optional[tuple[datetime, datetime]]]:+ """Build the ordered list of date windows to fetch for one account.++ Non-windowed endpoints (programmes) collapse to a single `None` window (one plain request).+ """+ if not config.date_windowed:+ return [None]++ now = datetime.now(UTC)+ if config.report_lookback_days is not None:+ # Reports are a rolling full-refresh snapshot, not an incremental scroll.+ start = now - timedelta(days=config.report_lookback_days)+ elif should_use_incremental_field and db_incremental_field_last_value is not None:+ start = _to_datetime(db_incremental_field_last_value) or (now - timedelta(days=DEFAULT_BACKFILL_DAYS))+ else:+ start = now - timedelta(days=DEFAULT_BACKFILL_DAYS)++ if start >= now:+ return []+ return list(_iter_windows(start, now, MAX_WINDOW_DAYS))+++def _rows_from_response(config: AwinEndpointConfig, data: Any, publisher_id: Optional[int]) -> list[dict[str, Any]]:+ if config.data_key is not None:+ rows = data.get(config.data_key, []) if isinstance(data, dict) else []+ else:+ rows = data if isinstance(data, list) else []++ rows = [row for row in rows if isinstance(row, dict)]+ if config.inject_publisher_id and publisher_id is not None:+ for row in rows:+ row.setdefault("publisherId", publisher_id)+ return rows+++def _resume_index(+ work_items: list[tuple[Optional[tuple[datetime, datetime]], int]], resume: Optional[AwinResumeConfig]+) -> int:+ """Find where to restart the (window, account) work list from a saved bookmark.++ Returns the index of the last-yielded item so it's re-processed (merge dedupes) and everything+ after it runs. Falls back to the start when there's no bookmark or it no longer matches (e.g. the+ account list changed between runs).+ """+ if resume is None:+ return 0+ for index, (window, publisher_id) in enumerate(work_items):+ window_start = window[0].isoformat() if window is not None else None+ if publisher_id == resume.account_id and window_start == resume.window_start:+ return index+ return 0+++def get_rows(+ api_token: str,+ endpoint: str,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[AwinResumeConfig],+ should_use_incremental_field: bool = False,+ db_incremental_field_last_value: Any = None,+ incremental_field: Optional[str] = None,+) -> Iterator[list[dict[str, Any]]]:+ config = AWIN_ENDPOINTS[endpoint]+ headers = _get_headers(api_token)+ # Register the token so the tracked transport masks it in logged URLs and captured samples.+ session = make_tracked_session(redact_values=(api_token,))++ if config.kind == "accounts":+ data = _fetch(session, config.path, headers, config.extra_params, logger)+ rows = _rows_from_response(config, data, publisher_id=None)+ if rows:+ yield rows+ return++ publisher_ids = _discover_publisher_ids(session, headers, logger)+ if not publisher_ids:+ logger.warning("Awin: no publisher accounts found for token; nothing to sync")+ return++ # Every account shares the same window list (it depends only on the cursor, not the account). We+ # iterate windows OUTER and accounts INNER so rows arrive in globally ascending date order across+ # all accounts — required for the `sort_mode="asc"` watermark to advance monotonically.+ windows = _windows_for_account(config, should_use_incremental_field, db_incremental_field_last_value)+ work_items = [(window, publisher_id) for window in windows for publisher_id in publisher_ids]++ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None+ start_index = _resume_index(work_items, resume)+ if start_index > 0:+ logger.debug(f"Awin: resuming {endpoint} from item {start_index}/{len(work_items)}")++ for window, publisher_id in work_items[start_index:]:+ params = config.extra_params if window is None else _build_window_params(config, *window, incremental_field)+ data = _fetch(session, config.path.format(publisher_id=publisher_id), headers, params, logger)+ rows = _rows_from_response(config, data, publisher_id)+ if rows:+ yield rows+ # Save after processing each work item. A crash before this line re-fetches the same item on+ # resume: if it yielded rows they're re-yielded and merge dedupes on the primary key; an empty+ # window is simply re-fetched (a no-op).+ resumable_source_manager.save_state(+ AwinResumeConfig(+ account_id=publisher_id,+ window_start=window[0].isoformat() if window is not None else None,+ )+ )+++def awin_source(+ api_token: str,+ endpoint: str,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[AwinResumeConfig],+ should_use_incremental_field: bool = False,+ db_incremental_field_last_value: Optional[Any] = None,+ incremental_field: Optional[str] = None,+) -> SourceResponse:+ config = AWIN_ENDPOINTS[endpoint]++ return SourceResponse(+ name=endpoint,+ items=lambda: get_rows(+ api_token=api_token,+ endpoint=endpoint,+ logger=logger,+ resumable_source_manager=resumable_source_manager,+ should_use_incremental_field=should_use_incremental_field,+ db_incremental_field_last_value=db_incremental_field_last_value,+ incremental_field=incremental_field,+ ),+ primary_keys=config.primary_keys,+ partition_mode="datetime" if config.partition_key else None,+ partition_format="month" if config.partition_key else None,+ partition_keys=[config.partition_key] if config.partition_key else None,+ )diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/awin/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/awin/canonical_descriptions.pynew file mode 100644index 000000000000..3e6492459c72--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/awin/canonical_descriptions.py@@ -0,0 +1,61 @@+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (+ CanonicalDescriptions,+)++CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {+ "accounts": {+ "description": "The publisher and advertiser accounts your Awin API token can access.",+ "docs_url": "https://wiki.awin.com/index.php/API_get_accounts",+ "columns": {+ "accountId": "Unique identifier for the account.",+ "accountName": "Human-readable name of the account.",+ "accountType": "Whether the account is a 'publisher' or an 'advertiser'.",+ "userRole": "Your user's role on the account (e.g. owner, viewer).",+ },+ },+ "programmes": {+ "description": "Advertiser programmes a publisher account has joined.",+ "docs_url": "https://wiki.awin.com/index.php/API_get_programmes",+ "columns": {+ "id": "Unique identifier of the advertiser programme.",+ "publisherId": "The publisher account this programme membership belongs to.",+ "name": "Name of the advertiser programme.",+ "currencyCode": "Currency the programme reports commissions in.",+ "status": "Relationship status between the publisher and the programme (e.g. active).",+ "primaryRegion": "The programme's primary operating region.",+ },+ },+ "transactions": {+ "description": "Individual affiliate transactions (sales and leads) recorded for a publisher account.",+ "docs_url": "https://wiki.awin.com/index.php/API_get_transactions_list",+ "columns": {+ "id": "Unique identifier for the transaction.",+ "publisherId": "Publisher account that earned the transaction.",+ "advertiserId": "Advertiser the transaction was placed with.",+ "commissionStatus": "Approval state of the commission (e.g. pending, approved, declined).",+ "transactionDate": "When the transaction occurred.",+ "validationDate": "When the transaction was validated/approved by the advertiser.",+ "clickDate": "When the click that led to the transaction happened.",+ "commissionAmount": "Commission earned, as an {amount, currency} object.",+ "saleAmount": "Order value that generated the commission, as an {amount, currency} object.",+ "type": "Transaction type (e.g. commission group transaction, bonus).",+ "voucherCode": "Voucher code used on the transaction, if any.",+ },+ },+ "reports_advertiser": {+ "description": "Performance metrics aggregated per advertiser over a trailing window, for a publisher account.",+ "docs_url": "https://wiki.awin.com/index.php/API_get_aggregated_reports_by_advertiser",+ "columns": {+ "advertiserId": "Advertiser the metrics are aggregated for.",+ "publisherId": "Publisher account the report was pulled for.",+ "impressions": "Number of impressions in the window.",+ "clicks": "Number of clicks in the window.",+ "pendingNo": "Count of pending transactions.",+ "confirmedNo": "Count of confirmed transactions.",+ "totalNo": "Total count of transactions.",+ "totalValue": "Total sale value across transactions.",+ "totalComm": "Total commission across transactions.",+ "currency": "Currency the monetary values are reported in.",+ },+ },+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/awin/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/awin/settings.pynew file mode 100644index 000000000000..77ae07362499--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/awin/settings.py@@ -0,0 +1,116 @@+from dataclasses import dataclass, field+from typing import Literal, Optional++from products.warehouse_sources.backend.types import IncrementalField, IncrementalFieldType++# Awin caps the transactions/report date windows at 31 days per request, so any range wider than+# this must be chunked. We use 30 to stay safely inside the (inclusive) limit.+MAX_WINDOW_DAYS = 30++# How far back the first transactions sync reaches when the user hasn't picked an incremental cursor+# yet (or on a full refresh). Bounds the initial backfill instead of walking all of history.+DEFAULT_BACKFILL_DAYS = 365++# Aggregated reports have no per-row timestamp to checkpoint on, so they're full-refresh snapshots+# over a fixed trailing window rather than an incremental scroll.+DEFAULT_REPORT_LOOKBACK_DAYS = 30++# `accounts` is a single top-level call; every other endpoint fans out over the publisher accounts+# the token can see (the publisherId is a path param).+AwinEndpointKind = Literal["accounts", "publisher_fanout"]+++@dataclass+class AwinEndpointConfig:+ name: str+ kind: AwinEndpointKind+ # Path relative to https://api.awin.com. `{publisher_id}` is substituted per account for fan-out+ # endpoints.+ path: str+ primary_keys: list[str]+ # For `accounts` the payload is wrapped as {"accounts": [...]}. Every other endpoint returns a+ # bare JSON array.+ data_key: Optional[str] = None+ # Inject the fan-out publisherId onto each row so the parent identifier is present in the table+ # (and in composite primary keys). Transactions/reports already carry publisherId, so only the+ # programmes endpoint needs it.+ inject_publisher_id: bool = False+ # Static query params sent on every request for this endpoint (e.g. the programmes relationship+ # filter).+ extra_params: dict[str, str] = field(default_factory=dict)+ # Whether the endpoint takes a startDate/endDate window. Transactions and reports do; accounts+ # and programmes don't.+ date_windowed: bool = False+ # Awin uses full ISO datetimes for transactions but date-only for the aggregated reports.+ date_format: str = "%Y-%m-%dT%H:%M:%S"+ incremental_fields: list[IncrementalField] = field(default_factory=list)+ # Maps the user-selected incremental field to Awin's `dateType` query param, which chooses which+ # timestamp the server windows on (transaction vs validation).+ date_type_by_field: dict[str, str] = field(default_factory=dict)+ partition_key: Optional[str] = None+ # Trailing window (in days) for full-refresh report snapshots. `None` for non-report endpoints.+ report_lookback_days: Optional[int] = None+ should_sync_default: bool = True+++AWIN_ENDPOINTS: dict[str, AwinEndpointConfig] = {+ "accounts": AwinEndpointConfig(+ name="accounts",+ kind="accounts",+ path="/accounts",+ data_key="accounts",+ primary_keys=["accountId"],+ ),+ "programmes": AwinEndpointConfig(+ name="programmes",+ kind="publisher_fanout",+ path="/publishers/{publisher_id}/programmes",+ primary_keys=["publisherId", "id"],+ inject_publisher_id=True,+ # Only the advertiser programmes the publisher has actually joined; the default (all+ # programmes in the network) would be enormous and mostly irrelevant.+ extra_params={"relationship": "joined"},+ ),+ "transactions": AwinEndpointConfig(+ name="transactions",+ kind="publisher_fanout",+ path="/publishers/{publisher_id}/transactions/",+ primary_keys=["id"],+ date_windowed=True,+ date_format="%Y-%m-%dT%H:%M:%S",+ incremental_fields=[+ {+ "label": "transactionDate",+ "type": IncrementalFieldType.DateTime,+ "field": "transactionDate",+ "field_type": IncrementalFieldType.DateTime,+ },+ {+ "label": "validationDate",+ "type": IncrementalFieldType.DateTime,+ "field": "validationDate",+ "field_type": IncrementalFieldType.DateTime,+ },+ ],+ date_type_by_field={"transactionDate": "transaction", "validationDate": "validation"},+ partition_key="transactionDate",+ ),+ "reports_advertiser": AwinEndpointConfig(+ name="reports_advertiser",+ kind="publisher_fanout",+ path="/publishers/{publisher_id}/reports/advertiser",+ # Aggregated per advertiser within the requested window; publisherId is injected so the same+ # advertiser under different publisher accounts stays distinct.+ primary_keys=["publisherId", "advertiserId"],+ inject_publisher_id=True,+ date_windowed=True,+ date_format="%Y-%m-%d",+ report_lookback_days=DEFAULT_REPORT_LOOKBACK_DAYS,+ ),+}++ENDPOINTS = tuple(AWIN_ENDPOINTS.keys())++INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {+ name: config.incremental_fields for name, config in AWIN_ENDPOINTS.items()+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/awin/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/awin/source.pyindex 7307ab5636d4..ce24472c4873 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/awin/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/awin/source.py@@ -1,19 +1,43 @@-from typing import cast+from typing import Optional, castfrom posthog.schema import (DataWarehouseSourceCategory,ExternalDataSourceType as SchemaExternalDataSourceType,+ ReleaseStatus,SourceConfig,+ SourceFieldInputConfig,+ SourceFieldInputConfigType,)-from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, SimpleSource+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import (+ SourceInputs,+ SourceResponse,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.awin.awin import (+ AwinResumeConfig,+ awin_source,+ validate_credentials as validate_awin_credentials,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.awin.settings import (+ AWIN_ENDPOINTS,+ ENDPOINTS,+ INCREMENTAL_FIELDS,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, ResumableSource+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (+ CanonicalDescriptions,+)from products.warehouse_sources.backend.temporal.data_imports.sources.common.registry import SourceRegistry+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from products.warehouse_sources.backend.temporal.data_imports.sources.common.schema import SourceSchemafrom products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs import AwinSourceConfigfrom products.warehouse_sources.backend.types import ExternalDataSourceType@SourceRegistry.register-class AwinSource(SimpleSource[AwinSourceConfig]):+class AwinSource(ResumableSource[AwinSourceConfig, AwinResumeConfig]):+ lists_tables_without_credentials = True # static endpoint catalog — safe for public docs+@propertydef source_type(self) -> ExternalDataSourceType:return ExternalDataSourceType.AWIN@@ -23,8 +47,99 @@ class AwinSource(SimpleSource[AwinSourceConfig]):return SourceConfig(name=SchemaExternalDataSourceType.AWIN,category=DataWarehouseSourceCategory.ADVERTISING,- label="AWIN",- iconPath="/static/services/awin.png",- fields=cast(list[FieldType], []),+ label="Awin",+ releaseStatus=ReleaseStatus.ALPHA,unreleasedSource=True,+ caption="""Enter your Awin API token to pull your Awin affiliate data into the PostHog Data warehouse.++Create a personal OAuth2 token from the [Awin API settings](https://ui.awin.com/awin-api). The same token grants access to every publisher account your user can see.""",+ iconPath="/static/services/awin.png",+ docsUrl="https://posthog.com/docs/cdp/sources/awin",+ fields=cast(+ list[FieldType],+ [+ SourceFieldInputConfig(+ name="api_token",+ label="API token",+ type=SourceFieldInputConfigType.PASSWORD,+ required=True,+ placeholder="",+ secret=True,+ ),+ ],+ ),+ )++ def get_canonical_descriptions(self) -> CanonicalDescriptions:+ from products.warehouse_sources.backend.temporal.data_imports.sources.awin.canonical_descriptions import (+ CANONICAL_DESCRIPTIONS,+ )++ return CANONICAL_DESCRIPTIONS++ def get_non_retryable_errors(self) -> dict[str, str | None]:+ return {+ "401 Client Error: Unauthorized for url: https://api.awin.com": "Your Awin API token is invalid or has expired. Create a new token in your Awin API settings, then reconnect.",+ "403 Client Error: Forbidden for url: https://api.awin.com": "Your Awin API token does not have access to this data. Check the token's account permissions, then reconnect.",+ }++ def get_schemas(+ self,+ config: AwinSourceConfig,+ team_id: int,+ with_counts: bool = False,+ names: list[str] | None = None,+ force_refresh: bool = False,+ ) -> list[SourceSchema]:+ def _description(endpoint: str) -> str | None:+ if endpoint == "reports_advertiser":+ return "Full refresh only. A rolling snapshot of the last 30 days of performance, aggregated per advertiser"+ if endpoint == "transactions":+ return "Only syncs the last 365 days on initial sync"+ return None++ def _build_schema(endpoint: str) -> SourceSchema:+ has_incremental = bool(INCREMENTAL_FIELDS.get(endpoint))+ return SourceSchema(+ name=endpoint,+ supports_incremental=has_incremental,+ supports_append=has_incremental,+ incremental_fields=INCREMENTAL_FIELDS.get(endpoint, []),+ should_sync_default=AWIN_ENDPOINTS[endpoint].should_sync_default,+ description=_description(endpoint),+ )++ schemas = [_build_schema(endpoint) for endpoint in ENDPOINTS]+ if names is not None:+ names_set = set(names)+ schemas = [s for s in schemas if s.name in names_set]+ return schemas++ def validate_credentials(+ self, config: AwinSourceConfig, team_id: int, schema_name: Optional[str] = None+ ) -> tuple[bool, str | None]:+ if validate_awin_credentials(config.api_token):+ return True, None++ return False, "Invalid Awin API token"++ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[AwinResumeConfig]:+ return ResumableSourceManager[AwinResumeConfig](inputs, AwinResumeConfig)++ def source_for_pipeline(+ self,+ config: AwinSourceConfig,+ resumable_source_manager: ResumableSourceManager[AwinResumeConfig],+ inputs: SourceInputs,+ ) -> SourceResponse:+ return awin_source(+ api_token=config.api_token,+ endpoint=inputs.schema_name,+ logger=inputs.logger,+ resumable_source_manager=resumable_source_manager,+ should_use_incremental_field=inputs.should_use_incremental_field,+ db_incremental_field_last_value=inputs.db_incremental_field_last_value+ if inputs.should_use_incremental_field+ else None,+ incremental_field=inputs.incremental_field,)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/awin/tests/test_awin.py b/products/warehouse_sources/backend/temporal/data_imports/sources/awin/tests/test_awin.pynew file mode 100644index 000000000000..806ece7aa086--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/awin/tests/test_awin.py@@ -0,0 +1,330 @@+from datetime import UTC, datetime+from typing import Any, Optional++from freezegun import freeze_time+from unittest.mock import MagicMock, patch++from parameterized import parameterized++from products.warehouse_sources.backend.temporal.data_imports.sources.awin import awin+from products.warehouse_sources.backend.temporal.data_imports.sources.awin.awin import (+ AwinResumeConfig,+ _build_window_params,+ _discover_publisher_ids,+ _iter_windows,+ _rows_from_response,+ _to_datetime,+ _windows_for_account,+ awin_source,+ get_rows,+ validate_credentials,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.awin.settings import AWIN_ENDPOINTS+++def _counts(values: list[str]) -> dict[str, int]:+ counts: dict[str, int] = {}+ for value in values:+ counts[value] = counts.get(value, 0) + 1+ return counts+++class FakeResumableManager:+ """Minimal stand-in for ResumableSourceManager that records saved state in memory."""++ def __init__(self, state: Optional[AwinResumeConfig] = None):+ self.state = state+ self.saved: list[AwinResumeConfig] = []++ def can_resume(self) -> bool:+ return self.state is not None++ def load_state(self) -> Optional[AwinResumeConfig]:+ return self.state++ def save_state(self, data: AwinResumeConfig) -> None:+ self.saved.append(data)+++class TestIterWindows:+ def test_range_shorter_than_max_is_single_window(self) -> None:+ start = datetime(2024, 1, 1, tzinfo=UTC)+ end = datetime(2024, 1, 10, tzinfo=UTC)+ windows = list(_iter_windows(start, end, max_days=30))+ assert windows == [(start, end)]++ def test_range_is_chunked_and_ascending_and_contiguous(self) -> None:+ start = datetime(2024, 1, 1, tzinfo=UTC)+ end = datetime(2024, 3, 15, tzinfo=UTC)+ windows = list(_iter_windows(start, end, max_days=30))++ assert len(windows) == 3+ assert windows[0][0] == start+ assert windows[-1][1] == end+ # Contiguous, each no wider than 30 days, strictly ascending.+ for i, (ws, we) in enumerate(windows):+ assert ws < we+ assert (we - ws).days <= 30+ if i > 0:+ assert ws == windows[i - 1][1]+++class TestToDatetime:+ @parameterized.expand(+ [+ ("none", None, None),+ ("naive_string", "2024-01-01T00:00:00", datetime(2024, 1, 1, tzinfo=UTC)),+ ("z_string", "2024-01-01T00:00:00Z", datetime(2024, 1, 1, tzinfo=UTC)),+ ("garbage", "not-a-date", None),+ ]+ )+ def test_to_datetime(self, _name: str, value: Any, expected: Optional[datetime]) -> None:+ assert _to_datetime(value) == expected++ def test_naive_datetime_gets_utc(self) -> None:+ assert _to_datetime(datetime(2024, 1, 1)) == datetime(2024, 1, 1, tzinfo=UTC)+++class TestWindowsForAccount:+ def test_non_windowed_endpoint_is_single_none(self) -> None:+ windows = _windows_for_account(AWIN_ENDPOINTS["programmes"], False, None)+ assert windows == [None]++ @freeze_time("2024-06-01")+ def test_reports_use_lookback_window_regardless_of_incremental(self) -> None:+ windows = _windows_for_account(AWIN_ENDPOINTS["reports_advertiser"], True, datetime(2020, 1, 1, tzinfo=UTC))+ # 30-day rolling snapshot ending now, not the stale 2020 cursor.+ assert windows is not None and len(windows) == 1+ assert windows[0] is not None+ assert windows[0][0] == datetime(2024, 5, 2, tzinfo=UTC)+ assert windows[0][1] == datetime(2024, 6, 1, tzinfo=UTC)++ @freeze_time("2024-06-01")+ def test_transactions_incremental_windows_start_at_last_value(self) -> None:+ last_value = datetime(2024, 5, 15, tzinfo=UTC)+ windows = _windows_for_account(AWIN_ENDPOINTS["transactions"], True, last_value)+ assert windows[0] is not None+ assert windows[0][0] == last_value++ @freeze_time("2024-06-01")+ def test_transactions_full_refresh_backfills(self) -> None:+ windows = _windows_for_account(AWIN_ENDPOINTS["transactions"], False, None)+ # 365-day backfill chunked into 30-day windows.+ assert windows[0] is not None+ assert windows[0][0] == datetime(2023, 6, 2, tzinfo=UTC)+ assert len(windows) >= 12++ @freeze_time("2024-06-01")+ def test_future_cursor_yields_no_windows(self) -> None:+ windows = _windows_for_account(AWIN_ENDPOINTS["transactions"], True, datetime(2025, 1, 1, tzinfo=UTC))+ assert windows == []+++class TestBuildWindowParams:+ def test_transactions_datetime_format_and_date_type(self) -> None:+ params = _build_window_params(+ AWIN_ENDPOINTS["transactions"],+ datetime(2024, 1, 1, tzinfo=UTC),+ datetime(2024, 1, 31, tzinfo=UTC),+ incremental_field="transactionDate",+ )+ assert params["startDate"] == "2024-01-01T00:00:00"+ assert params["endDate"] == "2024-01-31T00:00:00"+ assert params["timezone"] == "UTC"+ assert params["dateType"] == "transaction"++ def test_transactions_validation_date_maps_to_validation_date_type(self) -> None:+ params = _build_window_params(+ AWIN_ENDPOINTS["transactions"],+ datetime(2024, 1, 1, tzinfo=UTC),+ datetime(2024, 1, 31, tzinfo=UTC),+ incremental_field="validationDate",+ )+ assert params["dateType"] == "validation"++ def test_reports_use_date_only_format_and_no_date_type(self) -> None:+ params = _build_window_params(+ AWIN_ENDPOINTS["reports_advertiser"],+ datetime(2024, 1, 1, tzinfo=UTC),+ datetime(2024, 1, 31, tzinfo=UTC),+ incremental_field=None,+ )+ assert params["startDate"] == "2024-01-01"+ assert params["endDate"] == "2024-01-31"+ assert "dateType" not in params+++class TestRowsFromResponse:+ def test_accounts_reads_wrapped_key(self) -> None:+ data = {"accounts": [{"accountId": 1}, {"accountId": 2}]}+ rows = _rows_from_response(AWIN_ENDPOINTS["accounts"], data, publisher_id=None)+ assert rows == [{"accountId": 1}, {"accountId": 2}]++ def test_bare_list_endpoint(self) -> None:+ data = [{"id": 1}, {"id": 2}]+ rows = _rows_from_response(AWIN_ENDPOINTS["transactions"], data, publisher_id=99)+ assert rows == [{"id": 1}, {"id": 2}]++ def test_inject_publisher_id_when_configured(self) -> None:+ data = [{"id": 1}]+ rows = _rows_from_response(AWIN_ENDPOINTS["programmes"], data, publisher_id=42)+ assert rows == [{"id": 1, "publisherId": 42}]++ def test_inject_does_not_overwrite_existing_publisher_id(self) -> None:+ data = [{"id": 1, "publisherId": 7}]+ rows = _rows_from_response(AWIN_ENDPOINTS["programmes"], data, publisher_id=42)+ assert rows == [{"id": 1, "publisherId": 7}]++ def test_non_dict_rows_are_dropped(self) -> None:+ data = [{"id": 1}, "junk", None]+ rows = _rows_from_response(AWIN_ENDPOINTS["transactions"], data, publisher_id=1)+ assert rows == [{"id": 1}]+++class TestDiscoverPublisherIds:+ def test_filters_publisher_accounts_and_sorts_and_dedupes(self) -> None:+ with patch.object(awin, "_fetch") as mock_fetch:+ mock_fetch.return_value = {+ "accounts": [+ {"accountId": 3, "accountType": "publisher"},+ {"accountId": 1, "accountType": "publisher"},+ {"accountId": 2, "accountType": "advertiser"},+ {"accountId": 1, "accountType": "publisher"},+ ]+ }+ ids = _discover_publisher_ids(MagicMock(), {}, MagicMock())+ assert ids == [1, 3]+++class TestValidateCredentials:+ @parameterized.expand([("ok", 200, True), ("unauthorized", 401, False), ("forbidden", 403, False)])+ def test_status_maps_to_bool(self, _name: str, status: int, expected: bool) -> None:+ with patch.object(awin, "make_tracked_session") as mock_session:+ response = MagicMock()+ response.status_code = status+ mock_session.return_value.get.return_value = response+ assert validate_credentials("token") is expected++ def test_exception_is_false(self) -> None:+ with patch.object(awin, "make_tracked_session") as mock_session:+ mock_session.return_value.get.side_effect = Exception("boom")+ assert validate_credentials("token") is False+++class TestGetRows:+ def test_accounts_endpoint_yields_accounts_without_fanout(self) -> None:+ manager = FakeResumableManager()+ with (+ patch.object(awin, "make_tracked_session"),+ patch.object(awin, "_fetch", return_value={"accounts": [{"accountId": 1}]}) as mock_fetch,+ ):+ batches = list(get_rows("token", "accounts", MagicMock(), manager)) # type: ignore[arg-type]++ assert batches == [[{"accountId": 1}]]+ # A single call to /accounts, no per-publisher fan-out.+ assert mock_fetch.call_count == 1++ @freeze_time("2024-06-01")+ def test_fanout_yields_per_account_and_saves_state(self) -> None:+ manager = FakeResumableManager()++ def fake_fetch(session: Any, path: str, headers: Any, params: Any, logger: Any) -> Any:+ if path == "/accounts":+ return {+ "accounts": [+ {"accountId": 10, "accountType": "publisher"},+ {"accountId": 20, "accountType": "publisher"},+ ]+ }+ return [{"id": 1, "publisherId": 999}]++ with patch.object(awin, "make_tracked_session"), patch.object(awin, "_fetch", side_effect=fake_fetch):+ batches = list(get_rows("token", "programmes", MagicMock(), manager)) # type: ignore[arg-type]++ # One batch per publisher account, publisherId injected only when absent.+ assert len(batches) == 2+ assert {row["publisherId"] for batch in batches for row in batch} == {999}+ # State saved after each account so a crash resumes at the right one.+ assert [s.account_id for s in manager.saved] == [10, 20]++ @freeze_time("2024-06-01")+ def test_resume_skips_already_synced_accounts(self) -> None:+ manager = FakeResumableManager(state=AwinResumeConfig(account_id=20, window_start=None))+ fetched_publishers: list[int] = []++ def fake_fetch(session: Any, path: str, headers: Any, params: Any, logger: Any) -> Any:+ if path == "/accounts":+ return {+ "accounts": [+ {"accountId": 10, "accountType": "publisher"},+ {"accountId": 20, "accountType": "publisher"},+ {"accountId": 30, "accountType": "publisher"},+ ]+ }+ fetched_publishers.append(int(path.split("/")[2]))+ return [{"id": 1}]++ with patch.object(awin, "make_tracked_session"), patch.object(awin, "_fetch", side_effect=fake_fetch):+ list(get_rows("token", "programmes", MagicMock(), manager)) # type: ignore[arg-type]++ # Account 10 already synced before the crash; resume starts at 20.+ assert fetched_publishers == [20, 30]++ @freeze_time("2024-06-01")+ def test_windowed_fanout_arrives_in_globally_ascending_order(self) -> None:+ # Two accounts, multiple 30-day windows each. To keep the asc watermark monotonic, every+ # account's window N must be fetched before any account's window N+1 (windows OUTER, accounts+ # INNER) — not one account fully before the next.+ manager = FakeResumableManager()+ seen_starts: list[str] = []++ def fake_fetch(session: Any, path: str, headers: Any, params: Any, logger: Any) -> Any:+ if path == "/accounts":+ return {+ "accounts": [+ {"accountId": 10, "accountType": "publisher"},+ {"accountId": 20, "accountType": "publisher"},+ ]+ }+ seen_starts.append(params["startDate"])+ return [{"id": 1}]++ with patch.object(awin, "make_tracked_session"), patch.object(awin, "_fetch", side_effect=fake_fetch):+ list(get_rows("token", "transactions", MagicMock(), manager, should_use_incremental_field=False)) # type: ignore[arg-type]++ # startDate is non-decreasing across the whole run despite fanning out over two accounts.+ assert seen_starts == sorted(seen_starts)+ # Each window's startDate appears once per account (two accounts).+ assert all(count == 2 for count in _counts(seen_starts).values())++ @freeze_time("2024-06-01")+ def test_no_publisher_accounts_yields_nothing(self) -> None:+ manager = FakeResumableManager()+ with (+ patch.object(awin, "make_tracked_session"),+ patch.object(awin, "_fetch", return_value={"accounts": []}),+ ):+ batches = list(get_rows("token", "programmes", MagicMock(), manager)) # type: ignore[arg-type]+ assert batches == []+++class TestAwinSource:+ @parameterized.expand(+ [+ ("accounts", ["accountId"], None),+ ("programmes", ["publisherId", "id"], None),+ ("transactions", ["id"], "transactionDate"),+ ("reports_advertiser", ["publisherId", "advertiserId"], None),+ ]+ )+ def test_source_response_shape(self, endpoint: str, expected_pks: list[str], partition_key: Optional[str]) -> None:+ response = awin_source("token", endpoint, MagicMock(), FakeResumableManager()) # type: ignore[arg-type]+ assert response.name == endpoint+ assert response.primary_keys == expected_pks+ if partition_key:+ assert response.partition_mode == "datetime"+ assert response.partition_keys == [partition_key]+ assert response.partition_format == "month"+ else:+ assert response.partition_mode is None+ assert response.partition_keys is Nonediff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/awin/tests/test_awin_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/awin/tests/test_awin_source.pynew file mode 100644index 000000000000..8d5419aca642--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/awin/tests/test_awin_source.py@@ -0,0 +1,108 @@+from typing import Optional++from unittest.mock import MagicMock, patch++from parameterized import parameterized++from posthog.schema import SourceFieldInputConfig, SourceFieldInputConfigType++from products.warehouse_sources.backend.temporal.data_imports.sources.awin import source as source_module+from products.warehouse_sources.backend.temporal.data_imports.sources.awin.awin import AwinResumeConfig+from products.warehouse_sources.backend.temporal.data_imports.sources.awin.source import AwinSource+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 AwinSourceConfig+from products.warehouse_sources.backend.types import ExternalDataSourceType+++def _inputs(schema_name: str = "transactions", **overrides: object) -> MagicMock:+ inputs = MagicMock()+ inputs.schema_name = schema_name+ inputs.should_use_incremental_field = overrides.get("should_use_incremental_field", True)+ inputs.db_incremental_field_last_value = overrides.get("db_incremental_field_last_value", "2024-01-01T00:00:00")+ inputs.incremental_field = overrides.get("incremental_field", "transactionDate")+ return inputs+++class TestAwinSourceClass:+ def test_source_type(self) -> None:+ assert AwinSource().source_type == ExternalDataSourceType.AWIN++ def test_get_source_config_fields(self) -> None:+ config = AwinSource().get_source_config+ assert config.name.value == "Awin"+ assert len(config.fields) == 1+ field = config.fields[0]+ assert isinstance(field, SourceFieldInputConfig)+ assert field.name == "api_token"+ assert field.type == SourceFieldInputConfigType.PASSWORD+ assert field.required is True+ assert field.secret is True+ assert config.docsUrl == "https://posthog.com/docs/cdp/sources/awin"++ def test_lists_tables_without_credentials(self) -> None:+ assert AwinSource.lists_tables_without_credentials is True++ def test_get_schemas_returns_all_endpoints(self) -> None:+ schemas = AwinSource().get_schemas(AwinSourceConfig(api_token="x"), team_id=1)+ names = {s.name for s in schemas}+ assert names == {"accounts", "programmes", "transactions", "reports_advertiser"}++ @parameterized.expand(+ [+ ("transactions", True),+ ("accounts", False),+ ("programmes", False),+ ("reports_advertiser", False),+ ]+ )+ def test_supports_incremental_per_endpoint(self, endpoint: str, expected: bool) -> None:+ schemas = AwinSource().get_schemas(AwinSourceConfig(api_token="x"), team_id=1, names=[endpoint])+ assert len(schemas) == 1+ assert schemas[0].supports_incremental is expected++ def test_transactions_advertises_both_date_fields(self) -> None:+ schemas = AwinSource().get_schemas(AwinSourceConfig(api_token="x"), team_id=1, names=["transactions"])+ fields = {f["field"] for f in schemas[0].incremental_fields}+ assert fields == {"transactionDate", "validationDate"}++ def test_documented_tables_render_without_credentials(self) -> None:+ tables = AwinSource().get_documented_tables()+ names = {t["name"] for t in tables}+ assert names == {"accounts", "programmes", "transactions", "reports_advertiser"}++ @parameterized.expand([("valid", True, True, None), ("invalid", False, False, "Invalid Awin API token")])+ def test_validate_credentials(self, _name: str, api_result: bool, ok: bool, err: Optional[str]) -> None:+ with patch.object(source_module, "validate_awin_credentials", return_value=api_result):+ result = AwinSource().validate_credentials(AwinSourceConfig(api_token="x"), team_id=1)+ assert result == (ok, err)++ def test_get_non_retryable_errors_cover_auth(self) -> None:+ errors = AwinSource().get_non_retryable_errors()+ assert any("401" in key for key in errors)+ assert any("403" in key for key in errors)++ def test_get_resumable_source_manager_bound_to_data_class(self) -> None:+ manager = AwinSource().get_resumable_source_manager(_inputs())+ assert isinstance(manager, ResumableSourceManager)+ assert manager._data_class is AwinResumeConfig++ def test_source_for_pipeline_plumbs_arguments(self) -> None:+ manager = MagicMock()+ inputs = _inputs(schema_name="transactions")+ with patch.object(source_module, "awin_source") as mock_awin_source:+ AwinSource().source_for_pipeline(AwinSourceConfig(api_token="tok"), manager, inputs)++ mock_awin_source.assert_called_once()+ kwargs = mock_awin_source.call_args.kwargs+ assert kwargs["api_token"] == "tok"+ assert kwargs["endpoint"] == "transactions"+ assert kwargs["incremental_field"] == "transactionDate"+ assert kwargs["db_incremental_field_last_value"] == "2024-01-01T00:00:00"++ def test_source_for_pipeline_drops_last_value_when_not_incremental(self) -> None:+ manager = MagicMock()+ inputs = _inputs(should_use_incremental_field=False)+ with patch.object(source_module, "awin_source") as mock_awin_source:+ AwinSource().source_for_pipeline(AwinSourceConfig(api_token="tok"), manager, inputs)++ assert mock_awin_source.call_args.kwargs["db_incremental_field_last_value"] is Nonediff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.py b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.pyindex dfd7e5fb41b5..fe2ebe24ca17 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.py@@ -362,7 +362,7 @@ class AviationstackSourceConfig(config.Config):@config.configclass AwinSourceConfig(config.Config):- pass+ api_token: str@config.config