: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): add four missing Fastly tables (#107708)
Tom Owers219637eb7bcc
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.mdindex dbb2a6932206..06413e92bcb7 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@@ -3014,23 +3014,23 @@ Note: The reference exposes roughly 140 list endpoints across ATS, attendance, c## Fastly — **thin**-Today (11): `acl_entries`, `billing_usage_metrics`, `current_user`, `dictionary_items`, `invoices`, `service_acls`, `service_backends`, `service_dictionaries`, `service_domains`, `service_versions`, `services`+Today (15): `acl_entries`, `billing_usage_metrics`, `current_user`, `dictionary_items`, `historical_stats`, `invoices`, `origin_inspector`, `pops`, `service_acls`, `service_authorizations`, `service_backends`, `service_dictionaries`, `service_domains`, `service_versions`, `services`Diffed against: <https://www.fastly.com/documentation/reference/api/>-- [ ] `metrics-stats/historical-stats (/stats, /stats/service/{id})` — per-service historical traffic, cache hit ratio, bandwidth and errors - Fastly's headline metric and the main reason to warehouse this data (high)+- [x] `metrics-stats/historical-stats (/stats, /stats/service/{id})` — per-service historical traffic, cache hit ratio, bandwidth and errors - Fastly's headline metric and the main reason to warehouse this data (high)- [x] `account/billing-usage-metrics` — usage and spend per product and service over time (high)- [x] `dictionaries/dictionary-item` — lookup table - the actual key/value rows inside the service_dictionaries we already sync (high)- [x] `acls/acl-entry` — lookup table - the IP entries inside the service_acls we already sync (high)- [x] `account/invoices` — billed amounts per period for cost reporting (high)-- [ ] `metrics-stats/origin-inspector` — origin-level latency, status and byte breakdowns (medium)+- [x] `metrics-stats/origin-inspector` — origin-level latency, status and byte breakdowns (medium)- [ ] `metrics-stats/domain-inspector` — per-domain request and error breakdowns, the natural dimension for service_domains (medium)- [ ] `account/events` — account audit event log - who changed what and when (medium)- [ ] `account/customer (and its users list)` — lookup resolving customer ids on services and users; today only current_user is synced (medium)-- [ ] `account/service-authorization` — user-to-service permission membership table (medium)-- [ ] `utils/pops` — lookup resolving POP/datacenter codes that appear in stats and inspector breakdowns (medium)+- [x] `account/service-authorization` — user-to-service permission membership table (medium)+- [x] `utils/pops` — lookup resolving POP/datacenter codes that appear in stats and inspector breakdowns (medium)-Note: Coverage is service configuration objects plus the account/billing family; none of the metrics-stats family is exposed. Fastly's own OpenAPI YAML is no longer served at the old developer.fastly.com path (404) - the category tree was read from the live documentation reference index and its per-category pages. Logging endpoint types (~25 of them), TLS, purging and VCL objects are config/plumbing and deliberately excluded.+Note: Coverage is service configuration objects, the account/billing family, and the historical stats and Origin Inspector halves of metrics-stats; the domain inspector and bots halves are not exposed. Fastly's own OpenAPI YAML is no longer served at the old developer.fastly.com path (404) - the category tree was read from the live documentation reference index and its per-category pages. Logging endpoint types (~25 of them), TLS, purging and VCL objects are config/plumbing and deliberately excluded.## Featurebase — **thin**diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/fastly/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/fastly/canonical_descriptions.pyindex 805b45c01e65..368d1db313ba 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/fastly/canonical_descriptions.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/fastly/canonical_descriptions.py@@ -137,6 +137,76 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {"deleted_at": "Timestamp (UTC) of when the item was deleted, if applicable.",},},+ "historical_stats": {+ "description": "Daily traffic, cache hit ratio, bandwidth and error counts for every service.",+ "docs_url": "https://www.fastly.com/documentation/reference/api/metrics-stats/historical-stats/",+ "columns": {+ "service_id": "Alphanumeric string identifying the service the sample belongs to.",+ "start_time": "Unix timestamp for the start of the day the sample covers.",+ "requests": "Number of requests processed.",+ "edge_requests": "Number of requests sent by end users to Fastly.",+ "hits": "Number of cache hits.",+ "miss": "Number of cache misses.",+ "errors": "Number of cache errors.",+ "hit_ratio": "Ratio of cache hits to cache misses, between 0 and 1.",+ "uncacheable": "Number of requests that were designated uncacheable.",+ "synth": "Number of requests that returned a synthetic response.",+ "origin_fetches": "Number of requests sent to origin.",+ "bandwidth": "Total bytes delivered, header and body, across every delivery path.",+ "resp_body_bytes": "Total body bytes delivered.",+ "resp_header_bytes": "Total header bytes delivered.",+ "status_2xx": 'Number of "Success" status codes delivered.',+ "status_3xx": 'Number of "Redirection" codes delivered.',+ "status_4xx": 'Number of "Client Error" codes delivered.',+ "status_5xx": 'Number of "Server Error" codes delivered.',+ },+ },+ "origin_inspector": {+ "description": "Daily origin latency, status code and byte counts per origin host, for services with Origin Inspector enabled.",+ "docs_url": "https://www.fastly.com/documentation/reference/api/metrics-stats/origin-inspector/historical/",+ "columns": {+ "service_id": "Alphanumeric string identifying the service the sample belongs to.",+ "host": "The origin host the responses in this sample came from.",+ "start_time": "Unix timestamp for the start of the day the sample covers.",+ "responses": "Number of responses from origin.",+ "resp_header_bytes": "Number of header bytes from origin.",+ "resp_body_bytes": "Number of body bytes from origin.",+ "status_2xx": 'Number of 2xx "Success" status codes delivered from origin.',+ "status_3xx": 'Number of 3xx "Redirection" codes delivered from origin.',+ "status_4xx": 'Number of 4xx "Client Error" codes delivered from origin.',+ "status_5xx": 'Number of 5xx "Server Error" codes delivered from origin.',+ "latency_0_to_1ms": "Number of responses from origin with latency between 0 and 1 millisecond.",+ "latency_1000_to_5000ms": "Number of responses from origin with latency between 1,000 and 5,000 milliseconds.",+ },+ },+ "service_authorizations": {+ "description": "Which users can reach which services, and the permission each one holds.",+ "docs_url": "https://www.fastly.com/documentation/reference/api/account/service-authorization/",+ "columns": {+ "id": "Alphanumeric string identifying a service authorization.",+ "type": "Resource type.",+ "permission": "The permission the user has in relation to the service.",+ "service_id": "Alphanumeric string identifying the service access is granted to.",+ "user_id": "The ID of the user being given access to the service.",+ "created_at": "Timestamp (UTC) of when the authorization was created.",+ "updated_at": "Timestamp (UTC) of when the authorization was last updated.",+ "deleted_at": "Timestamp (UTC) of when the authorization was deleted, if applicable.",+ },+ },+ "pops": {+ "description": "Every Fastly POP, with the datacenter codes used in stats and origin metrics.",+ "docs_url": "https://www.fastly.com/documentation/reference/api/utils/pops/",+ "columns": {+ "code": "The three-letter code for the POP.",+ "name": "The name of the POP.",+ "group": "The group the POP belongs to.",+ "region": "The region the POP sits in.",+ "stats_region": "The region used for stats reporting.",+ "billing_region": "The region used for billing.",+ "coordinates": "The latitude and longitude of the POP.",+ "shield": "The shield code for this POP, if it is suitable for shielding.",+ },+ },"invoices": {"description": "Posted invoices for the account, with the line items billed on each.","docs_url": "https://www.fastly.com/documentation/reference/api/account/invoices/",diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/fastly/fastly.py b/products/warehouse_sources/backend/temporal/data_imports/sources/fastly/fastly.pyindex c88e1cc16294..1343707bfd58 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/fastly/fastly.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/fastly/fastly.py@@ -1,9 +1,10 @@from collections.abc import Iteratorfrom datetime import UTC, datetimefrom typing import Any-from urllib.parse import urlencode+from urllib.parse import urlencode, urljoin, urlsplitimport requests+from dateutil import parser as date_parserfrom structlog.types import FilteringBoundLoggerfrom tenacity import retry, retry_if_exception_type, stop_after_attempt, wait_exponential_jitter@@ -32,6 +33,27 @@ INVOICE_PAGE_LIMIT = 200# The usage metrics API rejects a window longer than three months, so ask for the three ending now.USAGE_METRICS_MONTHS = 3+# `/service-authorizations` is JSON:API and pages with `page[size]`, capped at 100.+SERVICE_AUTHORIZATION_PAGE_SIZE = 100++# Origin Inspector caps `limit` (timeseries per page) at 200.+ORIGIN_INSPECTOR_PAGE_LIMIT = 200++# Both metrics families are read in whole days. Day buckets close around 2am the following day, and+# a day is the coarsest bucket, so it keeps the row count proportionate to a warehouse table.+METRICS_DOWNSAMPLE = "day"++# Origin Inspector groups its timeseries by origin host, which is the breakdown the table is for.+ORIGIN_INSPECTOR_GROUP_BY = "host"++# Length in seconds of each bucket Fastly's metrics APIs report, by downsample name.+BUCKET_SECONDS: dict[str, int] = {"minute": 60, "hour": 60 * 60, "day": 24 * 60 * 60}++# A service without the Origin Inspector upgrade cannot serve its origin metrics. Fastly's docs do+# not pin down which status that is, so treat both refusals as "not enabled here" and move on rather+# than failing every other service's rows with it.+ORIGIN_INSPECTOR_UNAVAILABLE_STATUSES = frozenset({403, 404})+class FastlyRetryableError(Exception):pass@@ -54,14 +76,22 @@ class FastlyResumeConfig:cursor_request: str | None = None+@frozen+class _BucketTimeline:+ """The time grid an Origin Inspector page's `values` array is indexed against."""++ first_start_time: int+ bucket_seconds: int++def _get_headers(api_key: str) -> dict[str, str]:return {"Fastly-Key": api_key, "Accept": "application/json"}-def _build_url(base_url: str, params: dict[str, Any]) -> str:+def _build_url(base_url: str, params: dict[str, Any], safe: str = "") -> str:if not params:return base_url- return f"{base_url}?{urlencode(params)}"+ return f"{base_url}?{urlencode(params, safe=safe)}"@retry(@@ -93,9 +123,42 @@ def _fetch(return response+def _fetch_optional(+ session: requests.Session,+ url: str,+ headers: dict[str, str],+ logger: FilteringBoundLogger,+ ignore_statuses: frozenset[int],+) -> requests.Response | None:+ """Fetch a URL, returning None when the API refuses it with one of `ignore_statuses`."""+ try:+ return _fetch(session, url, headers, logger)+ except requests.HTTPError as error:+ status = error.response.status_code if error.response is not None else None+ if status in ignore_statuses:+ return None+ raise+++def _require_fastly_host(url: str | None) -> str | None:+ """Reject a next-page URL that points anywhere but the Fastly API.++ Every request carries the customer's token in the `Fastly-Key` header, and a next-page link is+ read from a response rather than built here, so a link naming another host would send the token+ to that host. A resumed URL gets the same check, because it was a response link when it was+ stored."""+ if url is None:+ return None+ base = urlsplit(FASTLY_BASE_URL)+ target = urlsplit(url)+ if (target.scheme, target.netloc) != (base.scheme, base.netloc):+ raise FastlyPaginationError(f"Fastly returned a next page link outside the API host: {url}")+ return url++def _next_page_url(response: requests.Response) -> str | None:"""Fastly signals the next page of `/service` via a standard `Link: <...>; rel="next"` header."""- return response.links.get("next", {}).get("url")+ return _require_fastly_host(response.links.get("next", {}).get("url"))def validate_credentials(api_key: str) -> bool:@@ -183,6 +246,99 @@ def _flatten_usage_metrics(payload: dict[str, Any]) -> list[dict[str, Any]]:return rows+def _as_epoch_seconds(value: Any) -> int | None:+ """Normalise a watermark into the Unix seconds the `from` / `start` params take."""+ if value is None or isinstance(value, bool):+ return None+ if isinstance(value, datetime):+ return int(value.timestamp())+ if isinstance(value, int | float):+ return int(value)+ return None+++def _flatten_json_api(item: dict[str, Any]) -> dict[str, Any]:+ """Lift a JSON:API resource's `attributes` into the row root and each `relationships` member down+ to a `<name>_id` column, so the row reads like every other Fastly table."""+ row = {key: value for key, value in item.items() if key not in ("attributes", "relationships")}++ attributes = item.get("attributes")+ if isinstance(attributes, dict):+ row.update(attributes)++ relationships = item.get("relationships")+ if isinstance(relationships, dict):+ for name, relationship in relationships.items():+ related = relationship.get("data") if isinstance(relationship, dict) else None+ if isinstance(related, dict):+ row[f"{name}_id"] = related.get("id")++ return row+++def _next_body_link(payload: dict[str, Any]) -> str | None:+ """Read the next page from a JSON:API `links` object. Fastly returns a path there rather than an+ absolute URL, so resolve it against the API host."""+ links = payload.get("links")+ if not isinstance(links, dict):+ return None+ next_link = links.get("next")+ if not isinstance(next_link, str) or not next_link:+ return None+ return _require_fastly_host(urljoin(FASTLY_BASE_URL, next_link))+++def _bucket_timeline(meta: dict[str, Any]) -> _BucketTimeline | None:+ """Resolve the bucket grid an Origin Inspector page reports against.++ The API returns one `values` entry per time bucket but puts no timestamp on the entry, so the+ bucket a value belongs to is its index counted forward from `meta.start`."""+ downsample = meta.get("downsample")+ bucket_seconds = BUCKET_SECONDS.get(downsample) if isinstance(downsample, str) else None+ start = meta.get("start")+ if bucket_seconds is None or not isinstance(start, str):+ return None++ try:+ parsed = date_parser.parse(start)+ except (ValueError, OverflowError):+ return None++ if parsed.tzinfo is None:+ parsed = parsed.replace(tzinfo=UTC)+ return _BucketTimeline(first_start_time=int(parsed.timestamp()), bucket_seconds=bucket_seconds)+++def _flatten_origin_inspector(payload: dict[str, Any], service_id: str) -> list[dict[str, Any]]:+ """Turn an Origin Inspector page into one row per (timeseries, time bucket)."""+ meta = payload.get("meta")+ timeline = _bucket_timeline(meta) if isinstance(meta, dict) else None+ if timeline is None:+ return []++ rows: list[dict[str, Any]] = []+ for entry in payload.get("data") or []:+ if not isinstance(entry, dict):+ continue+ dimensions = entry.get("dimensions")+ dimensions = dimensions if isinstance(dimensions, dict) else {}+ values = entry.get("values")+ if not isinstance(values, list):+ continue+ for index, value in enumerate(values):+ if not isinstance(value, dict):+ continue+ rows.append(+ {+ **dimensions,+ **value,+ "service_id": service_id,+ "start_time": timeline.first_start_time + index * timeline.bucket_seconds,+ }+ )+ return rows++def _iter_services(session: requests.Session, headers: dict[str, str], logger: FilteringBoundLogger) -> Iterator[dict[str, Any]]:@@ -229,6 +385,131 @@ def _get_object_rows(yield data+def _get_plain_list_rows(+ session: requests.Session, config: FastlyEndpointConfig, headers: dict[str, str], logger: FilteringBoundLogger+) -> Iterator[list[dict[str, Any]]]:+ response = _fetch(session, f"{FASTLY_BASE_URL}{config.path}", headers, logger)+ data = response.json()+ rows = [row for row in data if isinstance(row, dict)] if isinstance(data, list) else []+ if rows:+ yield rows+++def _get_json_api_rows(+ session: requests.Session,+ config: FastlyEndpointConfig,+ headers: dict[str, str],+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[FastlyResumeConfig],+) -> Iterator[list[dict[str, Any]]]:+ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None+ if resume is not None and resume.next_url:+ url = _require_fastly_host(resume.next_url) or ""+ logger.debug(f"Fastly: resuming {config.name} from URL: {url}")+ else:+ # Fastly documents its JSON:API pagination params with literal brackets, so send them+ # unencoded rather than as %5B / %5D.+ url = _build_url(f"{FASTLY_BASE_URL}{config.path}", {"page[size]": SERVICE_AUTHORIZATION_PAGE_SIZE}, safe="[]")++ while True:+ response = _fetch(session, url, headers, logger)+ payload = response.json()+ if not isinstance(payload, dict):+ return++ data = payload.get("data")+ rows = [_flatten_json_api(item) for item in data if isinstance(item, dict)] if isinstance(data, list) else []+ if rows:+ yield rows++ next_url = _next_body_link(payload)+ if not next_url:+ return+ if next_url == url:+ raise FastlyPaginationError(f"Fastly returned an unchanged next page link for {url}")+ # Saved AFTER yielding so a crash re-yields the last page rather than skipping it.+ resumable_source_manager.save_state(FastlyResumeConfig(next_url=next_url))+ url = next_url+++def _get_stats_rows(+ session: requests.Session,+ config: FastlyEndpointConfig,+ headers: dict[str, str],+ logger: FilteringBoundLogger,+ incremental_start: int | None,+) -> Iterator[list[dict[str, Any]]]:+ """Read `/stats`, which answers for every service in one unpaginated response keyed by service id.++ With no `from`, Fastly defaults the window to the last month, so a full refresh takes that and an+ incremental run takes everything since its watermark."""+ params: dict[str, Any] = {"by": METRICS_DOWNSAMPLE}+ if incremental_start is not None:+ params["from"] = incremental_start++ response = _fetch(session, _build_url(f"{FASTLY_BASE_URL}{config.path}", params), headers, logger)+ payload = response.json()+ data = payload.get("data") if isinstance(payload, dict) else None+ if not isinstance(data, dict):+ return++ for service_id, service_rows in data.items():+ if not isinstance(service_rows, list):+ continue+ rows = [_ensure_service_id(row, service_id) for row in service_rows if isinstance(row, dict)]+ if rows:+ yield rows+++def _get_origin_inspector_rows(+ session: requests.Session,+ config: FastlyEndpointConfig,+ headers: dict[str, str],+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[FastlyResumeConfig],+ incremental_start: int | None,+) -> Iterator[list[dict[str, Any]]]:+ params: dict[str, Any] = {+ "downsample": METRICS_DOWNSAMPLE,+ "group_by": ORIGIN_INSPECTOR_GROUP_BY,+ "limit": ORIGIN_INSPECTOR_PAGE_LIMIT,+ }+ if incremental_start is not None:+ params["start"] = incremental_start++ for service_id in _iter_services_from_bookmark(session, config, headers, logger, resumable_source_manager):+ url_base = f"{FASTLY_BASE_URL}{config.path.format(service_id=service_id)}"+ cursor: str | None = None++ while True:+ page_params = {**params, "cursor": cursor} if cursor else params+ response = _fetch_optional(+ session,+ _build_url(url_base, page_params),+ headers,+ logger,+ ORIGIN_INSPECTOR_UNAVAILABLE_STATUSES,+ )+ if response is None:+ logger.debug(f"Fastly: service {service_id} cannot serve origin metrics, skipping")+ break++ payload = response.json()+ if not isinstance(payload, dict):+ break++ rows = _flatten_origin_inspector(payload, service_id)+ if rows:+ yield rows++ next_cursor = _next_cursor(payload)+ if not next_cursor:+ break+ if next_cursor == cursor:+ raise FastlyPaginationError(f"Fastly returned an unchanged cursor for {url_base}")+ cursor = next_cursor++def _get_service_list_rows(session: requests.Session,headers: dict[str, str],@@ -237,7 +518,7 @@ def _get_service_list_rows() -> Iterator[list[dict[str, Any]]]:resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else Noneif resume is not None and resume.next_url:- url = resume.next_url+ url = _require_fastly_host(resume.next_url) or ""logger.debug(f"Fastly: resuming services from URL: {url}")else:url = _build_url(f"{FASTLY_BASE_URL}/service", {"per_page": SERVICE_PAGE_SIZE})@@ -429,6 +710,7 @@ def get_rows(endpoint: str,logger: FilteringBoundLogger,resumable_source_manager: ResumableSourceManager[FastlyResumeConfig],+ incremental_start: int | None = None,) -> Iterator[list[dict[str, Any]]]:config = FASTLY_ENDPOINTS[endpoint]headers = _get_headers(api_key)@@ -438,6 +720,16 @@ def get_rows(if config.kind == "object":yield from _get_object_rows(session, config, headers, logger)+ elif config.kind == "plain_list":+ yield from _get_plain_list_rows(session, config, headers, logger)+ elif config.kind == "json_api_list":+ yield from _get_json_api_rows(session, config, headers, logger, resumable_source_manager)+ elif config.kind == "stats_list":+ yield from _get_stats_rows(session, config, headers, logger, incremental_start)+ elif config.kind == "origin_inspector":+ yield from _get_origin_inspector_rows(+ session, config, headers, logger, resumable_source_manager, incremental_start+ )elif config.kind == "service_list":yield from _get_service_list_rows(session, headers, logger, resumable_source_manager)elif config.kind == "version_resource_child":@@ -455,8 +747,11 @@ def fastly_source(endpoint: str,logger: FilteringBoundLogger,resumable_source_manager: ResumableSourceManager[FastlyResumeConfig],+ should_use_incremental_field: bool = False,+ db_incremental_field_last_value: Any = None,) -> SourceResponse:config = FASTLY_ENDPOINTS[endpoint]+ incremental_start = _as_epoch_seconds(db_incremental_field_last_value) if should_use_incremental_field else Nonereturn SourceResponse(name=endpoint,@@ -465,6 +760,7 @@ def fastly_source(endpoint=endpoint,logger=logger,resumable_source_manager=resumable_source_manager,+ incremental_start=incremental_start,),primary_keys=config.primary_keys,partition_count=1,@@ -472,6 +768,9 @@ def fastly_source(partition_mode="datetime" if config.partition_key else None,partition_format="week" if config.partition_key else None,partition_keys=[config.partition_key] if config.partition_key else None,+ # The metrics endpoints report buckets ascending within a service but walk the services one+ # after another, so the table as a whole arrives unordered.+ sort_mode=None if config.incremental_fields else "asc",)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/fastly/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/fastly/settings.pyindex 4ba70f5d7451..4c952839a8e9 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/fastly/settings.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/fastly/settings.py@@ -3,6 +3,8 @@ from typing import Literalfrom posthog.dataclasses import frozen+from products.warehouse_sources.backend.types import IncrementalField, IncrementalFieldType+# How each Fastly endpoint is fetched:# - "object": GET returns a single object (e.g. /current_user).# - "service_list": GET /service returns a page-paginated array (Link header for next page).@@ -15,6 +17,11 @@ from posthog.dataclasses import frozen# opaque cursor rather than a Link header.# - "billing_usage_metrics": as "billing_list", but each page groups per-service rows under a usage# type, so the transport flattens them.+# - "plain_list": GET returns an unpaginated array (e.g. /datacenters).+# - "json_api_list": GET a JSON:API collection; rows sit under `data` with their fields split+# across `attributes` and `relationships`, and the next page is a body link.+# - "stats_list": GET /stats returns one array of time buckets per service, keyed by service id.+# - "origin_inspector": fan out over every service, reading its origin metrics timeseries.FastlyEndpointKind = Literal["object","service_list",@@ -23,8 +30,28 @@ FastlyEndpointKind = Literal["version_resource_child","billing_list","billing_usage_metrics",+ "plain_list",+ "json_api_list",+ "stats_list",+ "origin_inspector",+]++# Fastly reports both metrics families in whole time buckets keyed by their start. The cursor is the+# bucket start as a Unix timestamp, which is also what the `from` / `start` request params take, so a+# watermark feeds straight back into the next sync with no reformatting.+_BUCKET_START_INCREMENTAL_FIELDS: list[IncrementalField] = [+ {+ "label": "Bucket start",+ "type": IncrementalFieldType.DateTime,+ "field": "start_time",+ "field_type": IncrementalFieldType.Integer,+ },]+# Fastly revises recently reported metrics, so each incremental run re-reads a trailing window+# rather than freezing a bucket at the value it first had.+METRICS_LOOKBACK_SECONDS = 3 * 24 * 60 * 60+@frozenclass FastlyEndpointConfig:@@ -45,6 +72,9 @@ class FastlyEndpointConfig:# "version_resource_child" only: a truthy field on a parent row that means its members cannot be# listed, so the transport must not request them.skip_parent_flag: str | None = None+ # Empty means the endpoint has no server-side timestamp filter, so it is full refresh only.+ incremental_fields: list[IncrementalField] = field(default_factory=list)+ incremental_lookback_seconds: int | None = None# Version-scoped resource paths carry `{service_id}` and `{version}` placeholders that the@@ -122,6 +152,45 @@ FASTLY_ENDPOINTS: dict[str, FastlyEndpointConfig] = {primary_keys=["service_id", "dictionary_id", "item_key"],description="The key/value rows held in each service's edge dictionaries.",),+ "historical_stats": FastlyEndpointConfig(+ name="historical_stats",+ path="/stats",+ kind="stats_list",+ partition_key="start_time",+ primary_keys=["service_id", "start_time"],+ incremental_fields=_BUCKET_START_INCREMENTAL_FIELDS,+ incremental_lookback_seconds=METRICS_LOOKBACK_SECONDS,+ description="Daily traffic, cache hit ratio, bandwidth and error counts for every service.",+ ),+ "origin_inspector": FastlyEndpointConfig(+ name="origin_inspector",+ path="/metrics/origins/services/{service_id}",+ kind="origin_inspector",+ partition_key="start_time",+ primary_keys=["service_id", "host", "start_time"],+ incremental_fields=_BUCKET_START_INCREMENTAL_FIELDS,+ incremental_lookback_seconds=METRICS_LOOKBACK_SECONDS,+ # Origin Inspector is a paid upgrade enabled per service, so most accounts have it on no+ # service and would sync an empty table.+ should_sync_default=False,+ description="Daily origin latency, status code and byte counts per origin host, for services with Origin Inspector enabled.",+ ),+ "service_authorizations": FastlyEndpointConfig(+ name="service_authorizations",+ path="/service-authorizations",+ kind="json_api_list",+ primary_keys=["id"],+ description="Which users can reach which services, and the permission each one holds.",+ ),+ "pops": FastlyEndpointConfig(+ name="pops",+ path="/datacenters",+ kind="plain_list",+ # A POP carries no timestamp, and the list is small enough that one partition is right.+ partition_key=None,+ primary_keys=["code"],+ description="Every Fastly POP, with the datacenter codes used in stats and origin metrics.",+ ),"invoices": FastlyEndpointConfig(name="invoices",path="/billing/v3/invoices",diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/fastly/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/fastly/source.pyindex 5bccc5e5f0a7..b23515b01f5d 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/fastly/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/fastly/source.py@@ -88,17 +88,19 @@ A read-only token with **global** scope is sufficient to sync every table.""",force_refresh: bool = False,api_version: str | None = None,) -> list[SourceSchema]:- # Fastly's config endpoints expose no server-side timestamp filter, so every table is full- # refresh only. Each object carries a stable `created_at` used for partitioning.+ # Only the metrics endpoints take a server-side time filter. Every config endpoint is full+ # refresh only, partitioned on the stable `created_at` each object carries. Append is never+ # offered: Fastly revises a reported bucket after the fact, which append would duplicate.def _build_schema(endpoint: str) -> SourceSchema:endpoint_config = FASTLY_ENDPOINTS[endpoint]return SourceSchema(name=endpoint,- supports_incremental=False,+ supports_incremental=bool(endpoint_config.incremental_fields),supports_append=False,- incremental_fields=[],+ incremental_fields=endpoint_config.incremental_fields,should_sync_default=endpoint_config.should_sync_default,description=endpoint_config.description,+ default_incremental_lookback_seconds=endpoint_config.incremental_lookback_seconds,)schemas = [_build_schema(endpoint) for endpoint in ENDPOINTS]@@ -133,4 +135,6 @@ A read-only token with **global** scope is sufficient to sync every table.""",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,)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/fastly/tests/test_fastly.py b/products/warehouse_sources/backend/temporal/data_imports/sources/fastly/tests/test_fastly.pyindex 259bd628c55c..91c1f6ad3bbb 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/fastly/tests/test_fastly.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/fastly/tests/test_fastly.py@@ -1,5 +1,6 @@+from collections.abc import Iterablefrom datetime import UTC, datetime-from typing import Any+from typing import Any, castimport pytestfrom unittest.mock import MagicMock, patch@@ -10,12 +11,17 @@ from parameterized import parameterizedfrom products.warehouse_sources.backend.temporal.data_imports.sources.fastly import fastlyfrom products.warehouse_sources.backend.temporal.data_imports.sources.fastly.fastly import (FASTLY_BASE_URL,+ ORIGIN_INSPECTOR_PAGE_LIMIT,FastlyPaginationError,FastlyResumeConfig,FastlyRetryableError,_active_version_number,+ _as_epoch_seconds,+ _bucket_timeline,_build_url,_ensure_service_id,+ _flatten_json_api,+ _flatten_origin_inspector,_flatten_usage_metrics,_next_cursor,_next_page_url,@@ -186,9 +192,22 @@ class TestFetchRetries:assert session.get.call_count == 5-def _collect(endpoint: str, manager: _FakeResumableManager, pages: dict[str, Any]) -> list[dict]:+def _http_error(status_code: int) -> requests.HTTPError:+ response = MagicMock()+ response.status_code = status_code+ return requests.HTTPError(f"{status_code} Client Error", response=response)+++def _collect(+ endpoint: str,+ manager: _FakeResumableManager,+ pages: dict[str, Any],+ incremental_start: int | None = None,+) -> list[dict]:def fake_fetch(session: Any, url: str, headers: dict[str, str], logger: Any) -> Any:payload = pages[url]+ if isinstance(payload, Exception):+ raise payloadif isinstance(payload, tuple):body, next_url = payloadreturn _fake_response(body, next_url)@@ -204,6 +223,7 @@ def _collect(endpoint: str, manager: _FakeResumableManager, pages: dict[str, Anyendpoint=endpoint,logger=MagicMock(),resumable_source_manager=manager, # type: ignore[arg-type]+ incremental_start=incremental_start,):rows.extend(batch)return rows@@ -574,7 +594,305 @@ class TestFastlySourceResponse:logger=MagicMock(),resumable_source_manager=MagicMock(),)+ if FASTLY_ENDPOINTS[endpoint].partition_key is None:+ assert response.partition_mode is None+ assert response.partition_keys is None+ return+assert response.partition_mode == "datetime"assert response.partition_keys is not None# A partition key that moves rewrites every partition on each sync.assert not any(key.startswith(("updated", "last_", "deleted")) for key in response.partition_keys)++ @parameterized.expand(+ [+ ("epoch_int", 1_700_000_000, 1_700_000_000),+ ("epoch_float", 1_700_000_000.9, 1_700_000_000),+ ("datetime", datetime(2026, 9, 1, tzinfo=UTC), 1_788_220_800),+ ("unusable", "2026-09-01", None),+ ]+ )+ def test_watermark_is_normalised_to_unix_seconds(self, _name: str, value: Any, expected: int | None) -> None:+ assert _as_epoch_seconds(value) == expected++ def test_full_refresh_sends_no_watermark(self) -> None:+ # The watermark is only read when the run is actually incremental; a full refresh has to ask+ # for the API's own default window instead of resending the last cursor.+ seen: list[str] = []++ def fake_fetch(session: Any, url: str, headers: dict[str, str], logger: Any) -> Any:+ seen.append(url)+ return _fake_response({"data": {}})++ response = fastly_source(+ api_key="token",+ endpoint="historical_stats",+ logger=MagicMock(),+ resumable_source_manager=MagicMock(),+ should_use_incremental_field=False,+ db_incremental_field_last_value=1_700_000_000,+ )+ with (+ patch.object(fastly, "_fetch", side_effect=fake_fetch),+ patch.object(fastly, "make_tracked_session", return_value=MagicMock()),+ ):+ list(cast(Iterable[Any], response.items()))++ assert seen == [f"{FASTLY_BASE_URL}/stats?by=day"]+++class TestGetRowsPlainList:+ @parameterized.expand(+ [+ # /datacenters answers with a bare array rather than the usual `{"data": [...]}` wrapper.+ ("array", [{"code": "IAD"}, {"code": "SYD"}], [{"code": "IAD"}, {"code": "SYD"}]),+ ("error_object", {"msg": "nope"}, []),+ ]+ )+ def test_unpaginated_array_is_yielded_as_one_batch(self, _name: str, payload: Any, expected: list) -> None:+ pages = {f"{FASTLY_BASE_URL}/datacenters": payload}+ assert _collect("pops", _FakeResumableManager(), pages) == expected+++class TestFlattenJsonApi:+ @parameterized.expand(+ [+ (+ "full_resource",+ {+ "id": "SA1",+ "type": "service_authorization",+ "attributes": {"permission": "full", "created_at": "2026-09-01T00:00:00Z"},+ "relationships": {+ "service": {"data": {"id": "S1", "type": "service"}},+ "user": {"data": {"id": "U1", "type": "user"}},+ },+ },+ {+ "id": "SA1",+ "type": "service_authorization",+ "permission": "full",+ "created_at": "2026-09-01T00:00:00Z",+ "service_id": "S1",+ "user_id": "U1",+ },+ ),+ ("no_attributes_or_relationships", {"id": "SA1"}, {"id": "SA1"}),+ # A relationship can come back empty once the related object is deleted.+ ("empty_relationship", {"id": "SA1", "relationships": {"user": {"data": None}}}, {"id": "SA1"}),+ ]+ )+ def test_lifts_attributes_and_relationship_ids_into_the_row(self, _name: str, item: dict, expected: dict) -> None:+ assert _flatten_json_api(item) == expected+++class TestGetRowsJsonApiList:+ def test_flattens_rows_and_follows_the_body_link(self) -> None:+ first = f"{FASTLY_BASE_URL}/service-authorizations?page[size]=100"+ second = f"{FASTLY_BASE_URL}/service-authorizations?page[number]=2&page[size]=100"+ pages = {+ # Fastly returns the next page as a path, which has to resolve against the API host.+ first: {+ "data": [{"id": "SA1", "relationships": {"service": {"data": {"id": "S1"}}}}],+ "links": {"next": "/service-authorizations?page[number]=2&page[size]=100"},+ },+ second: {"data": [{"id": "SA2", "attributes": {"permission": "read_only"}}], "links": {}},+ }+ manager = _FakeResumableManager()+ rows = _collect("service_authorizations", manager, pages)++ assert rows == [{"id": "SA1", "service_id": "S1"}, {"id": "SA2", "permission": "read_only"}]+ assert [state.next_url for state in manager.saved] == [second]++ def test_resumes_from_the_saved_page_url(self) -> None:+ second = f"{FASTLY_BASE_URL}/service-authorizations?page[number]=2&page[size]=100"+ pages = {second: {"data": [{"id": "SA2"}], "links": {}}}+ manager = _FakeResumableManager(FastlyResumeConfig(next_url=second))+ assert _collect("service_authorizations", manager, pages) == [{"id": "SA2"}]++ def test_repeated_next_link_stops_instead_of_looping(self) -> None:+ first = f"{FASTLY_BASE_URL}/service-authorizations?page[size]=100"+ pages = {first: {"data": [{"id": "SA1"}], "links": {"next": "/service-authorizations?page[size]=100"}}}+ with pytest.raises(FastlyPaginationError):+ _collect("service_authorizations", _FakeResumableManager(), pages)++ @parameterized.expand([("absolute", "https://evil.example.com/x"), ("scheme_relative", "//evil.example.com/x")])+ def test_off_host_next_link_is_refused(self, _name: str, next_link: str) -> None:+ # Every request carries the token in `Fastly-Key`, so following a link to another host would+ # hand that host the customer's Fastly credential.+ first = f"{FASTLY_BASE_URL}/service-authorizations?page[size]=100"+ pages = {first: {"data": [{"id": "SA1"}], "links": {"next": next_link}}}+ with pytest.raises(FastlyPaginationError):+ _collect("service_authorizations", _FakeResumableManager(), pages)++ def test_off_host_resume_url_is_refused(self) -> None:+ manager = _FakeResumableManager(FastlyResumeConfig(next_url="https://evil.example.com/x"))+ with pytest.raises(FastlyPaginationError):+ _collect("service_authorizations", manager, {})+++class TestGetRowsStatsList:+ def test_unpacks_the_per_service_map_into_rows(self) -> None:+ pages = {+ f"{FASTLY_BASE_URL}/stats?by=day": {+ "data": {+ "S1": [{"start_time": 100, "requests": 5}],+ # Fastly already stamps `service_id` on most rows; both shapes have to key.+ "S2": [{"service_id": "S2", "start_time": 100, "requests": 7}],+ }+ }+ }+ rows = _collect("historical_stats", _FakeResumableManager(), pages)++ assert rows == [+ {"service_id": "S1", "start_time": 100, "requests": 5},+ {"service_id": "S2", "start_time": 100, "requests": 7},+ ]++ def test_incremental_run_sends_the_watermark_as_from(self) -> None:+ pages = {+ f"{FASTLY_BASE_URL}/stats?by=day&from=1700000000": {"data": {"S1": [{"start_time": 1700086400}]}},+ }+ rows = _collect("historical_stats", _FakeResumableManager(), pages, incremental_start=1_700_000_000)+ assert rows == [{"start_time": 1700086400, "service_id": "S1"}]++ @parameterized.expand([("not_a_dict", {"data": []}), ("no_data", {"status": "error"})])+ def test_unusable_payloads_yield_nothing(self, _name: str, payload: dict) -> None:+ assert _collect("historical_stats", _FakeResumableManager(), {f"{FASTLY_BASE_URL}/stats?by=day": payload}) == []+++class TestBucketTimeline:+ @parameterized.expand(+ [+ ("day", {"start": "2026-09-01T00:00:00Z", "downsample": "day"}, (1_788_220_800, 86400)),+ ("hour", {"start": "2026-09-01T00:00:00Z", "downsample": "hour"}, (1_788_220_800, 3600)),+ # A start without a zone is UTC, as every absolute time in the Fastly metrics APIs is.+ ("naive_start_is_utc", {"start": "2026-09-01T00:00:00", "downsample": "day"}, (1_788_220_800, 86400)),+ ("unknown_downsample", {"start": "2026-09-01T00:00:00Z", "downsample": "fortnight"}, None),+ ("missing_start", {"downsample": "day"}, None),+ ("unparseable_start", {"start": "whenever", "downsample": "day"}, None),+ ]+ )+ def test_bucket_timeline(self, _name: str, meta: dict, expected: tuple[int, int] | None) -> None:+ timeline = _bucket_timeline(meta)+ if expected is None:+ assert timeline is None+ return+ assert timeline is not None+ assert (timeline.first_start_time, timeline.bucket_seconds) == expected+++class TestFlattenOriginInspector:+ def test_derives_each_bucket_timestamp_from_its_index(self) -> None:+ # Origin Inspector puts no timestamp on a value, so the bucket is the value's position+ # counted forward from `meta.start`.+ payload = {+ "meta": {"start": "2026-09-01T00:00:00Z", "downsample": "day"},+ "data": [+ {+ "dimensions": {"host": "origin.example.com"},+ "values": [{"responses": 1}, {"responses": 2}, {"responses": 3}],+ }+ ],+ }+ rows = _flatten_origin_inspector(payload, "S1")++ assert [row["start_time"] for row in rows] == [1_788_220_800, 1_788_307_200, 1_788_393_600]+ assert all(row["service_id"] == "S1" and row["host"] == "origin.example.com" for row in rows)+ assert [row["responses"] for row in rows] == [1, 2, 3]++ @parameterized.expand(+ [+ ("no_meta", {"data": [{"dimensions": {}, "values": [{"responses": 1}]}]}),+ ("no_data", {"meta": {"start": "2026-09-01T00:00:00Z", "downsample": "day"}}),+ (+ "values_not_a_list",+ {+ "meta": {"start": "2026-09-01T00:00:00Z", "downsample": "day"},+ "data": [{"dimensions": {}, "values": None}],+ },+ ),+ ]+ )+ def test_unusable_payloads_yield_no_rows(self, _name: str, payload: dict) -> None:+ assert _flatten_origin_inspector(payload, "S1") == []+++class TestGetRowsOriginInspector:+ def _url(self, service_id: str, cursor: str | None = None, start: int | None = None) -> str:+ params: dict[str, Any] = {+ "downsample": "day",+ "group_by": "host",+ "limit": ORIGIN_INSPECTOR_PAGE_LIMIT,+ }+ if start is not None:+ params["start"] = start+ if cursor is not None:+ params["cursor"] = cursor+ return _build_url(f"{FASTLY_BASE_URL}/metrics/origins/services/{service_id}", params)++ def test_fans_out_over_services_and_follows_the_cursor(self) -> None:+ meta = {"start": "2026-09-01T00:00:00Z", "downsample": "day"}+ pages = {+ f"{FASTLY_BASE_URL}/service?per_page=100": ([{"id": "S1"}, {"id": "S2"}], None),+ self._url("S1"): {+ "meta": {**meta, "next_cursor": "CUR2"},+ "data": [{"dimensions": {"host": "a"}, "values": [{"responses": 1}]}],+ },+ self._url("S1", cursor="CUR2"): {+ "meta": meta,+ "data": [{"dimensions": {"host": "b"}, "values": [{"responses": 2}]}],+ },+ self._url("S2"): {+ "meta": meta,+ "data": [{"dimensions": {"host": "c"}, "values": [{"responses": 3}]}],+ },+ }+ manager = _FakeResumableManager()+ rows = _collect("origin_inspector", manager, pages)++ assert [(row["service_id"], row["host"]) for row in rows] == [("S1", "a"), ("S1", "b"), ("S2", "c")]+ assert [state.service_id for state in manager.saved] == ["S1", "S2"]++ @parameterized.expand([("forbidden", 403), ("not_found", 404)])+ def test_service_without_the_origin_inspector_upgrade_is_skipped(self, _name: str, status_code: int) -> None:+ # Only some services carry the paid upgrade; the rest must not fail the whole table.+ pages = {+ f"{FASTLY_BASE_URL}/service?per_page=100": ([{"id": "S1"}, {"id": "S2"}], None),+ self._url("S1"): _http_error(status_code),+ self._url("S2"): {+ "meta": {"start": "2026-09-01T00:00:00Z", "downsample": "day"},+ "data": [{"dimensions": {"host": "c"}, "values": [{"responses": 3}]}],+ },+ }+ rows = _collect("origin_inspector", _FakeResumableManager(), pages)+ assert [row["service_id"] for row in rows] == ["S2"]++ def test_other_errors_still_fail_the_sync(self) -> None:+ pages = {+ f"{FASTLY_BASE_URL}/service?per_page=100": ([{"id": "S1"}], None),+ self._url("S1"): _http_error(401),+ }+ with pytest.raises(requests.HTTPError):+ _collect("origin_inspector", _FakeResumableManager(), pages)++ def test_incremental_run_sends_the_watermark_as_start(self) -> None:+ pages = {+ f"{FASTLY_BASE_URL}/service?per_page=100": ([{"id": "S1"}], None),+ self._url("S1", start=1_700_000_000): {+ "meta": {"start": "2026-09-01T00:00:00Z", "downsample": "day"},+ "data": [{"dimensions": {"host": "a"}, "values": [{"responses": 1}]}],+ },+ }+ rows = _collect("origin_inspector", _FakeResumableManager(), pages, incremental_start=1_700_000_000)+ assert [row["host"] for row in rows] == ["a"]++ def test_repeated_cursor_stops_instead_of_looping(self) -> None:+ meta = {"start": "2026-09-01T00:00:00Z", "downsample": "day", "next_cursor": "CUR2"}+ pages = {+ f"{FASTLY_BASE_URL}/service?per_page=100": ([{"id": "S1"}], None),+ self._url("S1"): {"meta": meta, "data": []},+ self._url("S1", cursor="CUR2"): {"meta": meta, "data": []},+ }+ with pytest.raises(FastlyPaginationError):+ _collect("origin_inspector", _FakeResumableManager(), pages)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/fastly/tests/test_fastly_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/fastly/tests/test_fastly_source.pyindex 8e96fc412ad0..0a8da96b7ef6 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/fastly/tests/test_fastly_source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/fastly/tests/test_fastly_source.py@@ -39,13 +39,13 @@ class TestFastlySource:non_retryable_errors = self.source.get_non_retryable_errors()assert not any(key in other_error for key in non_retryable_errors)- def test_get_schemas_are_full_refresh_only(self):- schemas = self.source.get_schemas(self.config, self.team_id)+ def test_get_schemas_offer_incremental_only_where_the_api_filters_by_time(self):+ schemas = {schema.name: schema for schema in self.source.get_schemas(self.config, self.team_id)}- assert {schema.name for schema in schemas} == set(ENDPOINTS)- assert all(not schema.supports_incremental for schema in schemas)- assert all(not schema.supports_append for schema in schemas)- assert all(schema.incremental_fields == [] for schema in schemas)+ assert set(schemas) == set(ENDPOINTS)+ incremental = {name for name, schema in schemas.items() if schema.supports_incremental}+ assert incremental == {"historical_stats", "origin_inspector"}+ assert all(bool(schema.incremental_fields) == schema.supports_incremental for schema in schemas.values())def test_get_schemas_have_descriptions(self):schemas = self.source.get_schemas(self.config, self.team_id)