Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

feat(fastly): sync ACL entries, dictionary items and billing tables (#107282)

Tom Owersaab6d7fcdcae
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.md b/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.md
index 9201c9a8907c..900f78046488 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
@@ -3013,15 +3013,15 @@ Note: The reference exposes roughly 140 list endpoints across ATS, attendance, c
## Fastly — **thin**
-Today (7): `current_user`, `service_acls`, `service_backends`, `service_dictionaries`, `service_domains`, `service_versions`, `services`
+Today (11): `acl_entries`, `billing_usage_metrics`, `current_user`, `dictionary_items`, `invoices`, `service_acls`, `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)
-- [ ] `account/billing-usage-metrics` — usage and spend per product and service over time (high)
-- [ ] `dictionaries/dictionary-item` — lookup table - the actual key/value rows inside the service_dictionaries we already sync (high)
-- [ ] `acls/acl-entry` — lookup table - the IP entries inside the service_acls we already sync (high)
-- [ ] `account/invoices` — billed amounts per period for cost reporting (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)
- [ ] `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)
@@ -3029,7 +3029,7 @@ Diffed against: <https://www.fastly.com/documentation/reference/api/>
- [ ] `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)
-Note: Current coverage is almost entirely service configuration objects; none of the metrics-stats or account/billing families are 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 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.
## 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.py
index 99ba143036d1..805b45c01e65 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
@@ -108,4 +108,62 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
"deleted_at": "Timestamp (UTC) of when the dictionary was deleted, if applicable.",
},
},
+ "acl_entries": {
+ "description": "The IP addresses and subnet ranges held in each service's ACLs.",
+ "docs_url": "https://www.fastly.com/documentation/reference/api/acls/acl-entry/",
+ "columns": {
+ "id": "Alphanumeric string identifying an ACL entry.",
+ "acl_id": "Alphanumeric string identifying the ACL the entry belongs to.",
+ "service_id": "Alphanumeric string identifying the service.",
+ "ip": "An IP address.",
+ "subnet": "Number of bits for the subnet mask applied to the IP address. If not provided, no mask is applied.",
+ "negated": "Whether to negate the match, used to make exceptions to larger subnets.",
+ "comment": "A freeform descriptive note.",
+ "created_at": "Timestamp (UTC) of when the entry was created.",
+ "updated_at": "Timestamp (UTC) of when the entry was last updated.",
+ "deleted_at": "Timestamp (UTC) of when the entry was deleted, if applicable.",
+ },
+ },
+ "dictionary_items": {
+ "description": "The key/value rows held in each service's edge dictionaries.",
+ "docs_url": "https://www.fastly.com/documentation/reference/api/dictionaries/dictionary-item/",
+ "columns": {
+ "item_key": "Item key, unique within its dictionary.",
+ "item_value": "Item value.",
+ "dictionary_id": "Alphanumeric string identifying the dictionary the item belongs to.",
+ "service_id": "Alphanumeric string identifying the service.",
+ "created_at": "Timestamp (UTC) of when the item was created.",
+ "updated_at": "Timestamp (UTC) of when the item was last updated.",
+ "deleted_at": "Timestamp (UTC) of when the item was deleted, if applicable.",
+ },
+ },
+ "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/",
+ "columns": {
+ "invoice_id": "Numeric string identifying the invoice.",
+ "customer_id": "Customer ID associated with the invoice.",
+ "invoice_posted_on": "Timestamp (UTC) of when the invoice was posted.",
+ "billing_start_date": "Start of the billing cycle the invoice covers.",
+ "billing_end_date": "End of the billing cycle the invoice covers.",
+ "statement_number": "Alphanumeric string identifying the statement number.",
+ "currency_code": "Three-letter code for the currency the invoice is billed in.",
+ "monthly_transaction_amount": "Total billable amount for services charged within the month.",
+ "transaction_line_items": "The individual charges making up the invoice, each with a product, rate, units and amount.",
+ },
+ },
+ "billing_usage_metrics": {
+ "description": "Usage per product and service over the most recent billing months.",
+ "docs_url": "https://www.fastly.com/documentation/reference/api/account/billing-usage-metrics/",
+ "columns": {
+ "customer_id": "Alphanumeric string identifying the customer.",
+ "service_id": "Alphanumeric string identifying the service the usage belongs to.",
+ "service_name": "Name of the service the usage belongs to.",
+ "usage_type": "The billable metric the usage is measured against.",
+ "unit": "The unit the usage is measured in, as it appears on an invoice.",
+ "usage_units": "The quantity of usage for the billing period, in the given unit.",
+ "start_time": "Start of the billing cycle the usage covers.",
+ "end_time": "End of the billing cycle the usage covers.",
+ },
+ },
}
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.py
index 36fe9aaba435..c88e1cc16294 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,5 +1,5 @@
-import dataclasses
from collections.abc import Iterator
+from datetime import UTC, datetime
from typing import Any
from urllib.parse import urlencode
@@ -7,6 +7,8 @@ import requests
from structlog.types import FilteringBoundLogger
from tenacity import retry, retry_if_exception_type, stop_after_attempt, wait_exponential_jitter
+from posthog.dataclasses import frozen
+
from products.warehouse_sources.backend.temporal.data_imports.sources.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
@@ -21,18 +23,35 @@ FASTLY_BASE_URL = "https://api.fastly.com"
# the account's service count is small in practice, so a large page keeps the round-trip count down.
SERVICE_PAGE_SIZE = 100
+# ACL entries and dictionary items page the same way, and both accept up to 100 records per page.
+CHILD_PAGE_SIZE = 100
+
+# `/billing/v3/invoices` caps `limit` at 200.
+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
+
class FastlyRetryableError(Exception):
pass
+class FastlyPaginationError(Exception):
+ pass
+
+
+@frozen
class FastlyResumeConfig:
# Next page URL for the paginated top-level `services` list.
next_url: str | None = None
# Bookmark for fan-out endpoints: the service we were processing when state was saved. On resume
# we restart at this service and re-yield its rows (merge dedupes on the primary key).
service_id: str | None = None
+ # Opaque next-page cursor for the /billing/v3 endpoints, with the request it continues. A cursor
+ # only continues the request that produced it, and the usage metrics window moves with the month.
+ cursor: str | None = None
+ cursor_request: str | None = None
def _get_headers(api_key: str) -> dict[str, str]:
@@ -91,14 +110,79 @@ def validate_credentials(api_key: str) -> bool:
return False
-def _ensure_service_id(row: dict[str, Any], service_id: str) -> dict[str, Any]:
- """Fastly's version-scoped objects already carry `service_id`, but inject it defensively so the
- composite primary key is never missing its parent identifier."""
- if not row.get("service_id"):
- row = {**row, "service_id": service_id}
+def _ensure_id(row: dict[str, Any], field: str, value: str) -> dict[str, Any]:
+ """Fastly's nested objects already carry their parent identifiers, but inject them defensively so
+ a composite primary key is never missing a parent."""
+ if not row.get(field):
+ row = {**row, field: value}
return row
+def _ensure_service_id(row: dict[str, Any], service_id: str) -> dict[str, Any]:
+ return _ensure_id(row, "service_id", service_id)
+
+
+def _iter_linked_pages(
+ session: requests.Session, url: str, headers: dict[str, str], logger: FilteringBoundLogger
+) -> Iterator[requests.Response]:
+ """Walk a Link-header paginated Fastly endpoint, yielding each page's response."""
+ while True:
+ response = _fetch(session, url, headers, logger)
+ yield response
+ next_url = _next_page_url(response)
+ if not next_url:
+ return
+ # A next link that points at the page just read would loop forever and re-yield its rows.
+ if next_url == url:
+ raise FastlyPaginationError(f"Fastly returned an unchanged next page link for {url}")
+ url = next_url
+
+
+def _next_cursor(payload: dict[str, Any]) -> str | None:
+ """Read the next-page cursor from a /billing/v3 response. Invoices carry `meta` at the top level
+ while the usage metrics response nests it under `data`, so check both rather than assume one."""
+ meta = payload.get("meta")
+ if not isinstance(meta, dict):
+ data = payload.get("data")
+ meta = data.get("meta") if isinstance(data, dict) else None
+ if not isinstance(meta, dict):
+ return None
+ cursor = meta.get("next_cursor")
+ return cursor if isinstance(cursor, str) and cursor else None
+
+
+def _request_fingerprint(path: str, params: dict[str, Any]) -> str:
+ return _build_url(path, dict(sorted(params.items())))
+
+
+def _usage_metrics_window(today: datetime | None = None) -> dict[str, str]:
+ """The `YYYY-MM` window covering the current month and the two before it."""
+ now = today or datetime.now(tz=UTC)
+ end_index = now.year * 12 + now.month - 1
+ start_index = end_index - (USAGE_METRICS_MONTHS - 1)
+ return {
+ "start_month": f"{start_index // 12:04d}-{start_index % 12 + 1:02d}",
+ "end_month": f"{end_index // 12:04d}-{end_index % 12 + 1:02d}",
+ }
+
+
+def _flatten_usage_metrics(payload: dict[str, Any]) -> list[dict[str, Any]]:
+ """Turn a usage metrics page into one row per (usage type, service). Fastly's own spec models
+ `data` as a single usage-type block; live responses may return a list of them, so accept both."""
+ data = payload.get("data")
+ blocks = data if isinstance(data, list) else [data] if isinstance(data, dict) else []
+
+ rows: list[dict[str, Any]] = []
+ for block in blocks:
+ if not isinstance(block, dict):
+ continue
+ usage_type = {key: value for key, value in block.items() if key not in ("details", "meta")}
+ for detail in block.get("details") or []:
+ if isinstance(detail, dict):
+ rows.append({**usage_type, **detail})
+ return rows
+
+
def _iter_services(
session: requests.Session, headers: dict[str, str], logger: FilteringBoundLogger
) -> Iterator[dict[str, Any]]:
@@ -172,18 +256,19 @@ def _get_service_list_rows(
url = next_url
-def _get_fanout_rows(
+def _iter_services_from_bookmark(
session: requests.Session,
config: FastlyEndpointConfig,
headers: dict[str, str],
logger: FilteringBoundLogger,
resumable_source_manager: ResumableSourceManager[FastlyResumeConfig],
-) -> Iterator[list[dict[str, Any]]]:
+) -> Iterator[str]:
+ """Yield the service ids a fan-out endpoint still has to process, bookmarking each one once the
+ caller has yielded its rows. If the bookmarked service no longer exists (deleted between runs),
+ start over — merge dedupes the re-pulled rows."""
services = list(_iter_services(session, headers, logger))
service_ids = [s["id"] for s in services if isinstance(s, dict) and s.get("id")]
- # Resolve the saved service bookmark to the slice still to process. If the bookmarked service no
- # longer exists (deleted between runs), start over — merge dedupes the re-pulled rows.
resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None
start = 0
if resume is not None and resume.service_id and resume.service_id in service_ids:
@@ -191,27 +276,152 @@ def _get_fanout_rows(
logger.debug(f"Fastly: resuming {config.name} from service_id={resume.service_id}")
for service_id in service_ids[start:]:
- rows: list[dict[str, Any]] = []
+ yield service_id
+ # Bookmark the service AFTER yielding so a crash resumes here and re-yields. Advanced even for
+ # a versionless (skipped) service so resume doesn't re-evaluate it every time.
+ resumable_source_manager.save_state(FastlyResumeConfig(service_id=service_id))
+
+
+def _get_version_scoped_rows(
+ session: requests.Session,
+ config: FastlyEndpointConfig,
+ service_id: str,
+ path: str,
+ headers: dict[str, str],
+ logger: FilteringBoundLogger,
+) -> list[dict[str, Any]]:
+ version = _active_version_number(session, service_id, headers, logger)
+ if version is None:
+ logger.debug(f"Fastly: service {service_id} has no versions, skipping {config.name}")
+ return []
+
+ response = _fetch(
+ session, f"{FASTLY_BASE_URL}{path.format(service_id=service_id, version=version)}", headers, logger
+ )
+ data = response.json()
+ return [row for row in data if isinstance(row, dict)] if isinstance(data, list) else []
+
+
+def _get_fanout_rows(
+ session: requests.Session,
+ config: FastlyEndpointConfig,
+ headers: dict[str, str],
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[FastlyResumeConfig],
+) -> Iterator[list[dict[str, Any]]]:
+ for service_id in _iter_services_from_bookmark(session, config, headers, logger, resumable_source_manager):
if config.kind == "version_list":
response = _fetch(session, f"{FASTLY_BASE_URL}/service/{service_id}/version", headers, logger)
data = response.json()
- rows = data if isinstance(data, list) else []
+ rows = [row for row in data if isinstance(row, dict)] if isinstance(data, list) else []
else:
- version = _active_version_number(session, service_id, headers, logger)
- if version is None:
- logger.debug(f"Fastly: service {service_id} has no versions, skipping {config.name}")
- else:
- path = config.path.format(service_id=service_id, version=version)
- response = _fetch(session, f"{FASTLY_BASE_URL}{path}", headers, logger)
- data = response.json()
- rows = data if isinstance(data, list) else []
-
- rows = [_ensure_service_id(row, service_id) for row in rows if isinstance(row, dict)]
+ rows = _get_version_scoped_rows(session, config, service_id, config.path, headers, logger)
+
+ rows = [_ensure_service_id(row, service_id) for row in rows]
+ if rows:
+ yield rows
+
+
+def _get_version_resource_child_rows(
+ session: requests.Session,
+ config: FastlyEndpointConfig,
+ headers: dict[str, str],
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[FastlyResumeConfig],
+) -> Iterator[list[dict[str, Any]]]:
+ parent_path = config.parent_path
+ parent_key = config.parent_key
+ assert parent_path is not None and parent_key is not None
+
+ for service_id in _iter_services_from_bookmark(session, config, headers, logger, resumable_source_manager):
+ parents = _get_version_scoped_rows(session, config, service_id, parent_path, headers, logger)
+
+ for parent in parents:
+ if config.skip_parent_flag and parent.get(config.skip_parent_flag):
+ continue
+
+ parent_id = parent.get("id")
+ if not parent_id:
+ continue
+
+ path = config.path.format(service_id=service_id, parent_id=parent_id)
+ url = _build_url(f"{FASTLY_BASE_URL}{path}", {"per_page": CHILD_PAGE_SIZE})
+ for response in _iter_linked_pages(session, url, headers, logger):
+ items = response.json()
+ if not isinstance(items, list):
+ continue
+ rows = [
+ _ensure_id(_ensure_service_id(row, service_id), parent_key, parent_id)
+ for row in items
+ if isinstance(row, dict)
+ ]
+ if rows:
+ yield rows
+
+
+def _iter_billing_pages(
+ session: requests.Session,
+ path: str,
+ params: dict[str, Any],
+ headers: dict[str, str],
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[FastlyResumeConfig],
+) -> Iterator[dict[str, Any]]:
+ request = _request_fingerprint(path, params)
+ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None
+
+ cursor = None
+ if resume is not None and resume.cursor and resume.cursor_request == request:
+ cursor = resume.cursor
+ logger.debug(f"Fastly: resuming {path} from cursor")
+
+ while True:
+ page_params = {**params, "cursor": cursor} if cursor else params
+ response = _fetch(session, _build_url(f"{FASTLY_BASE_URL}{path}", page_params), headers, logger)
+ payload = response.json()
+ if not isinstance(payload, dict):
+ return
+
+ yield payload
+
+ next_cursor = _next_cursor(payload)
+ if not next_cursor:
+ return
+ # A cursor that repeats the one just sent would loop forever and re-yield the same page.
+ if next_cursor == cursor:
+ raise FastlyPaginationError(f"Fastly returned an unchanged cursor for {path}")
+ cursor = next_cursor
+ # Saved AFTER yielding so a crash re-yields the last page rather than skipping it.
+ resumable_source_manager.save_state(FastlyResumeConfig(cursor=cursor, cursor_request=request))
+
+
+def _get_billing_list_rows(
+ session: requests.Session,
+ config: FastlyEndpointConfig,
+ headers: dict[str, str],
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[FastlyResumeConfig],
+) -> Iterator[list[dict[str, Any]]]:
+ params = {"limit": INVOICE_PAGE_LIMIT}
+ for payload in _iter_billing_pages(session, config.path, params, headers, logger, resumable_source_manager):
+ data = payload.get("data")
+ rows = [row for row in data if isinstance(row, dict)] if isinstance(data, list) else []
+ if rows:
+ yield rows
+
+
+def _get_billing_usage_metrics_rows(
+ session: requests.Session,
+ config: FastlyEndpointConfig,
+ headers: dict[str, str],
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[FastlyResumeConfig],
+) -> Iterator[list[dict[str, Any]]]:
+ params = _usage_metrics_window()
+ for payload in _iter_billing_pages(session, config.path, params, headers, logger, resumable_source_manager):
+ rows = _flatten_usage_metrics(payload)
if rows:
yield rows
- # Bookmark the service AFTER yielding so a crash resumes here and re-yields. Advanced even for
- # a versionless (skipped) service so resume doesn't re-evaluate it every time.
- resumable_source_manager.save_state(FastlyResumeConfig(service_id=service_id))
def get_rows(
@@ -230,6 +440,12 @@ def get_rows(
yield from _get_object_rows(session, config, headers, logger)
elif config.kind == "service_list":
yield from _get_service_list_rows(session, headers, logger, resumable_source_manager)
+ elif config.kind == "version_resource_child":
+ yield from _get_version_resource_child_rows(session, config, headers, logger, resumable_source_manager)
+ elif config.kind == "billing_list":
+ yield from _get_billing_list_rows(session, config, headers, logger, resumable_source_manager)
+ elif config.kind == "billing_usage_metrics":
+ yield from _get_billing_usage_metrics_rows(session, config, headers, logger, resumable_source_manager)
else:
yield from _get_fanout_rows(session, config, headers, logger, resumable_source_manager)
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.py
index 8f64fb76af7f..4ba70f5d7451 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
@@ -1,16 +1,32 @@
-from dataclasses import dataclass, field
+from dataclasses import field
from typing import Literal
+from posthog.dataclasses import frozen
+
# 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).
# - "version_list": fan out over every service, list that service's versions.
# - "version_resource": fan out over every service, fetch a resource scoped to the service's
# currently-active version (domains, backends, ACLs, dictionaries).
-FastlyEndpointKind = Literal["object", "service_list", "version_list", "version_resource"]
+# - "version_resource_child": as above, then fan out again over each returned resource to list its
+# versionless members (ACL entries, dictionary items).
+# - "billing_list": GET a /billing/v3 collection; rows sit under `data` and the next page is an
+# 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.
+FastlyEndpointKind = Literal[
+ "object",
+ "service_list",
+ "version_list",
+ "version_resource",
+ "version_resource_child",
+ "billing_list",
+ "billing_usage_metrics",
+]
-@dataclass
+@frozen
class FastlyEndpointConfig:
name: str
path: str
@@ -22,6 +38,13 @@ class FastlyEndpointConfig:
# Unique across the whole table. Fan-out children aggregate rows from every parent, so the
# key includes the parent (service) identifier unless the resource id is globally unique.
primary_keys: list[str] = field(default_factory=lambda: ["id"])
+ # "version_resource_child" only: the version-scoped endpoint listing the parents of `path`, and
+ # the column on a child row that holds its parent's id.
+ parent_path: str | None = None
+ parent_key: str | None = None
+ # "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
# Version-scoped resource paths carry `{service_id}` and `{version}` placeholders that the
@@ -78,6 +101,43 @@ FASTLY_ENDPOINTS: dict[str, FastlyEndpointConfig] = {
primary_keys=["service_id", "id"],
description="Edge dictionaries on each service's active version.",
),
+ "acl_entries": FastlyEndpointConfig(
+ name="acl_entries",
+ path="/service/{service_id}/acl/{parent_id}/entries",
+ kind="version_resource_child",
+ parent_path="/service/{service_id}/version/{version}/acl",
+ parent_key="acl_id",
+ primary_keys=["service_id", "acl_id", "id"],
+ description="The IP addresses and subnet ranges held in each service's ACLs.",
+ ),
+ "dictionary_items": FastlyEndpointConfig(
+ name="dictionary_items",
+ path="/service/{service_id}/dictionary/{parent_id}/items",
+ kind="version_resource_child",
+ parent_path="/service/{service_id}/version/{version}/dictionary",
+ parent_key="dictionary_id",
+ # Fastly refuses to list the items of a write-only dictionary.
+ skip_parent_flag="write_only",
+ # A dictionary item has no id of its own; its key is unique within its dictionary.
+ primary_keys=["service_id", "dictionary_id", "item_key"],
+ description="The key/value rows held in each service's edge dictionaries.",
+ ),
+ "invoices": FastlyEndpointConfig(
+ name="invoices",
+ path="/billing/v3/invoices",
+ kind="billing_list",
+ partition_key="billing_start_date",
+ primary_keys=["invoice_id"],
+ description="Posted invoices for the account, with the line items billed on each.",
+ ),
+ "billing_usage_metrics": FastlyEndpointConfig(
+ name="billing_usage_metrics",
+ path="/billing/v3/service-usage-metrics",
+ kind="billing_usage_metrics",
+ partition_key="start_time",
+ primary_keys=["customer_id", "start_time", "usage_type", "service_id"],
+ description="Usage per product and service over the most recent billing months.",
+ ),
}
ENDPOINTS = tuple(FASTLY_ENDPOINTS.keys())
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.py
index f5c01a47c037..259bd628c55c 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,3 +1,4 @@
+from datetime import UTC, datetime
from typing import Any
import pytest
@@ -9,12 +10,16 @@ from parameterized import parameterized
from products.warehouse_sources.backend.temporal.data_imports.sources.fastly import fastly
from products.warehouse_sources.backend.temporal.data_imports.sources.fastly.fastly import (
FASTLY_BASE_URL,
+ FastlyPaginationError,
FastlyResumeConfig,
FastlyRetryableError,
_active_version_number,
_build_url,
_ensure_service_id,
+ _flatten_usage_metrics,
+ _next_cursor,
_next_page_url,
+ _usage_metrics_window,
fastly_source,
get_rows,
validate_credentials,
@@ -285,6 +290,270 @@ class TestGetRowsVersionResourceFanOut:
assert [s.service_id for s in manager.saved] == ["S1", "S2"]
+class TestNextCursor:
+ @parameterized.expand(
+ [
+ # Invoices carry `meta` at the top level.
+ ("top_level", {"data": [], "meta": {"next_cursor": "abc"}}, "abc"),
+ # The usage metrics response nests `meta` inside `data`.
+ ("nested_in_data", {"data": {"meta": {"next_cursor": "def"}}}, "def"),
+ ("last_page_empty_cursor", {"data": [], "meta": {"next_cursor": ""}}, None),
+ ("last_page_no_cursor", {"data": [], "meta": {"total": 3}}, None),
+ ("no_meta", {"data": []}, None),
+ ]
+ )
+ def test_next_cursor(self, _name: str, payload: dict, expected: str | None) -> None:
+ assert _next_cursor(payload) == expected
+
+
+class TestUsageMetricsWindow:
+ @parameterized.expand(
+ [
+ ("mid_year", datetime(2026, 9, 15, tzinfo=UTC), "2026-07", "2026-09"),
+ # The three-month window has to roll back over a year boundary, not clamp to January.
+ ("crosses_year", datetime(2026, 1, 3, tzinfo=UTC), "2025-11", "2026-01"),
+ ("december", datetime(2026, 12, 31, tzinfo=UTC), "2026-10", "2026-12"),
+ ]
+ )
+ def test_window_spans_three_months(self, _name: str, today: datetime, start: str, end: str) -> None:
+ assert _usage_metrics_window(today) == {"start_month": start, "end_month": end}
+
+
+class TestFlattenUsageMetrics:
+ def test_flattens_one_row_per_usage_type_and_service(self) -> None:
+ payload = {
+ "data": [
+ {
+ "customer_id": "C1",
+ "start_time": "2026-09-01T00:00:00Z",
+ "usage_type": "North America Requests",
+ "unit": "unit",
+ "meta": {"next_cursor": "x"},
+ "details": [
+ {"service_id": "S1", "service_name": "www", "usage_units": 10.5},
+ {"service_id": "S2", "service_name": "api", "usage_units": 2.0},
+ ],
+ }
+ ]
+ }
+ rows = _flatten_usage_metrics(payload)
+
+ # `meta` is pagination state, not a column on the row.
+ assert rows == [
+ {
+ "customer_id": "C1",
+ "start_time": "2026-09-01T00:00:00Z",
+ "usage_type": "North America Requests",
+ "unit": "unit",
+ "service_id": "S1",
+ "service_name": "www",
+ "usage_units": 10.5,
+ },
+ {
+ "customer_id": "C1",
+ "start_time": "2026-09-01T00:00:00Z",
+ "usage_type": "North America Requests",
+ "unit": "unit",
+ "service_id": "S2",
+ "service_name": "api",
+ "usage_units": 2.0,
+ },
+ ]
+
+ def test_accepts_a_single_data_object(self) -> None:
+ # Fastly's own spec models `data` as one usage-type block rather than a list.
+ payload = {"data": {"usage_type": "Bandwidth", "details": [{"service_id": "S1", "usage_units": 1.0}]}}
+ assert _flatten_usage_metrics(payload) == [{"usage_type": "Bandwidth", "service_id": "S1", "usage_units": 1.0}]
+
+ @parameterized.expand(
+ [
+ ("no_data", {}),
+ ("null_details", {"data": {"usage_type": "Bandwidth", "details": None}}),
+ ("empty_details", {"data": {"usage_type": "Bandwidth", "details": []}}),
+ ]
+ )
+ def test_pages_without_details_yield_no_rows(self, _name: str, payload: dict) -> None:
+ assert _flatten_usage_metrics(payload) == []
+
+
+class TestGetRowsVersionResourceChildFanOut:
+ def test_fans_out_through_the_parent_resource_and_injects_both_ids(self) -> None:
+ pages = {
+ f"{FASTLY_BASE_URL}/service?per_page=100": ([{"id": "S1"}], None),
+ f"{FASTLY_BASE_URL}/service/S1/version": [{"number": 2, "active": True}],
+ f"{FASTLY_BASE_URL}/service/S1/version/2/acl": [{"id": "A1"}, {"id": "A2"}],
+ f"{FASTLY_BASE_URL}/service/S1/acl/A1/entries?per_page=100": [{"id": "E1", "ip": "1.2.3.4"}],
+ f"{FASTLY_BASE_URL}/service/S1/acl/A2/entries?per_page=100": [{"id": "E2", "ip": "5.6.7.8"}],
+ }
+ rows = _collect("acl_entries", _FakeResumableManager(), pages)
+
+ assert rows == [
+ {"id": "E1", "ip": "1.2.3.4", "service_id": "S1", "acl_id": "A1"},
+ {"id": "E2", "ip": "5.6.7.8", "service_id": "S1", "acl_id": "A2"},
+ ]
+
+ def test_paginates_each_parent_via_the_link_header(self) -> None:
+ pages = {
+ f"{FASTLY_BASE_URL}/service?per_page=100": ([{"id": "S1"}], None),
+ f"{FASTLY_BASE_URL}/service/S1/version": [{"number": 1, "active": True}],
+ f"{FASTLY_BASE_URL}/service/S1/version/1/dictionary": [{"id": "D1"}],
+ f"{FASTLY_BASE_URL}/service/S1/dictionary/D1/items?per_page=100": (
+ [{"item_key": "a", "item_value": "1"}],
+ f"{FASTLY_BASE_URL}/service/S1/dictionary/D1/items?page=2",
+ ),
+ f"{FASTLY_BASE_URL}/service/S1/dictionary/D1/items?page=2": ([{"item_key": "b", "item_value": "2"}], None),
+ }
+ rows = _collect("dictionary_items", _FakeResumableManager(), pages)
+
+ assert [row["item_key"] for row in rows] == ["a", "b"]
+ # A dictionary item has no id, so the key needs both parents to stay unique table-wide.
+ assert all(row["service_id"] == "S1" and row["dictionary_id"] == "D1" for row in rows)
+
+ def test_bookmark_advances_once_per_service_not_per_parent(self) -> None:
+ pages = {
+ f"{FASTLY_BASE_URL}/service?per_page=100": ([{"id": "S1"}, {"id": "S2"}], None),
+ f"{FASTLY_BASE_URL}/service/S1/version": [{"number": 1, "active": True}],
+ f"{FASTLY_BASE_URL}/service/S1/version/1/acl": [{"id": "A1"}, {"id": "A2"}],
+ f"{FASTLY_BASE_URL}/service/S1/acl/A1/entries?per_page=100": [{"id": "E1"}],
+ f"{FASTLY_BASE_URL}/service/S1/acl/A2/entries?per_page=100": [{"id": "E2"}],
+ f"{FASTLY_BASE_URL}/service/S2/version": [],
+ }
+ manager = _FakeResumableManager()
+ rows = _collect("acl_entries", manager, pages)
+
+ assert [row["id"] for row in rows] == ["E1", "E2"]
+ assert [s.service_id for s in manager.saved] == ["S1", "S2"]
+
+ def test_write_only_dictionary_is_not_requested(self) -> None:
+ # Fastly refuses to list the items of a write-only dictionary, which would abort the sync.
+ pages = {
+ f"{FASTLY_BASE_URL}/service?per_page=100": ([{"id": "S1"}], None),
+ f"{FASTLY_BASE_URL}/service/S1/version": [{"number": 1, "active": True}],
+ f"{FASTLY_BASE_URL}/service/S1/version/1/dictionary": [
+ {"id": "D1", "write_only": True},
+ {"id": "D2", "write_only": False},
+ ],
+ f"{FASTLY_BASE_URL}/service/S1/dictionary/D2/items?per_page=100": [{"item_key": "a"}],
+ }
+ rows = _collect("dictionary_items", _FakeResumableManager(), pages)
+ assert [row["dictionary_id"] for row in rows] == ["D2"]
+
+ def test_repeated_next_link_stops_instead_of_looping(self) -> None:
+ self_referencing = f"{FASTLY_BASE_URL}/service/S1/acl/A1/entries?per_page=100"
+ pages = {
+ f"{FASTLY_BASE_URL}/service?per_page=100": ([{"id": "S1"}], None),
+ f"{FASTLY_BASE_URL}/service/S1/version": [{"number": 1, "active": True}],
+ f"{FASTLY_BASE_URL}/service/S1/version/1/acl": [{"id": "A1"}],
+ self_referencing: ([{"id": "E1"}], self_referencing),
+ }
+ with pytest.raises(FastlyPaginationError):
+ _collect("acl_entries", _FakeResumableManager(), pages)
+
+ def test_parent_without_an_id_is_skipped(self) -> None:
+ pages = {
+ f"{FASTLY_BASE_URL}/service?per_page=100": ([{"id": "S1"}], None),
+ f"{FASTLY_BASE_URL}/service/S1/version": [{"number": 1, "active": True}],
+ f"{FASTLY_BASE_URL}/service/S1/version/1/acl": [{"name": "no-id-here"}],
+ }
+ assert _collect("acl_entries", _FakeResumableManager(), pages) == []
+
+
+class TestGetRowsBillingList:
+ def test_follows_the_cursor_and_saves_it_after_each_page(self) -> None:
+ pages = {
+ f"{FASTLY_BASE_URL}/billing/v3/invoices?limit=200": {
+ "data": [{"invoice_id": "1"}],
+ "meta": {"next_cursor": "CUR2"},
+ },
+ f"{FASTLY_BASE_URL}/billing/v3/invoices?limit=200&cursor=CUR2": {
+ "data": [{"invoice_id": "2"}],
+ "meta": {"next_cursor": ""},
+ },
+ }
+ manager = _FakeResumableManager()
+ rows = _collect("invoices", manager, pages)
+
+ assert rows == [{"invoice_id": "1"}, {"invoice_id": "2"}]
+ assert [s.cursor for s in manager.saved] == ["CUR2"]
+
+ def test_resumes_from_the_saved_cursor(self) -> None:
+ pages = {
+ f"{FASTLY_BASE_URL}/billing/v3/invoices?limit=200&cursor=CUR2": {
+ "data": [{"invoice_id": "2"}],
+ "meta": {},
+ },
+ }
+ manager = _FakeResumableManager(
+ FastlyResumeConfig(cursor="CUR2", cursor_request="/billing/v3/invoices?limit=200")
+ )
+ assert _collect("invoices", manager, pages) == [{"invoice_id": "2"}]
+
+ def test_repeated_cursor_stops_instead_of_looping(self) -> None:
+ # A cursor pointing back at the page just read would re-fetch and re-yield it forever.
+ pages = {
+ f"{FASTLY_BASE_URL}/billing/v3/invoices?limit=200": {
+ "data": [{"invoice_id": "1"}],
+ "meta": {"next_cursor": "CUR2"},
+ },
+ f"{FASTLY_BASE_URL}/billing/v3/invoices?limit=200&cursor=CUR2": {
+ "data": [{"invoice_id": "2"}],
+ "meta": {"next_cursor": "CUR2"},
+ },
+ }
+ with pytest.raises(FastlyPaginationError):
+ _collect("invoices", _FakeResumableManager(), pages)
+
+ def test_non_dict_payload_yields_nothing(self) -> None:
+ pages: dict[str, Any] = {f"{FASTLY_BASE_URL}/billing/v3/invoices?limit=200": []}
+ assert _collect("invoices", _FakeResumableManager(), pages) == []
+
+
+class TestGetRowsBillingUsageMetrics:
+ def test_requests_a_three_month_window_and_flattens_each_page(self) -> None:
+ window = _usage_metrics_window()
+ first = (
+ f"{FASTLY_BASE_URL}/billing/v3/service-usage-metrics"
+ f"?start_month={window['start_month']}&end_month={window['end_month']}"
+ )
+ pages = {
+ first: {
+ "data": {
+ "usage_type": "Bandwidth",
+ "details": [{"service_id": "S1", "usage_units": 1.0}],
+ "meta": {"next_cursor": "CUR2"},
+ }
+ },
+ f"{first}&cursor=CUR2": {
+ "data": {
+ "usage_type": "Bandwidth",
+ "details": [{"service_id": "S2", "usage_units": 2.0}],
+ "meta": {},
+ }
+ },
+ }
+ manager = _FakeResumableManager()
+ rows = _collect("billing_usage_metrics", manager, pages)
+
+ assert [row["service_id"] for row in rows] == ["S1", "S2"]
+ assert [s.cursor for s in manager.saved] == ["CUR2"]
+
+ def test_cursor_saved_under_a_different_window_is_discarded(self) -> None:
+ # A run resuming after the UTC month rolls over computes a new window. Fastly only continues
+ # the request that produced the cursor, so the stale one has to be dropped.
+ window = _usage_metrics_window()
+ first = (
+ f"{FASTLY_BASE_URL}/billing/v3/service-usage-metrics"
+ f"?start_month={window['start_month']}&end_month={window['end_month']}"
+ )
+ pages = {
+ first: {"data": {"usage_type": "Bandwidth", "details": [{"service_id": "S1"}], "meta": {}}},
+ }
+ manager = _FakeResumableManager(
+ FastlyResumeConfig(cursor="STALE", cursor_request="/billing/v3/service-usage-metrics?end_month=1999-01")
+ )
+ assert _collect("billing_usage_metrics", manager, pages) == [{"usage_type": "Bandwidth", "service_id": "S1"}]
+
+
class TestFastlySourceResponse:
@parameterized.expand([(name,) for name in ENDPOINTS])
def test_source_response_primary_keys_match_settings(self, endpoint: str) -> None:
@@ -298,7 +567,7 @@ class TestFastlySourceResponse:
assert response.primary_keys == FASTLY_ENDPOINTS[endpoint].primary_keys
@parameterized.expand([(name,) for name in ENDPOINTS])
- def test_source_response_partitions_on_stable_created_at(self, endpoint: str) -> None:
+ def test_source_response_partitions_on_a_stable_key(self, endpoint: str) -> None:
response = fastly_source(
api_key="token",
endpoint=endpoint,
@@ -306,4 +575,6 @@ class TestFastlySourceResponse:
resumable_source_manager=MagicMock(),
)
assert response.partition_mode == "datetime"
- assert response.partition_keys == ["created_at"]
+ 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)