: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 adobe_analytics source (#73792)
Tom Owers82e2b545eba6
diff --git a/frontend/public/services/adobe_analytics.png b/frontend/public/services/adobe_analytics.pngindex 0de21b22a84c..1b04eead22ec 100644Binary files a/frontend/public/services/adobe_analytics.png and b/frontend/public/services/adobe_analytics.png differdiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.mdindex 37121260694f..b9affe994b9b 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md@@ -49,6 +49,7 @@ the row lists both.| Source | Comm method | Primary library | Tracked transport || -------------------------------- | --------------------------- | --------------------------------------------------------------- | --------------------------- || ably | HTTP | requests + `rest_source.RESTClient` | ✅ |+| adobe_analytics | HTTP | requests | ✅ || adroll | HTTP | requests | ✅ || adyen | HTTP | requests | ✅ || agilecrm | HTTP | requests | ✅ |@@ -706,7 +707,6 @@ doesn't conflict with concurrent PRs.- acuity_scheduling- adapty- adjust-- adobe_analytics- adobe_commerce- adp_workforce_now- aftershipdiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/adobe_analytics/adobe_analytics.py b/products/warehouse_sources/backend/temporal/data_imports/sources/adobe_analytics/adobe_analytics.pynew file mode 100644index 000000000000..feae444bb30a--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/adobe_analytics/adobe_analytics.py@@ -0,0 +1,471 @@+import re+import time+import dataclasses+from collections.abc import Iterator+from datetime import UTC, date, datetime, timedelta+from typing import Any, Optional++import requests+from structlog.types import FilteringBoundLogger++from products.warehouse_sources.backend.temporal.data_imports.sources.adobe_analytics.settings import (+ ADOBE_ANALYTICS_ENDPOINTS,+ DEFAULT_REPORT_DIMENSION,+ DEFAULT_REPORT_METRICS,+ METADATA_PAGE_SIZE,+ REPORT_ENDPOINT,+ REPORT_PAGE_SIZE,+)+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+from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceResponse++# Adobe IMS issues the access token for OAuth Server-to-Server credentials. JWT ("Service+# Account") credentials were retired on 2025-06-30, so this is the only server-side grant left.+IMS_TOKEN_URL = "https://ims-na1.adobelogin.com/ims/token/v3"+IMS_SCOPES = "openid,AdobeID,read_organizations,additional_info.projectedProductContext"++ANALYTICS_HOST = "https://analytics.adobe.io"+DISCOVERY_URL = f"{ANALYTICS_HOST}/discovery/me"++# Adobe terminates its own requests at 60s.+REQUEST_TIMEOUT_SECONDS = 60+# Hard, non-raisable throttle of 12 requests per 6 seconds per user.+MIN_REQUEST_INTERVAL_SECONDS = 0.5+# Adobe restates recent report data, so each incremental run re-pulls a trailing window.+INCREMENTAL_LOOKBACK_DAYS = 1+DEFAULT_BACKFILL_DAYS = 90+# The report stream walks one day per request, so an unbounded start date would issue+# hundreds of thousands of sequential calls. Cap the earliest day we'll backfill.+MAX_BACKFILL_DAYS = 365 * 3+# Guard against a report whose paging never signals completion.+MAX_REPORT_PAGES = 200+++class AdobeAnalyticsResumeConfig:+ # Metadata listings resume on a page number; the report stream resumes on the day+ # window it was mid-way through plus that day's page.+ page: int = 0+ next_date: Optional[str] = None+++class AdobeAnalyticsClient:+ """Token-minting, throttled client for the Adobe Analytics 2.0 API."""++ def __init__(+ self,+ client_id: str,+ client_secret: str,+ logger: FilteringBoundLogger,+ global_company_id: Optional[str] = None,+ min_request_interval: float = MIN_REQUEST_INTERVAL_SECONDS,+ ) -> None:+ self._client_id = client_id+ self._client_secret = client_secret+ self._logger = logger+ self._global_company_id = global_company_id or None+ self._min_request_interval = min_request_interval+ self._last_request_at: Optional[float] = None+ self._token: Optional[str] = None+ self._session = make_tracked_session(redact_values=(client_secret,))+ # The token exchange body carries the client secret and the response carries a live+ # bearer token, neither of which the name-based sample scrubbers recognise.+ self._auth_session = make_tracked_session(redact_values=(client_secret,), capture=False)++ def _pace(self) -> None:+ if self._min_request_interval <= 0:+ return+ if self._last_request_at is not None:+ elapsed = time.monotonic() - self._last_request_at+ if elapsed < self._min_request_interval:+ time.sleep(self._min_request_interval - elapsed)+ self._last_request_at = time.monotonic()++ def _mint_token(self) -> str:+ response = self._auth_session.post(+ IMS_TOKEN_URL,+ data={+ "grant_type": "client_credentials",+ "client_id": self._client_id,+ "client_secret": self._client_secret,+ "scope": IMS_SCOPES,+ },+ timeout=REQUEST_TIMEOUT_SECONDS,+ )+ response.raise_for_status()+ token = response.json().get("access_token")+ if not token:+ raise ValueError("Adobe IMS did not return an access token")+ return str(token)++ def _access_token(self) -> str:+ if self._token is None:+ self._token = self._mint_token()+ return self._token++ def _headers(self) -> dict[str, str]:+ return {+ "Authorization": f"Bearer {self._access_token()}",+ "x-api-key": self._client_id,+ "Accept": "application/json",+ }++ def request(+ self,+ method: str,+ url: str,+ params: Optional[dict[str, Any]] = None,+ json_body: Optional[dict[str, Any]] = None,+ ) -> requests.Response:+ def _do() -> requests.Response:+ self._pace()+ if method == "POST":+ return self._session.post(+ url, headers=self._headers(), params=params, json=json_body, timeout=REQUEST_TIMEOUT_SECONDS+ )+ return self._session.get(url, headers=self._headers(), params=params, timeout=REQUEST_TIMEOUT_SECONDS)++ response = _do()+ # IMS access tokens last ~24h; re-mint once if a long sync outlives one.+ if response.status_code == 401:+ self._token = None+ response = _do()++ if not response.ok:+ self._logger.error(+ f"Adobe Analytics API error: status={response.status_code}, body={response.text}, url={url}"+ )+ response.raise_for_status()++ return response++ def resolve_global_company_id(self) -> str:+ """Return the configured global company id, discovering it from /discovery/me if absent."""+ if self._global_company_id:+ return self._global_company_id++ payload = self.request("GET", DISCOVERY_URL).json()+ for org in payload.get("imsOrgs") or []:+ for company in org.get("companies") or []:+ company_id = company.get("globalCompanyId")+ if company_id:+ self._global_company_id = str(company_id)+ return self._global_company_id++ raise ValueError(+ "Could not find a global company ID for these credentials. Check that the Analytics API is added "+ "to your Adobe Developer Console project and that the credential has a product profile assigned."+ )++ @property+ def base_url(self) -> str:+ return f"{ANALYTICS_HOST}/api/{self.resolve_global_company_id()}"++ def get_json(self, path: str, params: Optional[dict[str, Any]] = None) -> Any:+ return self.request("GET", f"{self.base_url}{path}", params=params).json()++ def post_json(self, path: str, body: dict[str, Any]) -> dict[str, Any]:+ payload = self.request("POST", f"{self.base_url}{path}", json_body=body).json()+ return payload if isinstance(payload, dict) else {}+++def _today() -> date:+ return datetime.now(UTC).date()+++def parse_date(value: Any) -> Optional[date]:+ """Coerce a config string or incremental watermark into a UTC calendar date."""+ if isinstance(value, datetime):+ dt = value if value.tzinfo else value.replace(tzinfo=UTC)+ return dt.astimezone(UTC).date()+ if isinstance(value, date):+ return value+ if not value:+ return None+ try:+ return date.fromisoformat(str(value)[:10])+ except ValueError:+ return None+++def parse_metrics(raw: Optional[str]) -> list[str]:+ metrics = [metric.strip() for metric in (raw or DEFAULT_REPORT_METRICS).split(",")]+ metrics = [metric for metric in metrics if metric]+ if metrics:+ return metrics+ return [metric.strip() for metric in DEFAULT_REPORT_METRICS.split(",")]+++def metric_column_names(metric_ids: list[str]) -> list[str]:+ """Map Adobe metric ids onto stable, warehouse-safe column names."""+ names: list[str] = []+ seen: dict[str, int] = {}+ for metric_id in metric_ids:+ base = re.sub(r"[^0-9a-zA-Z_]", "_", metric_id.rsplit("/", 1)[-1]) or "metric"+ count = seen.get(base, 0)+ seen[base] = count + 1+ names.append(base if count == 0 else f"{base}_{count + 1}")+ return names+++def resolve_window(+ start_date: Optional[str],+ should_use_incremental_field: bool,+ db_incremental_field_last_value: Any,+ today: date,+) -> tuple[date, date]:+ earliest = today - timedelta(days=MAX_BACKFILL_DAYS)++ if should_use_incremental_field and db_incremental_field_last_value is not None:+ last_value = parse_date(db_incremental_field_last_value)+ if last_value is not None:+ return max(min(last_value - timedelta(days=INCREMENTAL_LOOKBACK_DAYS), today), earliest), today++ configured = parse_date(start_date)+ if configured is not None:+ return max(min(configured, today), earliest), today++ return today - timedelta(days=DEFAULT_BACKFILL_DAYS), today+++def build_report_body(+ report_suite_id: str, dimension: str, metric_ids: list[str], day: date, page: int+) -> dict[str, Any]:+ next_day = day + timedelta(days=1)+ return {+ "rsid": report_suite_id,+ "globalFilters": [+ {+ "type": "dateRange",+ "dateRange": f"{day.isoformat()}T00:00:00.000/{next_day.isoformat()}T00:00:00.000",+ }+ ],+ "metricContainer": {+ "metrics": [{"columnId": str(index), "id": metric_id} for index, metric_id in enumerate(metric_ids)]+ },+ "dimension": dimension,+ "settings": {"countRepeatInstances": True, "limit": REPORT_PAGE_SIZE, "page": page},+ }+++def report_rows(+ payload: dict[str, Any], report_suite_id: str, day: date, dimension: str, metric_columns: list[str]+) -> list[dict[str, Any]]:+ rows: list[dict[str, Any]] = []+ for row in payload.get("rows") or []:+ data = row.get("data") or []+ record: dict[str, Any] = {+ "rsid": report_suite_id,+ "date": day.isoformat(),+ "dimension": dimension,+ "item_id": str(row.get("itemId", "")),+ "value": row.get("value"),+ }+ for index, column in enumerate(metric_columns):+ record[column] = data[index] if index < len(data) else None+ rows.append(record)+ return rows+++def _metadata_batches(+ client: AdobeAnalyticsClient,+ endpoint: str,+ report_suite_id: str,+ manager: ResumableSourceManager[AdobeAnalyticsResumeConfig],+ resume: Optional[AdobeAnalyticsResumeConfig],+) -> Iterator[list[dict[str, Any]]]:+ config = ADOBE_ANALYTICS_ENDPOINTS[endpoint]+ params: dict[str, Any] = {}+ if config.report_suite_param:+ params[config.report_suite_param] = report_suite_id++ if config.data_key is None:+ # `/dimensions` and `/metrics` return the whole catalog as a bare array, and their+ # rows carry no report suite of their own.+ payload = client.get_json(config.path, params)+ items = [{**item, "rsid": report_suite_id} for item in (payload or [])]+ if items:+ yield items+ manager.clear_state()+ return++ page = resume.page if resume is not None else 0+ while True:+ payload = client.get_json(config.path, {**params, "limit": METADATA_PAGE_SIZE, "page": page})+ items = list((payload or {}).get(config.data_key) or [])+ if items:+ yield items++ if not items or bool((payload or {}).get("lastPage")):+ break++ page += 1+ # Save state AFTER yielding so a crash re-yields the last page (merge dedupes on+ # primary key) rather than skipping it.+ manager.save_state(AdobeAnalyticsResumeConfig(page=page))++ manager.clear_state()+++def _report_batches(+ client: AdobeAnalyticsClient,+ report_suite_id: str,+ dimension: str,+ metric_ids: list[str],+ start: date,+ end: date,+ manager: ResumableSourceManager[AdobeAnalyticsResumeConfig],+ resume: Optional[AdobeAnalyticsResumeConfig],+ logger: FilteringBoundLogger,+) -> Iterator[list[dict[str, Any]]]:+ metric_columns = metric_column_names(metric_ids)++ current = start+ page = 0+ if resume is not None and resume.next_date:+ resumed = parse_date(resume.next_date)+ if resumed is not None and start <= resumed <= end:+ current = resumed+ page = resume.page++ while current <= end:+ while True:+ payload = client.post_json(+ "/reports", build_report_body(report_suite_id, dimension, metric_ids, current, page)+ )+ rows = report_rows(payload, report_suite_id, current, dimension, metric_columns)+ if rows:+ yield rows++ total_pages = payload.get("totalPages")+ complete = (+ not rows or bool(payload.get("lastPage")) or (isinstance(total_pages, int) and page + 1 >= total_pages)+ )+ if not complete and page + 1 >= MAX_REPORT_PAGES:+ logger.warning(+ f"Adobe Analytics report page cap reached, truncating the day: "+ f"rsid={report_suite_id}, date={current.isoformat()}"+ )+ break+ if complete:+ break++ page += 1+ manager.save_state(AdobeAnalyticsResumeConfig(page=page, next_date=current.isoformat()))++ current += timedelta(days=1)+ page = 0+ if current <= end:+ manager.save_state(AdobeAnalyticsResumeConfig(page=0, next_date=current.isoformat()))++ manager.clear_state()+++def validate_credentials(+ client_id: str, client_secret: str, global_company_id: Optional[str], logger: FilteringBoundLogger+) -> tuple[bool, Optional[str]]:+ """Mint a token and confirm the credential can reach the Analytics API."""+ client = AdobeAnalyticsClient(client_id, client_secret, logger, global_company_id)+ try:+ client.resolve_global_company_id()+ except requests.HTTPError:+ return False, "Adobe Analytics rejected the credentials. Check the client ID and secret."+ except ValueError as e:+ return False, str(e)+ except Exception:+ return False, "Could not reach Adobe Analytics. Please try again."++ try:+ client.get_json("/collections/suites", {"limit": 1, "page": 0})+ except Exception:+ return False, (+ "Adobe Analytics denied access to your report suites. Check that the Analytics API is added to "+ "your Adobe Developer Console project and that the credential has a product profile assigned."+ )++ return True, None+++def get_rows(+ client_id: str,+ client_secret: str,+ global_company_id: Optional[str],+ report_suite_id: str,+ report_dimension: Optional[str],+ report_metrics: Optional[str],+ start_date: Optional[str],+ endpoint: str,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[AdobeAnalyticsResumeConfig],+ should_use_incremental_field: bool = False,+ db_incremental_field_last_value: Any = None,+) -> Iterator[list[dict[str, Any]]]:+ client = AdobeAnalyticsClient(client_id, client_secret, logger, global_company_id)+ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None++ if endpoint != REPORT_ENDPOINT:+ yield from _metadata_batches(client, endpoint, report_suite_id, resumable_source_manager, resume)+ return++ start, end = resolve_window(+ start_date,+ should_use_incremental_field,+ db_incremental_field_last_value,+ _today(),+ )+ yield from _report_batches(+ client,+ report_suite_id,+ (report_dimension or DEFAULT_REPORT_DIMENSION).strip() or DEFAULT_REPORT_DIMENSION,+ parse_metrics(report_metrics),+ start,+ end,+ resumable_source_manager,+ resume,+ logger,+ )+++def adobe_analytics_source(+ client_id: str,+ client_secret: str,+ global_company_id: Optional[str],+ report_suite_id: str,+ report_dimension: Optional[str],+ report_metrics: Optional[str],+ start_date: Optional[str],+ endpoint: str,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[AdobeAnalyticsResumeConfig],+ should_use_incremental_field: bool = False,+ db_incremental_field_last_value: Any = None,+) -> SourceResponse:+ config = ADOBE_ANALYTICS_ENDPOINTS[endpoint]+ is_report = endpoint == REPORT_ENDPOINT++ return SourceResponse(+ name=endpoint,+ items=lambda: get_rows(+ client_id=client_id,+ client_secret=client_secret,+ global_company_id=global_company_id,+ report_suite_id=report_suite_id,+ report_dimension=report_dimension,+ report_metrics=report_metrics,+ start_date=start_date,+ 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=config.primary_key,+ partition_count=1,+ partition_size=1,+ partition_mode="datetime" if is_report else None,+ partition_format="month" if is_report else None,+ partition_keys=["date"] if is_report else None,+ # Report day windows are walked oldest-first; metadata listings are single-shot.+ sort_mode="asc",+ )diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/adobe_analytics/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/adobe_analytics/canonical_descriptions.pynew file mode 100644index 000000000000..43c3f9312e51--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/adobe_analytics/canonical_descriptions.py@@ -0,0 +1,98 @@+"""Canonical, documentation-sourced descriptions for Adobe Analytics endpoints and columns.++Sourced from the official Adobe Analytics 2.0 API reference+(https://developer.adobe.com/analytics-apis/docs/2.0/). Keyed by the endpoint names in+`settings.py` `ADOBE_ANALYTICS_ENDPOINTS`, which match the `ExternalDataSchema.name` of a synced+Adobe Analytics table. Columns absent here fall back to LLM enrichment.+"""++from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (+ CanonicalDescriptions,+)++CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {+ "report_suites": {+ "description": "A report suite: the container that Adobe Analytics collects and reports data into.",+ "docs_url": "https://developer.adobe.com/analytics-apis/docs/2.0/guides/endpoints/reportsuites/",+ "columns": {+ "rsid": "Report suite id, the identifier used when querying reports.",+ "name": "Human-readable name of the report suite.",+ "collectionItemType": "Type of the collection item, always `reportsuite` for this table.",+ "currency": "Three-letter currency code the report suite reports revenue in.",+ "timezoneZoneinfo": "IANA time zone the report suite's calendar days are aligned to.",+ "parentRsid": "Report suite this one rolls up into, for virtual report suites.",+ },+ },+ "segments": {+ "description": "A saved segment: a reusable filter applied to report data.",+ "docs_url": "https://developer.adobe.com/analytics-apis/docs/2.0/guides/endpoints/segments/",+ "columns": {+ "id": "Unique identifier for the segment.",+ "name": "Name of the segment as shown in Adobe Analytics.",+ "description": "Description entered when the segment was saved.",+ "rsid": "Report suite the segment is defined against.",+ "owner": "Login and id of the user who owns the segment.",+ "definition": "Segment rule definition, returned when expanded.",+ "created": "Timestamp the segment was created.",+ "modified": "Timestamp the segment was last modified.",+ },+ },+ "calculated_metrics": {+ "description": "A calculated metric: a metric derived from other metrics, segments, and functions.",+ "docs_url": "https://developer.adobe.com/analytics-apis/docs/2.0/guides/endpoints/calculatedmetrics/",+ "columns": {+ "id": "Unique identifier for the calculated metric, usable as a metric id in reports.",+ "name": "Name of the calculated metric.",+ "description": "Description entered when the calculated metric was saved.",+ "rsid": "Report suite the calculated metric is defined against.",+ "owner": "Login and id of the user who owns the calculated metric.",+ "polarity": "Whether a higher value is good or bad.",+ "type": "Value type of the metric, such as decimal, currency, or percent.",+ "created": "Timestamp the calculated metric was created.",+ "modified": "Timestamp the calculated metric was last modified.",+ },+ },+ "dimensions": {+ "description": "The dimension catalog for a report suite: every dimension available to break a report down by.",+ "docs_url": "https://developer.adobe.com/analytics-apis/docs/2.0/guides/endpoints/dimensions/",+ "columns": {+ "id": "Dimension id, used as the `dimension` value in a report request (e.g. `variables/page`).",+ "rsid": "Report suite the dimension catalog was listed for.",+ "title": "Display name of the dimension.",+ "name": "Internal name of the dimension.",+ "category": "Grouping the dimension appears under in the Adobe Analytics UI.",+ "type": "Data type of the dimension's values.",+ "pathable": "Whether the dimension supports pathing reports.",+ "segmentable": "Whether the dimension can be used inside a segment.",+ "reportable": "Which report types the dimension can be used in.",+ },+ },+ "metrics": {+ "description": "The metric catalog for a report suite: every metric available to request in a report.",+ "docs_url": "https://developer.adobe.com/analytics-apis/docs/2.0/guides/endpoints/metrics/",+ "columns": {+ "id": "Metric id, used in a report's metric container (e.g. `metrics/visits`).",+ "rsid": "Report suite the metric catalog was listed for.",+ "title": "Display name of the metric.",+ "name": "Internal name of the metric.",+ "category": "Grouping the metric appears under in the Adobe Analytics UI.",+ "type": "Value type of the metric, such as int, decimal, currency, or percent.",+ "polarity": "Whether a higher value is good or bad.",+ "precision": "Number of decimal places the metric is reported to.",+ },+ },+ "report": {+ "description": (+ "Daily report rows from the Adobe Analytics reporting API: one row per report suite, day, "+ "and value of the configured dimension, with the configured metrics as columns."+ ),+ "docs_url": "https://developer.adobe.com/analytics-apis/docs/2.0/guides/endpoints/reports/",+ "columns": {+ "rsid": "Report suite the report was run against.",+ "date": "Calendar day (report suite time zone) the report window covers.",+ "dimension": "Dimension id the report was broken down by, e.g. `variables/daterangeday`.",+ "item_id": "Adobe's identifier for the dimension value in this report row.",+ "value": "The dimension value itself, e.g. the page name or the day.",+ },+ },+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/adobe_analytics/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/adobe_analytics/settings.pynew file mode 100644index 000000000000..70b033f1b22f--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/adobe_analytics/settings.py@@ -0,0 +1,87 @@+from dataclasses import dataclass, field+from typing import Optional++from products.warehouse_sources.backend.types import IncrementalField, IncrementalFieldType++# The reporting stream is the one endpoint that is a query rather than a listing, so it is+# routed separately from the metadata catalog endpoints.+REPORT_ENDPOINT = "report"++# Adobe's paginated metadata endpoints cap `limit` at 1000.+METADATA_PAGE_SIZE = 1000+# `/reports` defaults to 50 rows per page; 400 keeps each request comfortably under the 60s timeout.+REPORT_PAGE_SIZE = 400++DEFAULT_REPORT_DIMENSION = "variables/daterangeday"+DEFAULT_REPORT_METRICS = "metrics/visits,metrics/visitors,metrics/pageviews"+++@dataclass+class AdobeAnalyticsEndpointConfig:+ name: str+ # Path under https://analytics.adobe.io/api/{globalCompanyId}+ path: str+ primary_key: list[str]+ # Key the rows live under in a paginated response body. `None` means the endpoint+ # returns a bare JSON array in a single response (no pagination).+ data_key: Optional[str] = None+ # Query param used to scope the request to the configured report suite, if any.+ report_suite_param: Optional[str] = None+ incremental_fields: list[IncrementalField] = field(default_factory=list)+++ADOBE_ANALYTICS_ENDPOINTS: dict[str, AdobeAnalyticsEndpointConfig] = {+ "report_suites": AdobeAnalyticsEndpointConfig(+ name="report_suites",+ path="/collections/suites",+ primary_key=["rsid"],+ data_key="content",+ ),+ "segments": AdobeAnalyticsEndpointConfig(+ name="segments",+ path="/segments",+ primary_key=["id"],+ data_key="content",+ report_suite_param="rsids",+ ),+ "calculated_metrics": AdobeAnalyticsEndpointConfig(+ name="calculated_metrics",+ path="/calculatedmetrics",+ primary_key=["id"],+ data_key="content",+ report_suite_param="rsids",+ ),+ "dimensions": AdobeAnalyticsEndpointConfig(+ name="dimensions",+ path="/dimensions",+ primary_key=["rsid", "id"],+ report_suite_param="rsid",+ ),+ "metrics": AdobeAnalyticsEndpointConfig(+ name="metrics",+ path="/metrics",+ primary_key=["rsid", "id"],+ report_suite_param="rsid",+ ),+ REPORT_ENDPOINT: AdobeAnalyticsEndpointConfig(+ name=REPORT_ENDPOINT,+ path="/reports",+ # One row per (report suite, day, dimension item) — the dimension item id is only+ # unique inside its own day's report.+ primary_key=["rsid", "date", "item_id"],+ incremental_fields=[+ {+ "label": "date",+ "type": IncrementalFieldType.Date,+ "field": "date",+ "field_type": IncrementalFieldType.Date,+ },+ ],+ ),+}++ENDPOINTS = tuple(ADOBE_ANALYTICS_ENDPOINTS.keys())++INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {+ name: config.incremental_fields for name, config in ADOBE_ANALYTICS_ENDPOINTS.items() if config.incremental_fields+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/adobe_analytics/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/adobe_analytics/source.pyindex afe37d67899a..3613899546f6 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/adobe_analytics/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/adobe_analytics/source.py@@ -1,32 +1,199 @@-from typing import cast+from typing import Optional, cast++import structlogfrom 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.sources.adobe_analytics.adobe_analytics import (+ AdobeAnalyticsResumeConfig,+ adobe_analytics_source,+ validate_credentials as validate_adobe_analytics_credentials,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.adobe_analytics.settings import (+ ADOBE_ANALYTICS_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 (+ SourceSchema,+ build_endpoint_schemas,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceInputs, SourceResponsefrom products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.adobeanalytics import (AdobeAnalyticsSourceConfig,)from products.warehouse_sources.backend.types import ExternalDataSourceType+logger = structlog.get_logger(__name__)+@SourceRegistry.register-class AdobeAnalyticsSource(SimpleSource[AdobeAnalyticsSourceConfig]):+class AdobeAnalyticsSource(ResumableSource[AdobeAnalyticsSourceConfig, AdobeAnalyticsResumeConfig]):+ api_docs_url = "https://developer.adobe.com/analytics-apis/docs/2.0/"++ lists_tables_without_credentials = True # static endpoint catalog — safe for public docs+@propertydef source_type(self) -> ExternalDataSourceType:return ExternalDataSourceType.ADOBEANALYTICS+ def get_non_retryable_errors(self) -> dict[str, str | None]:+ return {+ "400 Client Error: Bad Request for url: https://ims-na1.adobelogin.com": "Adobe rejected your credentials. Check the client ID and secret from your Adobe Developer Console OAuth Server-to-Server credential.",+ "401 Client Error: Unauthorized for url: https://ims-na1.adobelogin.com": "Adobe could not authenticate your credentials. Check the client ID and secret from your Adobe Developer Console OAuth Server-to-Server credential.",+ "401 Client Error: Unauthorized for url: https://analytics.adobe.io": "Adobe Analytics rejected the access token. Reconnect the source with a fresh client ID and secret.",+ "403 Client Error: Forbidden for url: https://analytics.adobe.io": "Adobe Analytics denied access. Check that the Analytics API is added to your Developer Console project and that the credential has a product profile with access to this report suite.",+ }+@propertydef get_source_config(self) -> SourceConfig:return SourceConfig(name=SchemaExternalDataSourceType.ADOBE_ANALYTICS,category=DataWarehouseSourceCategory.ANALYTICS,label="Adobe Analytics",+ caption="""Pull Adobe Analytics report data and metadata into the PostHog Data warehouse.++Create an **OAuth Server-to-Server** credential in the [Adobe Developer Console](https://developer.adobe.com/console), add the Adobe Analytics API to the project, and assign a product profile that can read the report suite you want. Then enter the credential's client ID and secret.++The report table runs one query per day, so pick the dimension and metrics to break it down by. Adobe allows one dimension per report.""",iconPath="/static/services/adobe_analytics.png",- fields=cast(list[FieldType], []),- unreleasedSource=True,+ docsUrl="https://posthog.com/docs/cdp/sources/adobe-analytics",+ releaseStatus=ReleaseStatus.ALPHA,+ keywords=["adobe", "omniture", "sitecatalyst"],+ fields=cast(+ list[FieldType],+ [+ SourceFieldInputConfig(+ name="client_id",+ label="Client ID",+ type=SourceFieldInputConfigType.TEXT,+ required=True,+ placeholder="",+ secret=False,+ ),+ SourceFieldInputConfig(+ name="client_secret",+ label="Client secret",+ type=SourceFieldInputConfigType.PASSWORD,+ required=True,+ placeholder="p8e-...",+ secret=True,+ ),+ SourceFieldInputConfig(+ name="report_suite_id",+ label="Report suite ID",+ type=SourceFieldInputConfigType.TEXT,+ required=True,+ placeholder="examplersid",+ secret=False,+ ),+ SourceFieldInputConfig(+ name="global_company_id",+ label="Global company ID",+ type=SourceFieldInputConfigType.TEXT,+ required=False,+ placeholder="Leave blank to detect automatically",+ secret=False,+ ),+ SourceFieldInputConfig(+ name="report_dimension",+ label="Report dimension",+ type=SourceFieldInputConfigType.TEXT,+ required=False,+ placeholder="variables/daterangeday",+ secret=False,+ ),+ SourceFieldInputConfig(+ name="report_metrics",+ label="Report metrics",+ type=SourceFieldInputConfigType.TEXT,+ required=False,+ placeholder="metrics/visits,metrics/visitors,metrics/pageviews",+ secret=False,+ ),+ SourceFieldInputConfig(+ name="start_date",+ label="Start date",+ type=SourceFieldInputConfigType.TEXT,+ required=False,+ placeholder="YYYY-MM-DD (defaults to 90 days ago)",+ secret=False,+ ),+ ],+ ),+ )++ def get_canonical_descriptions(self) -> CanonicalDescriptions:+ from products.warehouse_sources.backend.temporal.data_imports.sources.adobe_analytics.canonical_descriptions import (+ CANONICAL_DESCRIPTIONS,+ )++ return CANONICAL_DESCRIPTIONS++ def get_schemas(+ self,+ config: AdobeAnalyticsSourceConfig,+ team_id: int,+ with_counts: bool = False,+ names: list[str] | None = None,+ force_refresh: bool = False,+ api_version: str | None = None,+ ) -> list[SourceSchema]:+ schemas = build_endpoint_schemas(ENDPOINTS, INCREMENTAL_FIELDS, names)+ for schema in schemas:+ schema.detected_primary_keys = ADOBE_ANALYTICS_ENDPOINTS[schema.name].primary_key+ return schemas++ def validate_credentials(+ self,+ config: AdobeAnalyticsSourceConfig,+ team_id: int,+ schema_name: Optional[str] = None,+ api_version: str | None = None,+ ) -> tuple[bool, str | None]:+ return validate_adobe_analytics_credentials(+ config.client_id, config.client_secret, config.global_company_id, logger+ )++ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[AdobeAnalyticsResumeConfig]:+ # Report day windows and metadata page numbers are incompatible cursors, so each+ # schema keeps its resume state in its own slot.+ return ResumableSourceManager[AdobeAnalyticsResumeConfig](+ inputs, AdobeAnalyticsResumeConfig, namespace=inputs.schema_name+ )++ def source_for_pipeline(+ self,+ config: AdobeAnalyticsSourceConfig,+ resumable_source_manager: ResumableSourceManager[AdobeAnalyticsResumeConfig],+ inputs: SourceInputs,+ ) -> SourceResponse:+ return adobe_analytics_source(+ client_id=config.client_id,+ client_secret=config.client_secret,+ global_company_id=config.global_company_id,+ report_suite_id=config.report_suite_id,+ report_dimension=config.report_dimension,+ report_metrics=config.report_metrics,+ start_date=config.start_date,+ 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/products/warehouse_sources/backend/temporal/data_imports/sources/adobe_analytics/tests/test_adobe_analytics.py b/products/warehouse_sources/backend/temporal/data_imports/sources/adobe_analytics/tests/test_adobe_analytics.pynew file mode 100644index 000000000000..3e283b58298c--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/adobe_analytics/tests/test_adobe_analytics.py@@ -0,0 +1,723 @@+import contextlib+from collections.abc import Iterator+from datetime import UTC, date, datetime, timedelta+from typing import Any, cast++import pytest+from unittest import mock++import requests+from structlog.types import FilteringBoundLogger++from products.warehouse_sources.backend.temporal.data_imports.sources.adobe_analytics.adobe_analytics import (+ ANALYTICS_HOST,+ DISCOVERY_URL,+ IMS_TOKEN_URL,+ AdobeAnalyticsClient,+ AdobeAnalyticsResumeConfig,+ adobe_analytics_source,+ build_report_body,+ get_rows,+ metric_column_names,+ parse_date,+ parse_metrics,+ report_rows,+ resolve_window,+ validate_credentials,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.adobe_analytics.settings import (+ ADOBE_ANALYTICS_ENDPOINTS,+ ENDPOINTS,+ REPORT_PAGE_SIZE,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager++_MODULE = "products.warehouse_sources.backend.temporal.data_imports.sources.adobe_analytics.adobe_analytics"++_LOGGER = cast(FilteringBoundLogger, mock.MagicMock())+++class FakeResumeManager(ResumableSourceManager[AdobeAnalyticsResumeConfig]):+ """In-memory stand-in for the Redis-backed manager."""++ def __init__(self, state: AdobeAnalyticsResumeConfig | None = None) -> None:+ self.state = state+ self.saved: list[AdobeAnalyticsResumeConfig] = []+ self.cleared = 0++ def can_resume(self) -> bool:+ return self.state is not None++ def load_state(self) -> AdobeAnalyticsResumeConfig | None:+ return self.state++ def save_state(self, data: AdobeAnalyticsResumeConfig) -> None:+ self.saved.append(data)++ def clear_state(self) -> None:+ self.cleared += 1+++def _response(body: Any, status: int = 200) -> mock.MagicMock:+ response = mock.MagicMock()+ response.json.return_value = body+ response.status_code = status+ response.ok = status < 400+ response.text = ""+ if status >= 400:+ response.raise_for_status.side_effect = requests.HTTPError(+ f"{status} Client Error", response=cast(requests.Response, response)+ )+ else:+ response.raise_for_status.return_value = None+ return response+++def _report_payload(rows: list[dict[str, Any]], last_page: bool = True, total_pages: int | None = 1) -> dict[str, Any]:+ payload: dict[str, Any] = {"rows": rows, "lastPage": last_page}+ if total_pages is not None:+ payload["totalPages"] = total_pages+ return payload+++def _sessions() -> Iterator[tuple[mock.MagicMock, mock.MagicMock]]:+ """Patch the tracked-session factory, splitting the API session from the token-exchange one."""+ api = mock.MagicMock()+ auth = mock.MagicMock()+ auth.post.return_value = _response({"access_token": "tok", "expires_in": 86399})++ def factory(**kwargs: Any) -> mock.MagicMock:+ return auth if kwargs.get("capture") is False else api++ with mock.patch(f"{_MODULE}.make_tracked_session", side_effect=factory):+ yield api, auth++[email protected](autouse=True)+def _no_sleep() -> Iterator[mock.MagicMock]:+ with mock.patch(f"{_MODULE}.time.sleep") as sleep:+ yield sleep+++def _get_rows(+ api_side_effect: list[mock.MagicMock] | None,+ post_side_effect: list[mock.MagicMock] | None,+ endpoint: str,+ manager: FakeResumeManager,+ **overrides: Any,+) -> list[list[dict[str, Any]]]:+ with _sessions() as (api, _auth):+ if api_side_effect is not None:+ api.get.side_effect = api_side_effect+ if post_side_effect is not None:+ api.post.side_effect = post_side_effect+ kwargs: dict[str, Any] = {+ "client_id": "cid",+ "client_secret": "sec",+ "global_company_id": "gcid",+ "report_suite_id": "rs1",+ "report_dimension": None,+ "report_metrics": None,+ "start_date": None,+ "endpoint": endpoint,+ "logger": _LOGGER,+ "resumable_source_manager": manager,+ }+ kwargs.update(overrides)+ batches = list(get_rows(**kwargs))+ return batches+++class TestParseDate:+ @pytest.mark.parametrize(+ "value, expected",+ [+ (datetime(2024, 1, 2, 3, 4, 5, tzinfo=UTC), date(2024, 1, 2)),+ (datetime(2024, 1, 2, 3, 4, 5), date(2024, 1, 2)),+ (date(2024, 1, 2), date(2024, 1, 2)),+ ("2024-01-02", date(2024, 1, 2)),+ ("2024-01-02T03:04:05Z", date(2024, 1, 2)),+ ("", None),+ (None, None),+ ("not-a-date", None),+ ],+ )+ def test_parse_date(self, value: Any, expected: date | None) -> None:+ assert parse_date(value) == expected+++class TestParseMetrics:+ @pytest.mark.parametrize(+ "raw, expected",+ [+ (None, ["metrics/visits", "metrics/visitors", "metrics/pageviews"]),+ ("", ["metrics/visits", "metrics/visitors", "metrics/pageviews"]),+ (" , ", ["metrics/visits", "metrics/visitors", "metrics/pageviews"]),+ ("metrics/visits", ["metrics/visits"]),+ (" metrics/visits , metrics/orders ", ["metrics/visits", "metrics/orders"]),+ ],+ )+ def test_parse_metrics(self, raw: str | None, expected: list[str]) -> None:+ assert parse_metrics(raw) == expected+++class TestMetricColumnNames:+ @pytest.mark.parametrize(+ "metric_ids, expected",+ [+ (["metrics/visits", "metrics/pageviews"], ["visits", "pageviews"]),+ (["cm300000123_5f8a"], ["cm300000123_5f8a"]),+ (["metrics/event1.2"], ["event1_2"]),+ # Two different metric ids can collapse to the same leaf; keep both columns.+ (["metrics/visits", "other/visits"], ["visits", "visits_2"]),+ ],+ )+ def test_metric_column_names(self, metric_ids: list[str], expected: list[str]) -> None:+ assert metric_column_names(metric_ids) == expected+++class TestResolveWindow:+ @pytest.mark.parametrize(+ "start_date, incremental, last_value, expected_start",+ [+ # Adobe restates recent days, so an incremental run re-reads one trailing day.+ (None, True, "2024-03-05", date(2024, 3, 4)),+ ("2024-01-01", True, "2024-03-05", date(2024, 3, 4)),+ # No watermark yet — fall back to the configured start date.+ ("2024-01-01", True, None, date(2024, 1, 1)),+ ("2024-01-01", False, "2024-03-05", date(2024, 1, 1)),+ # Nothing configured — backfill the default window.+ (None, False, None, date(2023, 12, 7)),+ # A start date in the future must not produce an inverted window.+ ("2099-01-01", False, None, date(2024, 3, 6)),+ # An ancient start date is clamped to the maximum backfill window so we+ # don't issue hundreds of thousands of sequential day requests.+ ("0001-01-01", False, None, date(2024, 3, 6) - timedelta(days=365 * 3)),+ ("0001-01-01", True, "0001-01-02", date(2024, 3, 6) - timedelta(days=365 * 3)),+ ],+ )+ def test_resolve_window(+ self, start_date: str | None, incremental: bool, last_value: str | None, expected_start: date+ ) -> None:+ today = date(2024, 3, 6)+ start, end = resolve_window(start_date, incremental, last_value, today)+ assert start == expected_start+ assert end == today+++class TestBuildReportBody:+ def test_body_scopes_a_single_day_and_page(self) -> None:+ body = build_report_body("rs1", "variables/page", ["metrics/visits", "metrics/orders"], date(2024, 1, 31), 2)++ assert body["rsid"] == "rs1"+ assert body["dimension"] == "variables/page"+ assert body["globalFilters"] == [+ {"type": "dateRange", "dateRange": "2024-01-31T00:00:00.000/2024-02-01T00:00:00.000"}+ ]+ assert body["metricContainer"]["metrics"] == [+ {"columnId": "0", "id": "metrics/visits"},+ {"columnId": "1", "id": "metrics/orders"},+ ]+ assert body["settings"]["page"] == 2+ assert body["settings"]["limit"] == REPORT_PAGE_SIZE+++class TestReportRows:+ def test_metric_columns_are_positional(self) -> None:+ payload = _report_payload([{"itemId": "1", "value": "Home", "data": [10, 20]}])++ rows = report_rows(payload, "rs1", date(2024, 1, 1), "variables/page", ["visits", "orders"])++ assert rows == [+ {+ "rsid": "rs1",+ "date": "2024-01-01",+ "dimension": "variables/page",+ "item_id": "1",+ "value": "Home",+ "visits": 10,+ "orders": 20,+ }+ ]++ def test_missing_metric_values_are_null_not_dropped(self) -> None:+ payload = _report_payload([{"itemId": 7, "value": "Home", "data": [10]}])++ rows = report_rows(payload, "rs1", date(2024, 1, 1), "variables/page", ["visits", "orders"])++ assert rows[0]["item_id"] == "7"+ assert rows[0]["orders"] is None++ def test_empty_report_yields_no_rows(self) -> None:+ assert report_rows({"rows": []}, "rs1", date(2024, 1, 1), "variables/page", ["visits"]) == []+++class TestClientAuth:+ def test_token_is_minted_once_and_sent_with_the_api_key(self) -> None:+ with _sessions() as (api, auth):+ api.get.return_value = _response({"content": []})+ client = AdobeAnalyticsClient("cid", "sec", _LOGGER, "gcid", min_request_interval=0)++ client.get_json("/segments")+ client.get_json("/segments")++ assert auth.post.call_count == 1+ assert auth.post.call_args.args[0] == IMS_TOKEN_URL+ assert auth.post.call_args.kwargs["data"]["grant_type"] == "client_credentials"+ headers = api.get.call_args.kwargs["headers"]+ assert headers["Authorization"] == "Bearer tok"+ assert headers["x-api-key"] == "cid"++ def test_401_remints_the_token_once_and_retries(self) -> None:+ with _sessions() as (api, auth):+ api.get.side_effect = [_response({}, 401), _response({"content": [{"id": "s1"}]})]+ client = AdobeAnalyticsClient("cid", "sec", _LOGGER, "gcid", min_request_interval=0)++ assert client.get_json("/segments") == {"content": [{"id": "s1"}]}+ assert auth.post.call_count == 2+ assert api.get.call_count == 2++ def test_persistent_401_raises(self) -> None:+ with _sessions() as (api, _auth):+ api.get.side_effect = [_response({}, 401), _response({}, 401)]+ client = AdobeAnalyticsClient("cid", "sec", _LOGGER, "gcid", min_request_interval=0)++ with pytest.raises(requests.HTTPError):+ client.get_json("/segments")++ @pytest.mark.parametrize("status", [400, 403, 404])+ def test_error_statuses_raise(self, status: int) -> None:+ with _sessions() as (api, _auth):+ api.get.return_value = _response({}, status)+ client = AdobeAnalyticsClient("cid", "sec", _LOGGER, "gcid", min_request_interval=0)++ with pytest.raises(requests.HTTPError):+ client.get_json("/segments")++ def test_requests_are_paced_under_the_throttle(self, _no_sleep: mock.MagicMock) -> None:+ with _sessions() as (api, _auth):+ api.get.return_value = _response({"content": []})+ client = AdobeAnalyticsClient("cid", "sec", _LOGGER, "gcid")++ client.get_json("/segments")+ client.get_json("/segments")++ assert _no_sleep.call_count >= 1+ assert _no_sleep.call_args.args[0] <= 0.5+++class TestGlobalCompanyIdDiscovery:+ def test_configured_id_skips_discovery(self) -> None:+ with _sessions() as (api, _auth):+ client = AdobeAnalyticsClient("cid", "sec", _LOGGER, "gcid", min_request_interval=0)++ assert client.base_url == f"{ANALYTICS_HOST}/api/gcid"+ api.get.assert_not_called()++ def test_discovers_from_discovery_me(self) -> None:+ with _sessions() as (api, _auth):+ api.get.return_value = _response({"imsOrgs": [{"companies": [{"globalCompanyId": "discovered"}]}]})+ client = AdobeAnalyticsClient("cid", "sec", _LOGGER, None, min_request_interval=0)++ assert client.resolve_global_company_id() == "discovered"+ assert api.get.call_args.args[0] == DISCOVERY_URL+ # Cached — a second call must not re-probe discovery.+ assert client.resolve_global_company_id() == "discovered"+ assert api.get.call_count == 1++ @pytest.mark.parametrize("payload", [{}, {"imsOrgs": []}, {"imsOrgs": [{"companies": []}]}])+ def test_missing_company_raises_actionable_error(self, payload: dict[str, Any]) -> None:+ with _sessions() as (api, _auth):+ api.get.return_value = _response(payload)+ client = AdobeAnalyticsClient("cid", "sec", _LOGGER, None, min_request_interval=0)++ with pytest.raises(ValueError, match="global company ID"):+ client.resolve_global_company_id()+++class TestValidateCredentials:+ def test_valid_credentials(self) -> None:+ with _sessions() as (api, _auth):+ api.get.return_value = _response({"content": []})++ assert validate_credentials("cid", "sec", "gcid", _LOGGER) == (True, None)++ def test_bad_client_credentials_are_reported(self) -> None:+ with _sessions() as (api, _auth):+ api.get.return_value = _response({}, 401)++ valid, message = validate_credentials("cid", "sec", None, _LOGGER)++ assert valid is False+ assert message is not None and "client ID and secret" in message++ def test_missing_product_profile_is_reported(self) -> None:+ with _sessions() as (api, _auth):+ api.get.side_effect = [+ _response({"imsOrgs": [{"companies": [{"globalCompanyId": "gcid"}]}]}),+ _response({}, 403),+ ]++ valid, message = validate_credentials("cid", "sec", None, _LOGGER)++ assert valid is False+ assert message is not None and "product profile" in message+++class TestMetadataEndpoints:+ def test_paginates_until_last_page_and_saves_state_between_pages(self) -> None:+ manager = FakeResumeManager()++ batches = _get_rows(+ [+ _response({"content": [{"id": "s1"}], "lastPage": False}),+ _response({"content": [{"id": "s2"}], "lastPage": True}),+ ],+ None,+ "segments",+ manager,+ )++ assert batches == [[{"id": "s1"}], [{"id": "s2"}]]+ assert manager.saved == [AdobeAnalyticsResumeConfig(page=1)]+ assert manager.cleared == 1++ def test_stops_on_an_empty_page_when_last_page_is_not_flagged(self) -> None:+ manager = FakeResumeManager()++ batches = _get_rows(+ [+ _response({"content": [{"id": "s1"}]}),+ _response({"content": []}),+ ],+ None,+ "segments",+ manager,+ )++ assert batches == [[{"id": "s1"}]]+ assert manager.cleared == 1++ def test_scopes_the_request_to_the_report_suite(self) -> None:+ manager = FakeResumeManager()++ with _sessions() as (api, _auth):+ api.get.return_value = _response({"content": [], "lastPage": True})+ list(+ get_rows(+ client_id="cid",+ client_secret="sec",+ global_company_id="gcid",+ report_suite_id="rs1",+ report_dimension=None,+ report_metrics=None,+ start_date=None,+ endpoint="segments",+ logger=_LOGGER,+ resumable_source_manager=manager,+ )+ )++ assert api.get.call_args.args[0] == f"{ANALYTICS_HOST}/api/gcid/segments"+ assert api.get.call_args.kwargs["params"]["rsids"] == "rs1"+ assert api.get.call_args.kwargs["params"]["page"] == 0++ def test_resumes_from_the_saved_page(self) -> None:+ manager = FakeResumeManager(AdobeAnalyticsResumeConfig(page=4))++ with _sessions() as (api, _auth):+ api.get.return_value = _response({"content": [{"id": "s1"}], "lastPage": True})+ list(+ get_rows(+ client_id="cid",+ client_secret="sec",+ global_company_id="gcid",+ report_suite_id="rs1",+ report_dimension=None,+ report_metrics=None,+ start_date=None,+ endpoint="segments",+ logger=_LOGGER,+ resumable_source_manager=manager,+ )+ )++ assert api.get.call_args.kwargs["params"]["page"] == 4++ @pytest.mark.parametrize("endpoint, suite_param", [("dimensions", "rsid"), ("metrics", "rsid")])+ def test_bare_array_catalogs_are_single_shot_and_carry_the_report_suite(+ self, endpoint: str, suite_param: str+ ) -> None:+ manager = FakeResumeManager()++ with _sessions() as (api, _auth):+ api.get.return_value = _response([{"id": "variables/page"}])+ batches = list(+ get_rows(+ client_id="cid",+ client_secret="sec",+ global_company_id="gcid",+ report_suite_id="rs1",+ report_dimension=None,+ report_metrics=None,+ start_date=None,+ endpoint=endpoint,+ logger=_LOGGER,+ resumable_source_manager=manager,+ )+ )++ assert batches == [[{"id": "variables/page", "rsid": "rs1"}]]+ assert api.get.call_count == 1+ assert api.get.call_args.kwargs["params"] == {suite_param: "rs1"}+ assert manager.cleared == 1++ def test_report_suites_are_not_scoped_to_a_suite(self) -> None:+ manager = FakeResumeManager()++ with _sessions() as (api, _auth):+ api.get.return_value = _response({"content": [{"rsid": "rs1"}], "lastPage": True})+ list(+ get_rows(+ client_id="cid",+ client_secret="sec",+ global_company_id="gcid",+ report_suite_id="rs1",+ report_dimension=None,+ report_metrics=None,+ start_date=None,+ endpoint="report_suites",+ logger=_LOGGER,+ resumable_source_manager=manager,+ )+ )++ assert "rsids" not in api.get.call_args.kwargs["params"]+++class TestReportEndpoint:+ @mock.patch(f"{_MODULE}._today", return_value=date(2024, 1, 3))+ def test_walks_day_windows_ascending_and_checkpoints_each_day(self, _mock_today: mock.MagicMock) -> None:+ manager = FakeResumeManager()++ with _sessions() as (api, _auth):+ api.post.side_effect = [+ _response(_report_payload([{"itemId": "1", "value": "2024-01-02", "data": [1, 2, 3]}])),+ _response(_report_payload([{"itemId": "2", "value": "2024-01-03", "data": [4, 5, 6]}])),+ ]+ batches = list(+ get_rows(+ client_id="cid",+ client_secret="sec",+ global_company_id="gcid",+ report_suite_id="rs1",+ report_dimension=None,+ report_metrics=None,+ start_date="2024-01-02",+ endpoint="report",+ logger=_LOGGER,+ resumable_source_manager=manager,+ )+ )++ assert [row["date"] for batch in batches for row in batch] == ["2024-01-02", "2024-01-03"]+ assert batches[0][0]["visits"] == 1+ assert batches[0][0]["pageviews"] == 3+ bodies = [call.kwargs["json"] for call in api.post.call_args_list]+ assert [body["globalFilters"][0]["dateRange"].split("/")[0][:10] for body in bodies] == [+ "2024-01-02",+ "2024-01-03",+ ]+ # Checkpoint advances to the next unfetched day, never past the window.+ assert manager.saved == [AdobeAnalyticsResumeConfig(page=0, next_date="2024-01-03")]+ assert manager.cleared == 1++ @mock.patch(f"{_MODULE}._today", return_value=date(2024, 1, 1))+ def test_pages_within_a_day_before_advancing(self, _mock_today: mock.MagicMock) -> None:+ manager = FakeResumeManager()++ with _sessions() as (api, _auth):+ api.post.side_effect = [+ _response(+ _report_payload([{"itemId": "1", "value": "a", "data": [1]}], last_page=False, total_pages=2)+ ),+ _response(_report_payload([{"itemId": "2", "value": "b", "data": [2]}], last_page=True, total_pages=2)),+ ]+ batches = list(+ get_rows(+ client_id="cid",+ client_secret="sec",+ global_company_id="gcid",+ report_suite_id="rs1",+ report_dimension="variables/page",+ report_metrics="metrics/visits",+ start_date="2024-01-01",+ endpoint="report",+ logger=_LOGGER,+ resumable_source_manager=manager,+ )+ )++ assert len(batches) == 2+ assert [call.kwargs["json"]["settings"]["page"] for call in api.post.call_args_list] == [0, 1]+ assert manager.saved == [AdobeAnalyticsResumeConfig(page=1, next_date="2024-01-01")]++ @mock.patch(f"{_MODULE}._today", return_value=date(2024, 1, 3))+ def test_resumes_mid_window_from_saved_day_and_page(self, _mock_today: mock.MagicMock) -> None:+ manager = FakeResumeManager(AdobeAnalyticsResumeConfig(page=2, next_date="2024-01-03"))++ with _sessions() as (api, _auth):+ api.post.return_value = _response(_report_payload([]))+ list(+ get_rows(+ client_id="cid",+ client_secret="sec",+ global_company_id="gcid",+ report_suite_id="rs1",+ report_dimension=None,+ report_metrics=None,+ start_date="2024-01-01",+ endpoint="report",+ logger=_LOGGER,+ resumable_source_manager=manager,+ )+ )++ assert api.post.call_count == 1+ body = api.post.call_args.kwargs["json"]+ assert body["globalFilters"][0]["dateRange"].startswith("2024-01-03")+ assert body["settings"]["page"] == 2++ @mock.patch(f"{_MODULE}._today", return_value=date(2024, 1, 3))+ def test_stale_resume_state_outside_the_window_is_ignored(self, _mock_today: mock.MagicMock) -> None:+ manager = FakeResumeManager(AdobeAnalyticsResumeConfig(page=5, next_date="2020-01-01"))++ with _sessions() as (api, _auth):+ api.post.return_value = _response(_report_payload([]))+ list(+ get_rows(+ client_id="cid",+ client_secret="sec",+ global_company_id="gcid",+ report_suite_id="rs1",+ report_dimension=None,+ report_metrics=None,+ start_date="2024-01-03",+ endpoint="report",+ logger=_LOGGER,+ resumable_source_manager=manager,+ )+ )++ body = api.post.call_args.kwargs["json"]+ assert body["globalFilters"][0]["dateRange"].startswith("2024-01-03")+ assert body["settings"]["page"] == 0++ @mock.patch(f"{_MODULE}._today", return_value=date(2024, 3, 6))+ def test_incremental_run_re_reads_the_restatement_window(self, _mock_today: mock.MagicMock) -> None:+ manager = FakeResumeManager()++ with _sessions() as (api, _auth):+ api.post.return_value = _response(_report_payload([]))+ list(+ get_rows(+ client_id="cid",+ client_secret="sec",+ global_company_id="gcid",+ report_suite_id="rs1",+ report_dimension=None,+ report_metrics=None,+ start_date="2020-01-01",+ endpoint="report",+ logger=_LOGGER,+ resumable_source_manager=manager,+ should_use_incremental_field=True,+ db_incremental_field_last_value="2024-03-05",+ )+ )++ days = [call.kwargs["json"]["globalFilters"][0]["dateRange"][:10] for call in api.post.call_args_list]+ assert days == ["2024-03-04", "2024-03-05", "2024-03-06"]++ @mock.patch(f"{_MODULE}.MAX_REPORT_PAGES", 3)+ @mock.patch(f"{_MODULE}._today", return_value=date(2024, 1, 1))+ def test_page_cap_terminates_a_report_that_never_signals_completion(self, _mock_today: mock.MagicMock) -> None:+ manager = FakeResumeManager()++ with _sessions() as (api, _auth):+ # No `lastPage`, no `totalPages`, always rows — the cap is the only exit.+ api.post.return_value = _response({"rows": [{"itemId": "1", "value": "a", "data": [1]}]})+ batches = list(+ get_rows(+ client_id="cid",+ client_secret="sec",+ global_company_id="gcid",+ report_suite_id="rs1",+ report_dimension=None,+ report_metrics=None,+ start_date="2024-01-01",+ endpoint="report",+ logger=_LOGGER,+ resumable_source_manager=manager,+ )+ )++ assert len(batches) == 3+ assert api.post.call_count == 3+++class TestAdobeAnalyticsSourceResponse:+ @pytest.mark.parametrize("endpoint", ENDPOINTS)+ def test_primary_keys_match_the_endpoint_catalog(self, endpoint: str) -> None:+ response = adobe_analytics_source(+ client_id="cid",+ client_secret="sec",+ global_company_id="gcid",+ report_suite_id="rs1",+ report_dimension=None,+ report_metrics=None,+ start_date=None,+ endpoint=endpoint,+ logger=_LOGGER,+ resumable_source_manager=FakeResumeManager(),+ )++ assert response.name == endpoint+ assert response.primary_keys == ADOBE_ANALYTICS_ENDPOINTS[endpoint].primary_key+ assert response.sort_mode == "asc"++ def test_report_is_partitioned_on_the_stable_day_column(self) -> None:+ response = adobe_analytics_source(+ client_id="cid",+ client_secret="sec",+ global_company_id="gcid",+ report_suite_id="rs1",+ report_dimension=None,+ report_metrics=None,+ start_date=None,+ endpoint="report",+ logger=_LOGGER,+ resumable_source_manager=FakeResumeManager(),+ )++ assert response.partition_mode == "datetime"+ assert response.partition_keys == ["date"]+ assert response.partition_format == "month"++ def test_metadata_tables_are_not_datetime_partitioned(self) -> None:+ response = adobe_analytics_source(+ client_id="cid",+ client_secret="sec",+ global_company_id="gcid",+ report_suite_id="rs1",+ report_dimension=None,+ report_metrics=None,+ start_date=None,+ endpoint="segments",+ logger=_LOGGER,+ resumable_source_manager=FakeResumeManager(),+ )++ assert response.partition_mode is None+ assert response.partition_keys is Nonediff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/adobe_analytics/tests/test_adobe_analytics_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/adobe_analytics/tests/test_adobe_analytics_source.pynew file mode 100644index 000000000000..74707c0cfb35--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/adobe_analytics/tests/test_adobe_analytics_source.py@@ -0,0 +1,184 @@+import pytest+from unittest import mock++from posthog.schema import ReleaseStatus, SourceFieldInputConfig, SourceFieldInputConfigType++from products.warehouse_sources.backend.temporal.data_imports.sources.adobe_analytics.adobe_analytics import (+ AdobeAnalyticsResumeConfig,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.adobe_analytics.settings import (+ ENDPOINTS,+ INCREMENTAL_FIELDS,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.adobe_analytics.source import AdobeAnalyticsSource+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.adobeanalytics import (+ AdobeAnalyticsSourceConfig,+)+from products.warehouse_sources.backend.types import ExternalDataSourceType++_SOURCE_MODULE = "products.warehouse_sources.backend.temporal.data_imports.sources.adobe_analytics.source"+++class TestAdobeAnalyticsSource:+ def setup_method(self) -> None:+ self.source = AdobeAnalyticsSource()+ self.team_id = 123+ self.config = AdobeAnalyticsSourceConfig(+ client_id="cid",+ client_secret="sec",+ report_suite_id="rs1",+ global_company_id="gcid",+ )++ def test_source_type(self) -> None:+ assert self.source.source_type == ExternalDataSourceType.ADOBEANALYTICS++ def test_get_source_config(self) -> None:+ config = self.source.get_source_config++ assert config.name.value == "AdobeAnalytics"+ assert config.label == "Adobe Analytics"+ assert config.releaseStatus == ReleaseStatus.ALPHA+ assert config.unreleasedSource is None+ assert config.iconPath == "/static/services/adobe_analytics.png"++ assert [f.name for f in config.fields] == [+ "client_id",+ "client_secret",+ "report_suite_id",+ "global_company_id",+ "report_dimension",+ "report_metrics",+ "start_date",+ ]++ def test_client_secret_is_a_redacted_password_field(self) -> None:+ config = self.source.get_source_config+ field = next(f for f in config.fields if isinstance(f, SourceFieldInputConfig) and f.name == "client_secret")++ assert field.type == SourceFieldInputConfigType.PASSWORD+ assert field.secret is True+ assert field.required is True++ @pytest.mark.parametrize(+ "field_name",+ ["global_company_id", "report_dimension", "report_metrics", "start_date"],+ )+ def test_derivable_fields_are_optional(self, field_name: str) -> None:+ config = self.source.get_source_config+ field = next(f for f in config.fields if isinstance(f, SourceFieldInputConfig) and f.name == field_name)++ assert field.required is False++ @pytest.mark.parametrize(+ "observed_error",+ [+ "400 Client Error: Bad Request for url: https://ims-na1.adobelogin.com/ims/token/v3",+ "401 Client Error: Unauthorized for url: https://analytics.adobe.io/api/gcid/reports",+ "403 Client Error: Forbidden for url: https://analytics.adobe.io/api/gcid/segments",+ ],+ )+ def test_non_retryable_errors_match_auth_failures(self, observed_error: str) -> None:+ assert any(key in observed_error for key in self.source.get_non_retryable_errors())++ @pytest.mark.parametrize(+ "other_error",+ [+ "429 Client Error: Too Many Requests for url: https://analytics.adobe.io/api/gcid/reports",+ "500 Server Error for url: https://analytics.adobe.io/api/gcid/reports",+ "401 Client Error: Unauthorized for url: https://api.stripe.com/v1/customers",+ ],+ )+ def test_non_retryable_errors_do_not_swallow_transient_or_unrelated_failures(self, other_error: str) -> None:+ assert not any(key in other_error for key in self.source.get_non_retryable_errors())++ def test_get_schemas_lists_the_endpoint_catalog(self) -> None:+ schemas = self.source.get_schemas(self.config, self.team_id)++ assert {schema.name for schema in schemas} == set(ENDPOINTS)+ # Only the reporting stream has a server-side date filter to sync incrementally on.+ assert {schema.name for schema in schemas if schema.supports_incremental} == {"report"}++ def test_report_schema_advertises_its_date_cursor(self) -> None:+ schemas = {schema.name: schema for schema in self.source.get_schemas(self.config, self.team_id)}++ assert schemas["report"].incremental_fields == INCREMENTAL_FIELDS["report"]+ assert [f["field"] for f in schemas["report"].incremental_fields] == ["date"]+ assert schemas["segments"].incremental_fields == []+ assert schemas["segments"].supports_append is False++ def test_get_schemas_filtered_by_names(self) -> None:+ schemas = self.source.get_schemas(self.config, self.team_id, names=["report"])++ assert [schema.name for schema in schemas] == ["report"]++ def test_get_schemas_filtered_unknown_name_returns_empty(self) -> None:+ assert self.source.get_schemas(self.config, self.team_id, names=["nope"]) == []++ def test_documented_tables_render_without_credentials(self) -> None:+ tables = self.source.get_documented_tables()++ assert {table["name"] for table in tables} == set(ENDPOINTS)+ report = next(table for table in tables if table["name"] == "report")+ assert report["primary_keys"] == ["rsid", "date", "item_id"]+ assert report["description"] is not None++ def test_canonical_descriptions_cover_every_endpoint(self) -> None:+ descriptions = self.source.get_canonical_descriptions()++ assert set(descriptions) == set(ENDPOINTS)++ @pytest.mark.parametrize(+ "transport_result",+ [(True, None), (False, "Adobe Analytics rejected the credentials.")],+ )+ @mock.patch(f"{_SOURCE_MODULE}.validate_adobe_analytics_credentials")+ def test_validate_credentials_delegates_to_the_transport(+ self, mock_validate: mock.MagicMock, transport_result: tuple[bool, str | None]+ ) -> None:+ mock_validate.return_value = transport_result++ assert self.source.validate_credentials(self.config, self.team_id) == transport_result+ assert mock_validate.call_args.args[:3] == ("cid", "sec", "gcid")++ def test_resumable_manager_is_namespaced_per_schema(self) -> None:+ inputs = mock.MagicMock()+ inputs.schema_name = "report"++ manager = self.source.get_resumable_source_manager(inputs)++ assert isinstance(manager, ResumableSourceManager)+ assert manager._data_class is AdobeAnalyticsResumeConfig+ assert manager._namespace == "report"++ @mock.patch(f"{_SOURCE_MODULE}.adobe_analytics_source")+ def test_source_for_pipeline_plumbs_arguments(self, mock_source: mock.MagicMock) -> None:+ inputs = mock.MagicMock()+ inputs.schema_name = "report"+ inputs.should_use_incremental_field = True+ inputs.db_incremental_field_last_value = "2024-05-01"+ manager = mock.MagicMock()++ self.source.source_for_pipeline(self.config, manager, inputs)++ kwargs = mock_source.call_args.kwargs+ assert kwargs["client_id"] == "cid"+ assert kwargs["client_secret"] == "sec"+ assert kwargs["global_company_id"] == "gcid"+ assert kwargs["report_suite_id"] == "rs1"+ assert kwargs["endpoint"] == "report"+ assert kwargs["resumable_source_manager"] is manager+ assert kwargs["should_use_incremental_field"] is True+ assert kwargs["db_incremental_field_last_value"] == "2024-05-01"++ @mock.patch(f"{_SOURCE_MODULE}.adobe_analytics_source")+ def test_source_for_pipeline_omits_last_value_on_full_refresh(self, mock_source: mock.MagicMock) -> None:+ inputs = mock.MagicMock()+ inputs.schema_name = "segments"+ inputs.should_use_incremental_field = False+ inputs.db_incremental_field_last_value = "2024-05-01"++ self.source.source_for_pipeline(self.config, mock.MagicMock(), inputs)++ assert mock_source.call_args.kwargs["db_incremental_field_last_value"] is Nonediff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/adobeanalytics.py b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/adobeanalytics.pyindex 123396ad6cc8..ff5ef412304d 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/adobeanalytics.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/adobeanalytics.py@@ -6,4 +6,10 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common imp@config.configclass AdobeAnalyticsSourceConfig(config.Config):- pass+ client_id: str+ client_secret: str+ report_suite_id: str+ global_company_id: str | None = None+ report_dimension: str | None = None+ report_metrics: str | None = None+ start_date: str | None = None