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(awin): sync advertiser-side reports and programme lookups (#99679)

Tom Owers397af829af99
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.md b/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.md
index a3f39837d00a..533d2da8bbbe 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.md
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.md
@@ -644,14 +644,14 @@ Note: Aviator also ships a GraphQL API for pull request data at https://app.avia
## Awin — gaps
-Today (4): `accounts`, `programmes`, `reports_advertiser`, `transactions`
+Today (8): `accounts`, `advertiser_publishers`, `commission_groups`, `programme_details`, `programmes`, `reports_advertiser`, `reports_publisher`, `transactions`
Diffed against: <https://help.awin.com/llms.txt>
-- [ ] `GET publisher performance report (advertiser)` — per-publisher clicks/sales/commission breakdown - the headline advertiser metric and the counterpart to the advertiser report we already sync (high)
-- [ ] `GET publishers information for advertiser` — lookup table resolving the publisherId on every transaction and performance row (high)
-- [ ] `GET commission groups for an advertiser` — lookup resolving the commissionGroupId carried on transactions (high)
-- [ ] `GET programme details for publisher` — commission ranges, currency and terms per programme; programmes table only carries the summary (high)
+- [x] `GET publisher performance report (advertiser)` — per-publisher clicks/sales/commission breakdown - the headline advertiser metric and the counterpart to the advertiser report we already sync (high)
+- [x] `GET publishers information for advertiser` — lookup table resolving the publisherId on every transaction and performance row (high)
+- [x] `GET commission groups for an advertiser` — lookup resolving the commissionGroupId carried on transactions (high)
+- [x] `GET programme details for publisher` — commission ranges, currency and terms per programme; programmes table only carries the summary (high)
- [ ] `GET campaign performance report (publisher and advertiser)` — revenue and clicks broken down by campaign - a core reporting dimension we do not expose (medium)
- [ ] `GET creative performance report (publisher and advertiser)` — performance by creative/banner, the other main report dimension (medium)
- [ ] `GET transaction queries for a publisher` — dispute/query state on transactions - transition history for revenue we already sync (medium)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/awin/awin.py b/products/warehouse_sources/backend/temporal/data_imports/sources/awin/awin.py
index 7237f7f033ac..b98caf993afc 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/awin/awin.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/awin/awin.py
@@ -1,4 +1,3 @@
-import dataclasses
from collections.abc import Iterator
from datetime import UTC, date, datetime, timedelta
from typing import Any, Optional
@@ -8,6 +7,8 @@ import requests
from structlog.types import FilteringBoundLogger
from tenacity import retry, retry_if_exception_type, stop_after_attempt, wait_exponential_jitter
+from posthog.dataclasses import frozen
+
from products.warehouse_sources.backend.temporal.data_imports.sources.awin.settings import (
AWIN_ENDPOINTS,
DEFAULT_BACKFILL_DAYS,
@@ -31,15 +32,29 @@ class AwinRetryableError(Exception):
"""Transient Awin API failure (429 throttling or 5xx) worth retrying."""
+@frozen
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.
+ # The fan-out target last processed. A stable id bookmark (not a positional index) so accounts
+ # added or removed between a crash and the retry can't resume us into the wrong one.
+ publisher_id: Optional[int] = None
+ advertiser_id: Optional[int] = None
+ # ISO start of the date window last yielded for that target. `None` for non-windowed endpoints.
window_start: Optional[str] = None
+@frozen
+class AwinFanoutTarget:
+ """One unit of fan-out work: the ids that select the rows for a single request.
+
+ A publisher endpoint sets only `publisher_id` and an advertiser endpoint only `advertiser_id`.
+ The programme-scoped endpoints set both, because they sit on a publisher path and take the
+ advertiser as a query param.
+ """
+
+ publisher_id: Optional[int] = None
+ advertiser_id: Optional[int] = None
+
+
def _get_headers(api_token: str) -> dict[str, str]:
return {
"Authorization": f"Bearer {api_token}",
@@ -93,22 +108,61 @@ def validate_credentials(api_token: str) -> bool:
return False
-def _discover_publisher_ids(
- session: requests.Session, headers: dict[str, str], logger: FilteringBoundLogger
+def _discover_account_ids(
+ session: requests.Session, headers: dict[str, str], logger: FilteringBoundLogger, account_type: str
) -> list[int]:
- """Return the publisher account ids the token can access, sorted for deterministic fan-out order.
+ """Return the account ids of `account_type` the token can access, sorted for deterministic fan-out.
- Awin exposes both publisher and advertiser accounts through /accounts; every endpoint this source
- implements is publisher-scoped, so we keep only the publisher accounts.
+ Awin exposes both publisher and advertiser accounts through /accounts, and an endpoint is scoped
+ to one or the other, so each fan-out keeps only the accounts its path can address.
"""
data = _fetch(session, "/accounts", headers, {}, logger)
accounts = data.get("accounts", []) if isinstance(data, dict) else []
- publisher_ids = [
+ account_ids = [
account["accountId"]
for account in accounts
- if account.get("accountType") == "publisher" and account.get("accountId") is not None
+ if account.get("accountType") == account_type and account.get("accountId") is not None
+ ]
+ return sorted(set(account_ids))
+
+
+def _discover_joined_advertiser_ids(
+ session: requests.Session, headers: dict[str, str], logger: FilteringBoundLogger, publisher_id: int
+) -> list[int]:
+ """Return the advertiser ids of the programmes `publisher_id` has joined.
+
+ `commissiongroups` and `programmedetails` sit on a publisher path but still require an
+ advertiserId, so the joined programmes list is what bounds their fan-out.
+ """
+ programmes = AWIN_ENDPOINTS["programmes"]
+ data = _fetch(session, programmes.path.format(publisher_id=publisher_id), headers, programmes.extra_params, logger)
+ rows = data if isinstance(data, list) else []
+ advertiser_ids = [row["id"] for row in rows if isinstance(row, dict) and row.get("id") is not None]
+ return sorted(set(advertiser_ids))
+
+
+def _fanout_targets(
+ config: AwinEndpointConfig, session: requests.Session, headers: dict[str, str], logger: FilteringBoundLogger
+) -> list[AwinFanoutTarget]:
+ if config.kind == "advertiser_fanout":
+ return [
+ AwinFanoutTarget(advertiser_id=advertiser_id)
+ for advertiser_id in _discover_account_ids(session, headers, logger, "advertiser")
+ ]
+
+ publisher_ids = _discover_account_ids(session, headers, logger, "publisher")
+ if config.kind == "publisher_fanout":
+ return [AwinFanoutTarget(publisher_id=publisher_id) for publisher_id in publisher_ids]
+
+ return [
+ AwinFanoutTarget(publisher_id=publisher_id, advertiser_id=advertiser_id)
+ for publisher_id in publisher_ids
+ for advertiser_id in _discover_joined_advertiser_ids(session, headers, logger, publisher_id)
]
- return sorted(set(publisher_ids))
+
+
+def _format_path(config: AwinEndpointConfig, target: AwinFanoutTarget) -> str:
+ return config.path.format(publisher_id=target.publisher_id, advertiser_id=target.advertiser_id)
def _to_datetime(value: Any) -> Optional[datetime]:
@@ -184,23 +238,35 @@ def _windows_for_account(
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:
+def _rows_from_response(
+ config: AwinEndpointConfig, data: Any, target: Optional[AwinFanoutTarget] = None
+) -> list[dict[str, Any]]:
+ if config.single_row:
+ rows = [data] if isinstance(data, dict) else []
+ elif 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)
+
+ envelope = {key: data[key] for key in config.envelope_keys if key in data} if isinstance(data, dict) else {}
+ for row in rows:
+ for key, value in envelope.items():
+ row.setdefault(key, value)
+ if target is None:
+ continue
+ if config.inject_publisher_id and target.publisher_id is not None:
+ row.setdefault("publisherId", target.publisher_id)
+ if config.inject_advertiser_id and target.advertiser_id is not None:
+ row.setdefault("advertiserId", target.advertiser_id)
return rows
def _resume_index(
- work_items: list[tuple[Optional[tuple[datetime, datetime]], int]], resume: Optional[AwinResumeConfig]
+ work_items: list[tuple[Optional[tuple[datetime, datetime]], AwinFanoutTarget]], resume: Optional[AwinResumeConfig]
) -> int:
- """Find where to restart the (window, account) work list from a saved bookmark.
+ """Find where to restart the (window, target) 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
@@ -208,9 +274,13 @@ def _resume_index(
"""
if resume is None:
return 0
- for index, (window, publisher_id) in enumerate(work_items):
+ for index, (window, target) 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:
+ if (
+ target.publisher_id == resume.publisher_id
+ and target.advertiser_id == resume.advertiser_id
+ and window_start == resume.window_start
+ ):
return index
return 0
@@ -232,33 +302,38 @@ def get_rows(
if config.kind == "accounts":
data = _fetch(session, config.path, headers, config.extra_params, logger)
- rows = _rows_from_response(config, data, publisher_id=None)
+ rows = _rows_from_response(config, data)
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")
+ targets = _fanout_targets(config, session, headers, logger)
+ if not targets:
+ logger.warning(f"Awin: no accounts the token can reach for {endpoint}; 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
+ # Every target shares the same window list (it depends only on the cursor, not the account). We
+ # iterate windows OUTER and targets 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]
+ work_items = [(window, target) for window in windows for target in targets]
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:]:
+ for window, target in work_items[start_index:]:
params = (
- config.extra_params if window is None else _build_window_params(config, *window, incremental_field, region)
+ dict(config.extra_params)
+ if window is None
+ else _build_window_params(config, *window, incremental_field, region)
)
- data = _fetch(session, config.path.format(publisher_id=publisher_id), headers, params, logger)
- rows = _rows_from_response(config, data, publisher_id)
+ if config.kind == "publisher_programme_fanout":
+ params["advertiserId"] = str(target.advertiser_id)
+
+ data = _fetch(session, _format_path(config, target), headers, params, logger)
+ rows = _rows_from_response(config, data, target)
if rows:
yield rows
# Save after processing each work item. A crash before this line re-fetches the same item on
@@ -266,7 +341,8 @@ def get_rows(
# window is simply re-fetched (a no-op).
resumable_source_manager.save_state(
AwinResumeConfig(
- account_id=publisher_id,
+ publisher_id=target.publisher_id,
+ advertiser_id=target.advertiser_id,
window_start=window[0].isoformat() if window is not None 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.py
index 3e6492459c72..3860868d8cab 100644
--- 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.py
@@ -58,4 +58,75 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
"currency": "Currency the monetary values are reported in.",
},
},
+ "programme_details": {
+ "description": "Per-programme detail for a publisher account: commission ranges across commission groups, KPIs, and the programme's own metadata.",
+ "docs_url": "https://help.awin.com/apidocs/get-program-information-details-for-publisher",
+ "columns": {
+ "publisherId": "Publisher account the detail was pulled for.",
+ "advertiserId": "Advertiser programme the detail describes.",
+ "commissionRange": "Min and max commission per type across the programme's commission groups.",
+ "kpi": "Programme KPIs: approval percentage, average payment time, Awin index, conversion rate, EPC and validation days.",
+ "programmeInfo": "Programme metadata: name, description, currency code, membership status, primary region and sector, valid domains, and deeplink support.",
+ },
+ },
+ "commission_groups": {
+ "description": "Commission groups of an advertiser programme, with the rates the publisher account earns in each.",
+ "docs_url": "https://help.awin.com/apidocs/gets-an-array-of-commission-groups-for-an-advertiser",
+ "columns": {
+ "publisherId": "Publisher account the rates apply to.",
+ "advertiserId": "Advertiser programme the commission group belongs to.",
+ "groupId": "Unique identifier of the commission group, unique even across advertisers. Joins to commissionGroupId on transactions.",
+ "groupCode": "Advertiser-assigned code for the group. Not necessarily unique across advertisers.",
+ "groupName": "Human-readable name of the commission group.",
+ "type": "Whether the commission is a 'fix' amount or a 'percentage'.",
+ "amount": "Fixed commission amount. Only set when type is 'fix'.",
+ "currency": "Currency of the fixed amount. Only set when type is 'fix'.",
+ "percentage": "Commission percentage. Only set when type is 'percentage'.",
+ "conditions": "Conditions that must hold for the group's rate to apply, as {operator, type, values} objects.",
+ "ratesStart": "When this set of rates takes effect.",
+ "ratesEnd": "When this set of rates stops applying. Omitted while the rates are ongoing.",
+ },
+ },
+ "reports_publisher": {
+ "description": "Performance metrics aggregated per publisher over a trailing window, for an advertiser account. Publishers with no activity in the window are omitted.",
+ "docs_url": "https://help.awin.com/apidocs/get-publisher-performance-report",
+ "columns": {
+ "advertiserId": "Advertiser account the report was pulled for.",
+ "advertiserName": "Name of the advertiser account.",
+ "publisherId": "Publisher the metrics are aggregated for.",
+ "publisherName": "Name of the publisher.",
+ "region": "Region the metrics cover.",
+ "currency": "ISO code of the currency the monetary values are reported in.",
+ "impressions": "Number of impressions in the window.",
+ "clicks": "Number of clicks in the window.",
+ "pendingNo": "Count of pending transactions.",
+ "pendingValue": "Total value of pending transactions.",
+ "pendingComm": "Total commission on pending transactions.",
+ "confirmedNo": "Count of confirmed transactions.",
+ "confirmedValue": "Total value of confirmed transactions.",
+ "confirmedComm": "Total commission on confirmed transactions.",
+ "bonusNo": "Count of bonus transactions.",
+ "bonusValue": "Total value of bonus transactions.",
+ "bonusComm": "Total commission on bonus transactions.",
+ "declinedNo": "Count of declined transactions.",
+ "declinedValue": "Total value of declined transactions.",
+ "declinedComm": "Total commission on declined transactions.",
+ "totalNo": "Total count of transactions.",
+ "totalValue": "Total value across transactions.",
+ "totalComm": "Total commission across transactions.",
+ "tags": "Tags applied to the publisher.",
+ },
+ },
+ "advertiser_publishers": {
+ "description": "Publishers an advertiser account currently has an active relationship with.",
+ "docs_url": "https://help.awin.com/apidocs/get-publishers-information-for-advertiser",
+ "columns": {
+ "advertiserId": "Advertiser account the relationship belongs to.",
+ "id": "Unique identifier of the publisher. Joins to publisherId on transactions and performance rows.",
+ "name": "Name of the publisher.",
+ "primaryRegion": "The publisher's main region.",
+ "salesRegions": "Additional regions the publisher sells in, when defined.",
+ "primaryType": "The publisher's primary promotion type.",
+ },
+ },
}
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.py
index 1794908bfbab..4894f7135a04 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/awin/settings.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/awin/settings.py
@@ -1,6 +1,8 @@
-from dataclasses import dataclass, field
+from dataclasses import field
from typing import Literal, Optional
+from posthog.dataclasses import frozen
+
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
@@ -15,9 +17,10 @@ DEFAULT_BACKFILL_DAYS = 365
# 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"]
+# `accounts` is a single top-level call. Every other endpoint fans out over the publisher accounts
+# the token can see, over its advertiser accounts, or over each publisher's joined programmes. The
+# last kind is for publisher-scoped paths that also require an advertiserId query param.
+AwinEndpointKind = Literal["accounts", "publisher_fanout", "advertiser_fanout", "publisher_programme_fanout"]
# Awin's aggregated report endpoints require a `region` query param naming the account's market
# (there is no "all regions" value). Options and default ("GB") match Awin's own API docs.
@@ -46,26 +49,31 @@ REGION_OPTIONS: list[tuple[str, str]] = [
DEFAULT_REGION = "GB"
-@dataclass
+@frozen
class AwinEndpointConfig:
name: str
kind: AwinEndpointKind
- # Path relative to https://api.awin.com. `{publisher_id}` is substituted per account for fan-out
- # endpoints.
+ # Path relative to https://api.awin.com. `{publisher_id}` / `{advertiser_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.
+ # For `accounts` the payload is wrapped as {"accounts": [...]}; `commission_groups` wraps its rows
+ # under "commissionGroups". Every other list 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.
+ # The payload is a single object that becomes one row, rather than a list of them.
+ single_row: bool = False
+ # Top-level fields copied onto every row extracted from `data_key`. Awin hangs the rate validity
+ # window off the commission groups envelope rather than off each group.
+ envelope_keys: list[str] = field(default_factory=list)
+ # Inject the fan-out identifiers onto each row so the parent identifier is present in the table
+ # (and in composite primary keys). Transactions and the performance reports already carry them.
inject_publisher_id: bool = False
+ inject_advertiser_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.
+ # Whether the endpoint takes a startDate/endDate window. Transactions and reports do; the lookup
+ # endpoints 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"
@@ -77,7 +85,7 @@ class AwinEndpointConfig:
# Trailing window (in days) for full-refresh report snapshots. `None` for non-report endpoints.
report_lookback_days: Optional[int] = None
# Whether this endpoint needs the account's `region` in its query params. Only Awin's
- # aggregated report endpoints require it; transactions and programmes don't.
+ # publisher-side aggregated report requires it; the advertiser-side report does not.
requires_region: bool = False
should_sync_default: bool = True
@@ -100,6 +108,36 @@ AWIN_ENDPOINTS: dict[str, AwinEndpointConfig] = {
# programmes in the network) would be enormous and mostly irrelevant.
extra_params={"relationship": "joined"},
),
+ "programme_details": AwinEndpointConfig(
+ name="programme_details",
+ kind="publisher_programme_fanout",
+ path="/publishers/{publisher_id}/programmedetails",
+ primary_keys=["publisherId", "advertiserId"],
+ # One programme per call, so the whole payload (commission range, KPIs, programme info) is
+ # a single row.
+ single_row=True,
+ inject_publisher_id=True,
+ inject_advertiser_id=True,
+ extra_params={"relationship": "joined"},
+ # One request per joined programme, so it is slow for a publisher in many programmes.
+ should_sync_default=False,
+ ),
+ "commission_groups": AwinEndpointConfig(
+ name="commission_groups",
+ kind="publisher_programme_fanout",
+ path="/publishers/{publisher_id}/commissiongroups",
+ # groupId is documented as unique across advertisers, but the rates attached to it are the
+ # ones this publisher gets, so the publisher belongs in the key too.
+ primary_keys=["publisherId", "advertiserId", "groupId"],
+ data_key="commissionGroups",
+ envelope_keys=["ratesStart", "ratesEnd"],
+ # Without this Awin returns each condition's type and operator but not the values it
+ # compares against, which is the part a query needs.
+ extra_params={"extraConditionsDetails": "true"},
+ inject_publisher_id=True,
+ inject_advertiser_id=True,
+ should_sync_default=False,
+ ),
"transactions": AwinEndpointConfig(
name="transactions",
kind="publisher_fanout",
@@ -137,6 +175,26 @@ AWIN_ENDPOINTS: dict[str, AwinEndpointConfig] = {
report_lookback_days=DEFAULT_REPORT_LOOKBACK_DAYS,
requires_region=True,
),
+ "reports_publisher": AwinEndpointConfig(
+ name="reports_publisher",
+ kind="advertiser_fanout",
+ path="/advertisers/{advertiser_id}/reports/publisher",
+ # The advertiser-side counterpart of reports_advertiser; rows carry both ids already. Awin's
+ # spec shows a {body, statusCode, statusCodeValue} wrapper on both reports, but that is a
+ # Spring ResponseEntity artifact, so the service returns the bare array reports_advertiser
+ # already reads.
+ primary_keys=["advertiserId", "publisherId"],
+ date_windowed=True,
+ date_format="%Y-%m-%d",
+ report_lookback_days=DEFAULT_REPORT_LOOKBACK_DAYS,
+ ),
+ "advertiser_publishers": AwinEndpointConfig(
+ name="advertiser_publishers",
+ kind="advertiser_fanout",
+ path="/advertisers/{advertiser_id}/publishers",
+ primary_keys=["advertiserId", "id"],
+ inject_advertiser_id=True,
+ ),
}
ENDPOINTS = tuple(AWIN_ENDPOINTS.keys())
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.py
index d392cafed5f5..8b5eb3eb64fc 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
@@ -107,6 +107,12 @@ Create a personal OAuth2 token from the [Awin API settings](https://ui.awin.com/
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 == "reports_publisher":
+ return "Full refresh only. A rolling snapshot of the last 30 days of performance, aggregated per publisher. Needs an advertiser account"
+ if endpoint == "advertiser_publishers":
+ return "Full refresh only. Needs an advertiser account"
+ if endpoint in ("commission_groups", "programme_details"):
+ return "Full refresh only. Takes one request per joined programme, so it syncs slowly if your publisher accounts are in many programmes"
if endpoint == "transactions":
return "Only syncs the last 365 days on initial sync"
return None
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.py
index 5d11ae733b6e..78eef2c87e6b 100644
--- 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.py
@@ -8,9 +8,13 @@ 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 (
+ AwinFanoutTarget,
AwinResumeConfig,
_build_window_params,
- _discover_publisher_ids,
+ _discover_account_ids,
+ _discover_joined_advertiser_ids,
+ _fanout_targets,
+ _format_path,
_iter_windows,
_rows_from_response,
_to_datetime,
@@ -90,9 +94,10 @@ class TestWindowsForAccount:
windows = _windows_for_account(AWIN_ENDPOINTS["programmes"], False, None)
assert windows == [None]
+ @parameterized.expand([("reports_advertiser",), ("reports_publisher",)])
@time_machine.travel("2024-06-01", tick=False)
- 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))
+ def test_reports_use_lookback_window_regardless_of_incremental(self, endpoint: str) -> None:
+ windows = _windows_for_account(AWIN_ENDPOINTS[endpoint], 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
@@ -168,6 +173,17 @@ class TestBuildWindowParams:
)
assert params["region"] == "US"
+ def test_reports_publisher_does_not_include_region(self) -> None:
+ # Unlike its publisher-side counterpart, Awin's advertiser-side report takes no region param.
+ params = _build_window_params(
+ AWIN_ENDPOINTS["reports_publisher"],
+ datetime(2024, 1, 1, tzinfo=UTC),
+ datetime(2024, 1, 31, tzinfo=UTC),
+ incremental_field=None,
+ region="US",
+ )
+ assert params == {"startDate": "2024-01-01", "endDate": "2024-01-31", "timezone": "UTC"}
+
def test_transactions_does_not_include_region(self) -> None:
# Only endpoints marked `requires_region` (the aggregated reports) send the param.
params = _build_window_params(
@@ -183,32 +199,91 @@ class TestBuildWindowParams:
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)
+ rows = _rows_from_response(AWIN_ENDPOINTS["accounts"], data)
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)
+ rows = _rows_from_response(AWIN_ENDPOINTS["transactions"], data, AwinFanoutTarget(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)
+ rows = _rows_from_response(AWIN_ENDPOINTS["programmes"], data, AwinFanoutTarget(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)
+ rows = _rows_from_response(AWIN_ENDPOINTS["programmes"], data, AwinFanoutTarget(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)
+ rows = _rows_from_response(AWIN_ENDPOINTS["transactions"], data, AwinFanoutTarget(publisher_id=1))
assert rows == [{"id": 1}]
+ def test_commission_groups_flattens_envelope_onto_each_group(self) -> None:
+ # Awin hangs the rate validity window off the envelope, not off each group, so without the
+ # copy every commission_groups row loses when its rate applied.
+ data = {
+ "advertiser": 9,
+ "publisher": 42,
+ "ratesStart": "2024-01-01T00:00:00Z",
+ "ratesEnd": "2024-06-01T00:00:00Z",
+ "commissionGroups": [{"groupId": 1, "type": "fix"}, {"groupId": 2, "type": "percentage"}],
+ }
+ rows = _rows_from_response(
+ AWIN_ENDPOINTS["commission_groups"], data, AwinFanoutTarget(publisher_id=42, advertiser_id=9)
+ )
+
+ assert rows == [
+ {
+ "groupId": 1,
+ "type": "fix",
+ "ratesStart": "2024-01-01T00:00:00Z",
+ "ratesEnd": "2024-06-01T00:00:00Z",
+ "publisherId": 42,
+ "advertiserId": 9,
+ },
+ {
+ "groupId": 2,
+ "type": "percentage",
+ "ratesStart": "2024-01-01T00:00:00Z",
+ "ratesEnd": "2024-06-01T00:00:00Z",
+ "publisherId": 42,
+ "advertiserId": 9,
+ },
+ ]
+
+ def test_commission_groups_tolerates_a_missing_rates_end(self) -> None:
+ # ratesEnd is omitted while the rates are ongoing.
+ data = {"ratesStart": "2024-01-01T00:00:00Z", "commissionGroups": [{"groupId": 1}]}
+ rows = _rows_from_response(
+ AWIN_ENDPOINTS["commission_groups"], data, AwinFanoutTarget(publisher_id=42, advertiser_id=9)
+ )
+ assert rows == [{"groupId": 1, "ratesStart": "2024-01-01T00:00:00Z", "publisherId": 42, "advertiserId": 9}]
+
+ def test_programme_details_object_becomes_one_row_with_both_ids(self) -> None:
+ # The payload is the programme, not a list of them, and carries neither id in its root.
+ data = {"kpi": {"epc": 0.5}, "programmeInfo": {"id": 9, "name": "Acme"}}
+ rows = _rows_from_response(
+ AWIN_ENDPOINTS["programme_details"], data, AwinFanoutTarget(publisher_id=42, advertiser_id=9)
+ )
+ assert rows == [
+ {"kpi": {"epc": 0.5}, "programmeInfo": {"id": 9, "name": "Acme"}, "publisherId": 42, "advertiserId": 9}
+ ]
+
+ def test_advertiser_publishers_gets_the_advertiser_id_injected(self) -> None:
+ # The rows carry only the publisher's own fields, so without this the lookup can't be joined
+ # back to the advertiser it belongs to.
+ data = [{"id": 7, "name": "Some publisher"}]
+ rows = _rows_from_response(AWIN_ENDPOINTS["advertiser_publishers"], data, AwinFanoutTarget(advertiser_id=90))
+ assert rows == [{"id": 7, "name": "Some publisher", "advertiserId": 90}]
+
-class TestDiscoverPublisherIds:
- def test_filters_publisher_accounts_and_sorts_and_dedupes(self) -> None:
+class TestDiscoverAccountIds:
+ @parameterized.expand([("publisher", [1, 3]), ("advertiser", [2])])
+ def test_filters_by_account_type_and_sorts_and_dedupes(self, account_type: str, expected: list[int]) -> None:
with patch.object(awin, "_fetch") as mock_fetch:
mock_fetch.return_value = {
"accounts": [
@@ -218,8 +293,68 @@ class TestDiscoverPublisherIds:
{"accountId": 1, "accountType": "publisher"},
]
}
- ids = _discover_publisher_ids(MagicMock(), {}, MagicMock())
- assert ids == [1, 3]
+ ids = _discover_account_ids(MagicMock(), {}, MagicMock(), account_type)
+ assert ids == expected
+
+
+class TestDiscoverJoinedAdvertiserIds:
+ def test_reads_programme_ids_from_the_joined_programmes_list(self) -> None:
+ with patch.object(awin, "_fetch") as mock_fetch:
+ mock_fetch.return_value = [{"id": 7}, {"id": 3}, {"id": 7}, "junk", {"name": "no id"}]
+ ids = _discover_joined_advertiser_ids(MagicMock(), {}, MagicMock(), publisher_id=10)
+
+ assert ids == [3, 7]
+ # Bounded to joined programmes; the network-wide default would be enormous.
+ assert mock_fetch.call_args.args[1] == "/publishers/10/programmes"
+ assert mock_fetch.call_args.args[3] == {"relationship": "joined"}
+
+
+class TestFanoutTargets:
+ def _fetch_for(self, programmes_by_publisher: dict[int, 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": 90, "accountType": "advertiser"},
+ ]
+ }
+ publisher_id = int(path.split("/")[2])
+ return [{"id": advertiser_id} for advertiser_id in programmes_by_publisher[publisher_id]]
+
+ return fake_fetch
+
+ def test_programme_fanout_pairs_each_publisher_with_its_joined_advertisers(self) -> None:
+ with patch.object(awin, "_fetch", side_effect=self._fetch_for({10: [1, 2], 20: [2]})):
+ targets = _fanout_targets(AWIN_ENDPOINTS["commission_groups"], MagicMock(), {}, MagicMock())
+
+ assert targets == [
+ AwinFanoutTarget(publisher_id=10, advertiser_id=1),
+ AwinFanoutTarget(publisher_id=10, advertiser_id=2),
+ AwinFanoutTarget(publisher_id=20, advertiser_id=2),
+ ]
+
+
+class TestFormatPath:
+ @parameterized.expand(
+ [
+ ("transactions", AwinFanoutTarget(publisher_id=5), "/publishers/5/transactions/"),
+ (
+ "commission_groups",
+ AwinFanoutTarget(publisher_id=5, advertiser_id=9),
+ "/publishers/5/commissiongroups",
+ ),
+ ("reports_publisher", AwinFanoutTarget(advertiser_id=9), "/advertisers/9/reports/publisher"),
+ ("advertiser_publishers", AwinFanoutTarget(advertiser_id=9), "/advertisers/9/publishers"),
+ ]
+ )
+ def test_each_id_lands_in_the_path_segment_that_accepts_it(
+ self, endpoint: str, target: AwinFanoutTarget, expected: str
+ ) -> None:
+ # A programme-scoped path holds both ids, so a template naming the wrong one reads another
+ # account rather than failing loudly.
+ assert _format_path(AWIN_ENDPOINTS[endpoint], target) == expected
class TestValidateCredentials:
@@ -271,11 +406,11 @@ class TestGetRows:
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]
+ assert [s.publisher_id for s in manager.saved] == [10, 20]
@time_machine.travel("2024-06-01", tick=False)
def test_resume_skips_already_synced_accounts(self) -> None:
- manager = FakeResumableManager(state=AwinResumeConfig(account_id=20, window_start=None))
+ manager = FakeResumableManager(state=AwinResumeConfig(publisher_id=20, window_start=None))
fetched_publishers: list[int] = []
def fake_fetch(session: Any, path: str, headers: Any, params: Any, logger: Any) -> Any:
@@ -342,6 +477,97 @@ class TestGetRows:
batches = list(get_rows("token", "programmes", MagicMock(), manager, region="GB")) # type: ignore[arg-type]
assert batches == []
+ @time_machine.travel("2024-06-01", tick=False)
+ def test_advertiser_fanout_skips_publisher_accounts(self) -> None:
+ # /advertisers paths only accept advertiser accounts; fanning out over publisher ids 404s.
+ manager = FakeResumableManager()
+ seen_paths: 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": 90, "accountType": "advertiser"},
+ ]
+ }
+ seen_paths.append(path)
+ return [{"id": 7}]
+
+ with patch.object(awin, "make_tracked_session"), patch.object(awin, "_fetch", side_effect=fake_fetch):
+ batches = list(get_rows("token", "advertiser_publishers", MagicMock(), manager, region="GB")) # type: ignore[arg-type]
+
+ assert seen_paths == ["/advertisers/90/publishers"]
+ assert batches == [[{"id": 7, "advertiserId": 90}]]
+
+ @time_machine.travel("2024-06-01", tick=False)
+ def test_programme_fanout_sends_advertiser_id_per_joined_programme(self) -> None:
+ manager = FakeResumableManager()
+ requests_made: list[tuple[str, Any]] = []
+
+ def fake_fetch(session: Any, path: str, headers: Any, params: Any, logger: Any) -> Any:
+ if path == "/accounts":
+ return {"accounts": [{"accountId": 10, "accountType": "publisher"}]}
+ if path.endswith("/programmes"):
+ return [{"id": 1}, {"id": 2}]
+ requests_made.append((path, params))
+ return {"commissionGroups": [{"groupId": 100}]}
+
+ with patch.object(awin, "make_tracked_session"), patch.object(awin, "_fetch", side_effect=fake_fetch):
+ batches = list(get_rows("token", "commission_groups", MagicMock(), manager, region="GB")) # type: ignore[arg-type]
+
+ # advertiserId is a required query param on this publisher-scoped path, so Awin 400s without it.
+ assert requests_made == [
+ ("/publishers/10/commissiongroups", {"extraConditionsDetails": "true", "advertiserId": "1"}),
+ ("/publishers/10/commissiongroups", {"extraConditionsDetails": "true", "advertiserId": "2"}),
+ ]
+ assert [row["advertiserId"] for batch in batches for row in batch] == [1, 2]
+ # State carries the programme too, so a crash resumes at the right (publisher, advertiser) pair.
+ assert [(s.publisher_id, s.advertiser_id) for s in manager.saved] == [(10, 1), (10, 2)]
+
+ @time_machine.travel("2024-06-01", tick=False)
+ def test_programme_fanout_resumes_at_the_saved_pair(self) -> None:
+ manager = FakeResumableManager(state=AwinResumeConfig(publisher_id=10, advertiser_id=2, window_start=None))
+ fetched_advertisers: 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"}]}
+ if path.endswith("/programmes"):
+ return [{"id": 1}, {"id": 2}, {"id": 3}]
+ fetched_advertisers.append(params["advertiserId"])
+ return {}
+
+ with patch.object(awin, "make_tracked_session"), patch.object(awin, "_fetch", side_effect=fake_fetch):
+ list(get_rows("token", "programme_details", MagicMock(), manager, region="GB")) # type: ignore[arg-type]
+
+ # Programme 1 was already done before the crash; the pair bookmark restarts at 2.
+ assert fetched_advertisers == ["2", "3"]
+
+ @time_machine.travel("2024-06-01", tick=False)
+ def test_programme_fanout_static_params_are_not_mutated_between_requests(self) -> None:
+ # The endpoint's static extra_params dict is shared by every request, so writing advertiserId
+ # into it would leak the previous programme's id into later requests.
+ manager = FakeResumableManager()
+ seen_params: list[dict[str, Any]] = []
+
+ def fake_fetch(session: Any, path: str, headers: Any, params: Any, logger: Any) -> Any:
+ if path == "/accounts":
+ return {"accounts": [{"accountId": 10, "accountType": "publisher"}]}
+ if path.endswith("/programmes"):
+ return [{"id": 1}, {"id": 2}]
+ seen_params.append(dict(params))
+ return {}
+
+ with patch.object(awin, "make_tracked_session"), patch.object(awin, "_fetch", side_effect=fake_fetch):
+ list(get_rows("token", "programme_details", MagicMock(), manager, region="GB")) # type: ignore[arg-type]
+
+ assert seen_params == [
+ {"relationship": "joined", "advertiserId": "1"},
+ {"relationship": "joined", "advertiserId": "2"},
+ ]
+ assert AWIN_ENDPOINTS["programme_details"].extra_params == {"relationship": "joined"}
+
@time_machine.travel("2024-06-01", tick=False)
def test_reports_advertiser_request_carries_region(self) -> None:
manager = FakeResumableManager()
@@ -367,6 +593,10 @@ class TestAwinSource:
("programmes", ["publisherId", "id"], None),
("transactions", ["id"], "transactionDate"),
("reports_advertiser", ["publisherId", "advertiserId"], None),
+ ("reports_publisher", ["advertiserId", "publisherId"], None),
+ ("advertiser_publishers", ["advertiserId", "id"], None),
+ ("commission_groups", ["publisherId", "advertiserId", "groupId"], None),
+ ("programme_details", ["publisherId", "advertiserId"], None),
]
)
def test_source_response_shape(self, endpoint: str, expected_pks: list[str], partition_key: Optional[str]) -> None:
diff --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.py
index ed9666a63ba4..9f2793df2c91 100644
--- 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.py
@@ -34,14 +34,27 @@ class TestAwinSourceClass:
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"}
+ assert names == {
+ "accounts",
+ "programmes",
+ "programme_details",
+ "commission_groups",
+ "transactions",
+ "reports_advertiser",
+ "reports_publisher",
+ "advertiser_publishers",
+ }
@parameterized.expand(
[
("transactions", True),
("accounts", False),
("programmes", False),
+ ("programme_details", False),
+ ("commission_groups", False),
("reports_advertiser", False),
+ ("reports_publisher", False),
+ ("advertiser_publishers", False),
]
)
def test_supports_incremental_per_endpoint(self, endpoint: str, expected: bool) -> None:
@@ -57,7 +70,16 @@ class TestAwinSourceClass:
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"}
+ assert names == {
+ "accounts",
+ "programmes",
+ "programme_details",
+ "commission_groups",
+ "transactions",
+ "reports_advertiser",
+ "reports_publisher",
+ "advertiser_publishers",
+ }
@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: