: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 fastly import source (#67790)
Tom Owersf91e6689d629
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.mdindex 1d887152fa16..a7da497d3c52 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md@@ -142,6 +142,7 @@ the row lists both.| exchange_rates_api | HTTP | requests | ✅ || ezofficeinventory | HTTP | requests | ✅ || factorial | HTTP | requests + `rest_source.RESTClient` | ✅ |+| fastly | HTTP | requests | ✅ || fillout | HTTP | requests + `rest_source.RESTClient` | ✅ || finage | HTTP | requests | ✅ || financial_modelling | HTTP | requests | ✅ |@@ -398,7 +399,6 @@ doesn't conflict with concurrent PRs.- expensify- facebook_pages- fastbill-- fastly- fauna- feishu- firebasediff --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.pynew file mode 100644index 000000000000..99ba143036d1--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/fastly/canonical_descriptions.py@@ -0,0 +1,111 @@+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (+ CanonicalDescriptions,+)++# Descriptions taken from Fastly's public API docs (https://www.fastly.com/documentation/reference/api/).+CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {+ "current_user": {+ "description": "The user whose API token authenticates this connection.",+ "docs_url": "https://www.fastly.com/documentation/reference/api/account/user/",+ "columns": {+ "id": "Unique identifier for the user.",+ "login": "The login (email) associated with the user.",+ "name": "The real-life name of the user.",+ "role": "The user's role within the customer account.",+ "customer_id": "Identifier of the customer the user belongs to.",+ "email_hash": "Hashed version of the user's email address.",+ "two_factor_auth_enabled": "Whether two-factor authentication is enabled for the user.",+ "locked": "Whether the user is locked out of the account.",+ "created_at": "Timestamp (UTC) of when the user was created.",+ "updated_at": "Timestamp (UTC) of when the user was last updated.",+ "deleted_at": "Timestamp (UTC) of when the user was deleted, if applicable.",+ },+ },+ "services": {+ "description": "Every Fastly service in the account.",+ "docs_url": "https://www.fastly.com/documentation/reference/api/services/service/",+ "columns": {+ "id": "Alphanumeric string identifying the service.",+ "name": "The name of the service.",+ "customer_id": "Identifier of the customer that owns the service.",+ "type": "The type of the service (vcl or wasm).",+ "comment": "A freeform descriptive note.",+ "version": "The active version number for the service.",+ "created_at": "Timestamp (UTC) of when the service was created.",+ "updated_at": "Timestamp (UTC) of when the service was last updated.",+ "deleted_at": "Timestamp (UTC) of when the service was deleted, if applicable.",+ },+ },+ "service_versions": {+ "description": "All configuration versions for each service.",+ "docs_url": "https://www.fastly.com/documentation/reference/api/services/version/",+ "columns": {+ "number": "The version number of the configuration (unique within a service).",+ "service_id": "Alphanumeric string identifying the service.",+ "active": "Whether this version is currently active.",+ "staging": "Whether this version is staged.",+ "testing": "Whether this version is in a testing state.",+ "locked": "Whether this version is locked from further edits.",+ "deployed": "Whether this version has been deployed.",+ "comment": "A freeform descriptive note.",+ "created_at": "Timestamp (UTC) of when the version was created.",+ "updated_at": "Timestamp (UTC) of when the version was last updated.",+ "deleted_at": "Timestamp (UTC) of when the version was deleted, if applicable.",+ },+ },+ "service_domains": {+ "description": "Domains attached to each service's active version.",+ "docs_url": "https://www.fastly.com/documentation/reference/api/services/domain/",+ "columns": {+ "name": "The domain name (hostname).",+ "service_id": "Alphanumeric string identifying the service.",+ "version": "The service version number the domain belongs to.",+ "comment": "A freeform descriptive note.",+ "created_at": "Timestamp (UTC) of when the domain was created.",+ "updated_at": "Timestamp (UTC) of when the domain was last updated.",+ "deleted_at": "Timestamp (UTC) of when the domain was deleted, if applicable.",+ },+ },+ "service_backends": {+ "description": "Origin backends configured on each service's active version.",+ "docs_url": "https://www.fastly.com/documentation/reference/api/services/backend/",+ "columns": {+ "name": "The name of the backend.",+ "service_id": "Alphanumeric string identifying the service.",+ "version": "The service version number the backend belongs to.",+ "address": "A hostname, IPv4, or IPv6 address for the backend.",+ "port": "The port on which the backend listens.",+ "use_ssl": "Whether to use TLS to connect to the backend.",+ "created_at": "Timestamp (UTC) of when the backend was created.",+ "updated_at": "Timestamp (UTC) of when the backend was last updated.",+ "deleted_at": "Timestamp (UTC) of when the backend was deleted, if applicable.",+ },+ },+ "service_acls": {+ "description": "Access control lists on each service's active version.",+ "docs_url": "https://www.fastly.com/documentation/reference/api/acls/acl/",+ "columns": {+ "id": "Alphanumeric string identifying the ACL.",+ "name": "The name of the ACL.",+ "service_id": "Alphanumeric string identifying the service.",+ "version": "The service version number the ACL belongs to.",+ "created_at": "Timestamp (UTC) of when the ACL was created.",+ "updated_at": "Timestamp (UTC) of when the ACL was last updated.",+ "deleted_at": "Timestamp (UTC) of when the ACL was deleted, if applicable.",+ },+ },+ "service_dictionaries": {+ "description": "Edge dictionaries on each service's active version.",+ "docs_url": "https://www.fastly.com/documentation/reference/api/dictionaries/dictionary/",+ "columns": {+ "id": "Alphanumeric string identifying the dictionary.",+ "name": "The name of the dictionary.",+ "service_id": "Alphanumeric string identifying the service.",+ "version": "The service version number the dictionary belongs to.",+ "write_only": "Whether the dictionary is write-only (private).",+ "created_at": "Timestamp (UTC) of when the dictionary was created.",+ "updated_at": "Timestamp (UTC) of when the dictionary was last updated.",+ "deleted_at": "Timestamp (UTC) of when the dictionary was deleted, if applicable.",+ },+ },+}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.pynew file mode 100644index 000000000000..f5211e24b523--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/fastly/fastly.py@@ -0,0 +1,262 @@+import dataclasses+from collections.abc import Iterator+from typing import Any+from urllib.parse import urlencode++import requests+from structlog.types import FilteringBoundLogger+from tenacity import retry, retry_if_exception_type, stop_after_attempt, wait_exponential_jitter++from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import SourceResponse+from products.warehouse_sources.backend.temporal.data_imports.sources.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.fastly.settings import (+ FASTLY_ENDPOINTS,+ FastlyEndpointConfig,+)++FASTLY_BASE_URL = "https://api.fastly.com"++# Fastly caps read requests at ~6,000/minute per token. `/service` supports page-number pagination;+# the account's service count is small in practice, so a large page keeps the round-trip count down.+SERVICE_PAGE_SIZE = 100+++class FastlyRetryableError(Exception):+ pass+++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+++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:+ if not params:+ return base_url+ return f"{base_url}?{urlencode(params)}"+++@retry(+ retry=retry_if_exception_type(+ (+ FastlyRetryableError,+ requests.ReadTimeout,+ requests.ConnectionError,+ requests.exceptions.ChunkedEncodingError,+ )+ ),+ stop=stop_after_attempt(5),+ wait=wait_exponential_jitter(initial=1, max=30),+ reraise=True,+)+def _fetch(+ session: requests.Session, url: str, headers: dict[str, str], logger: FilteringBoundLogger+) -> requests.Response:+ response = session.get(url, headers=headers, timeout=60)++ # 429 carries rate-limit reset headers; 5xx are transient. Both are retryable.+ if response.status_code == 429 or response.status_code >= 500:+ raise FastlyRetryableError(f"Fastly API error (retryable): status={response.status_code}, url={url}")++ if not response.ok:+ logger.error(f"Fastly API error: status={response.status_code}, body={response.text}, url={url}")+ response.raise_for_status()++ return response+++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")+++def validate_credentials(api_key: str) -> bool:+ try:+ response = make_tracked_session(redact_values=(api_key,)).get(+ f"{FASTLY_BASE_URL}/current_user", headers=_get_headers(api_key), timeout=10+ )+ return response.status_code == 200+ except requests.RequestException:+ # A network blip / timeout at source-create can't confirm the token, so report it as invalid+ # rather than crashing setup. Non-request errors are unexpected and left to propagate.+ 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}+ return row+++def _iter_services(+ session: requests.Session, headers: dict[str, str], logger: FilteringBoundLogger+) -> Iterator[dict[str, Any]]:+ """Page through GET /service, yielding each service object. Used to drive fan-out endpoints."""+ url = _build_url(f"{FASTLY_BASE_URL}/service", {"per_page": SERVICE_PAGE_SIZE})+ while True:+ response = _fetch(session, url, headers, logger)+ items = response.json()+ if isinstance(items, list):+ yield from items+ next_url = _next_page_url(response)+ if not next_url:+ break+ url = next_url+++def _active_version_number(+ session: requests.Session, service_id: str, headers: dict[str, str], logger: FilteringBoundLogger+) -> int | None:+ """Resolve the version to read version-scoped resources from: the active version, else the highest+ version number. Fastly config resources are version-scoped, so syncing the active version reflects+ the service's current production configuration."""+ response = _fetch(session, f"{FASTLY_BASE_URL}/service/{service_id}/version", headers, logger)+ versions = response.json()+ if not isinstance(versions, list):+ return None++ active = [v["number"] for v in versions if isinstance(v, dict) and v.get("active") and "number" in v]+ if active:+ return max(active)++ numbers = [v["number"] for v in versions if isinstance(v, dict) and isinstance(v.get("number"), int)]+ return max(numbers) if numbers else None+++def _get_object_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()+ if isinstance(data, dict):+ yield [data]+ elif isinstance(data, list) and data:+ yield data+++def _get_service_list_rows(+ session: requests.Session,+ 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 = resume.next_url+ logger.debug(f"Fastly: resuming services from URL: {url}")+ else:+ url = _build_url(f"{FASTLY_BASE_URL}/service", {"per_page": SERVICE_PAGE_SIZE})++ while True:+ response = _fetch(session, url, headers, logger)+ items = response.json()+ if isinstance(items, list) and items:+ yield items++ next_url = _next_page_url(response)+ if not next_url:+ break+ # Save 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_fanout_rows(+ session: requests.Session,+ config: FastlyEndpointConfig,+ headers: dict[str, str],+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[FastlyResumeConfig],+) -> Iterator[list[dict[str, Any]]]:+ 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:+ start = service_ids.index(resume.service_id)+ 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]] = []+ 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 []+ 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)]+ 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(+ api_key: str,+ endpoint: str,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[FastlyResumeConfig],+) -> Iterator[list[dict[str, Any]]]:+ config = FASTLY_ENDPOINTS[endpoint]+ headers = _get_headers(api_key)+ # Redact the token so it never lands in captured HTTP samples — Fastly's custom `Fastly-Key`+ # header isn't covered by the transport's known-auth-header scrubbing.+ session = make_tracked_session(redact_values=(api_key,))++ if config.kind == "object":+ 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)+ else:+ yield from _get_fanout_rows(session, config, headers, logger, resumable_source_manager)+++def fastly_source(+ api_key: str,+ endpoint: str,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[FastlyResumeConfig],+) -> SourceResponse:+ config = FASTLY_ENDPOINTS[endpoint]++ return SourceResponse(+ name=endpoint,+ items=lambda: get_rows(+ api_key=api_key,+ endpoint=endpoint,+ logger=logger,+ resumable_source_manager=resumable_source_manager,+ ),+ primary_keys=config.primary_keys,+ partition_count=1,+ partition_size=1,+ 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,+ )+++__all__ = ["FastlyResumeConfig", "fastly_source", "validate_credentials"]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.pynew file mode 100644index 000000000000..8f64fb76af7f--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/fastly/settings.py@@ -0,0 +1,83 @@+from dataclasses import dataclass, field+from typing import Literal++# 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"]+++@dataclass+class FastlyEndpointConfig:+ name: str+ path: str+ kind: FastlyEndpointKind+ # Partition on a STABLE creation timestamp so partitions aren't rewritten every sync.+ partition_key: str | None = "created_at"+ should_sync_default: bool = True+ description: str | None = None+ # 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-scoped resource paths carry `{service_id}` and `{version}` placeholders that the+# transport formats with the service id and its active version number.+FASTLY_ENDPOINTS: dict[str, FastlyEndpointConfig] = {+ "current_user": FastlyEndpointConfig(+ name="current_user",+ path="/current_user",+ kind="object",+ primary_keys=["id"],+ description="The user whose API token authenticates this connection.",+ ),+ "services": FastlyEndpointConfig(+ name="services",+ path="/service",+ kind="service_list",+ primary_keys=["id"],+ description="Every Fastly service in the account.",+ ),+ "service_versions": FastlyEndpointConfig(+ name="service_versions",+ path="/service/{service_id}/version",+ kind="version_list",+ primary_keys=["service_id", "number"],+ description="All configuration versions for each service.",+ ),+ "service_domains": FastlyEndpointConfig(+ name="service_domains",+ path="/service/{service_id}/version/{version}/domain",+ kind="version_resource",+ primary_keys=["service_id", "version", "name"],+ description="Domains attached to each service's active version.",+ ),+ "service_backends": FastlyEndpointConfig(+ name="service_backends",+ path="/service/{service_id}/version/{version}/backend",+ kind="version_resource",+ primary_keys=["service_id", "version", "name"],+ description="Origin backends configured on each service's active version.",+ ),+ "service_acls": FastlyEndpointConfig(+ name="service_acls",+ path="/service/{service_id}/version/{version}/acl",+ kind="version_resource",+ # ACL ids are globally unique; the service id is kept in the key defensively.+ primary_keys=["service_id", "id"],+ description="Access control lists on each service's active version.",+ ),+ "service_dictionaries": FastlyEndpointConfig(+ name="service_dictionaries",+ path="/service/{service_id}/version/{version}/dictionary",+ kind="version_resource",+ # Dictionary ids are globally unique; the service id is kept in the key defensively.+ primary_keys=["service_id", "id"],+ description="Edge dictionaries on each service's active version.",+ ),+}++ENDPOINTS = tuple(FASTLY_ENDPOINTS.keys())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 815853faee30..52a0527f4e5e 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@@ -1,19 +1,39 @@-from typing import cast+from typing import Optional, castfrom posthog.schema import (DataWarehouseSourceCategory,ExternalDataSourceType as SchemaExternalDataSourceType,+ ReleaseStatus,SourceConfig,+ SourceFieldInputConfig,+ SourceFieldInputConfigType,)-from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, SimpleSource+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import (+ SourceInputs,+ SourceResponse,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.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+from products.warehouse_sources.backend.temporal.data_imports.sources.fastly.fastly import (+ FastlyResumeConfig,+ fastly_source,+ validate_credentials as validate_fastly_credentials,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.fastly.settings import ENDPOINTS, FASTLY_ENDPOINTSfrom products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs import FastlySourceConfigfrom products.warehouse_sources.backend.types import ExternalDataSourceType@SourceRegistry.register-class FastlySource(SimpleSource[FastlySourceConfig]):+class FastlySource(ResumableSource[FastlySourceConfig, FastlyResumeConfig]):+ lists_tables_without_credentials = True # static endpoint catalog — safe for public docs+@propertydef source_type(self) -> ExternalDataSourceType:return ExternalDataSourceType.FASTLY@@ -24,7 +44,93 @@ class FastlySource(SimpleSource[FastlySourceConfig]):name=SchemaExternalDataSourceType.FASTLY,category=DataWarehouseSourceCategory.ENGINEERING___MONITORING,label="Fastly",+ releaseStatus=ReleaseStatus.ALPHA,+ caption="""Enter your Fastly API token to automatically pull your Fastly account and service configuration into the PostHog Data warehouse.++You can create an API token in your [Fastly account settings](https://manage.fastly.com/account/personal/tokens).++A read-only token with **global** scope is sufficient to sync every table.""",iconPath="/static/services/fastly.png",- fields=cast(list[FieldType], []),+ docsUrl="https://posthog.com/docs/cdp/sources/fastly",unreleasedSource=True,+ fields=cast(+ list[FieldType],+ [+ SourceFieldInputConfig(+ name="api_key",+ label="API token",+ type=SourceFieldInputConfigType.PASSWORD,+ required=True,+ placeholder="",+ secret=True,+ ),+ ],+ ),+ )++ def get_canonical_descriptions(self) -> CanonicalDescriptions:+ from products.warehouse_sources.backend.temporal.data_imports.sources.fastly.canonical_descriptions import (+ CANONICAL_DESCRIPTIONS,+ )++ return CANONICAL_DESCRIPTIONS++ def get_non_retryable_errors(self) -> dict[str, str | None]:+ return {+ # A missing, invalid, or under-scoped Fastly token surfaces as an HTTPError when+ # `_fetch` calls `raise_for_status()`. Retrying can never satisfy a credential+ # problem. Match the stable status text and base host, not the per-request path.+ "401 Client Error: Unauthorized for url: https://api.fastly.com": "Your Fastly API token is missing or invalid. Create a new token in your Fastly account settings, then reconnect.",+ "403 Client Error: Forbidden for url: https://api.fastly.com": "Your Fastly API token does not have the scope needed to sync this data. Grant it read access, then reconnect.",+ }++ def get_schemas(+ self,+ config: FastlySourceConfig,+ team_id: int,+ with_counts: bool = False,+ names: list[str] | None = None,+ force_refresh: bool = False,+ ) -> 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.+ def _build_schema(endpoint: str) -> SourceSchema:+ endpoint_config = FASTLY_ENDPOINTS[endpoint]+ return SourceSchema(+ name=endpoint,+ supports_incremental=False,+ supports_append=False,+ incremental_fields=[],+ should_sync_default=endpoint_config.should_sync_default,+ description=endpoint_config.description,+ )++ schemas = [_build_schema(endpoint) for endpoint in ENDPOINTS]+ if names is not None:+ names_set = set(names)+ schemas = [s for s in schemas if s.name in names_set]+ return schemas++ def validate_credentials(+ self, config: FastlySourceConfig, team_id: int, schema_name: Optional[str] = None+ ) -> tuple[bool, str | None]:+ if validate_fastly_credentials(config.api_key):+ return True, None++ return False, "Invalid Fastly API token"++ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[FastlyResumeConfig]:+ return ResumableSourceManager[FastlyResumeConfig](inputs, FastlyResumeConfig)++ def source_for_pipeline(+ self,+ config: FastlySourceConfig,+ resumable_source_manager: ResumableSourceManager[FastlyResumeConfig],+ inputs: SourceInputs,+ ) -> SourceResponse:+ return fastly_source(+ api_key=config.api_key,+ endpoint=inputs.schema_name,+ logger=inputs.logger,+ resumable_source_manager=resumable_source_manager,)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.pynew file mode 100644index 000000000000..f5c01a47c037--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/fastly/tests/test_fastly.py@@ -0,0 +1,309 @@+from typing import Any++import pytest+from unittest.mock import MagicMock, patch++import requests+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,+ FastlyResumeConfig,+ FastlyRetryableError,+ _active_version_number,+ _build_url,+ _ensure_service_id,+ _next_page_url,+ fastly_source,+ get_rows,+ validate_credentials,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.fastly.settings import ENDPOINTS, FASTLY_ENDPOINTS+++def _fake_response(payload: Any, next_url: str | None = None) -> MagicMock:+ response = MagicMock()+ response.json.return_value = payload+ response.links = {"next": {"url": next_url}} if next_url else {}+ return response+++class _FakeResumableManager:+ def __init__(self, state: FastlyResumeConfig | None = None) -> None:+ self._state = state+ self.saved: list[FastlyResumeConfig] = []++ def can_resume(self) -> bool:+ return self._state is not None++ def load_state(self) -> FastlyResumeConfig | None:+ return self._state++ def save_state(self, data: FastlyResumeConfig) -> None:+ self.saved.append(data)+++class TestBuildUrl:+ def test_no_params_returns_base(self) -> None:+ assert _build_url(f"{FASTLY_BASE_URL}/service", {}) == f"{FASTLY_BASE_URL}/service"++ def test_encodes_params(self) -> None:+ assert _build_url(f"{FASTLY_BASE_URL}/service", {"per_page": 100}) == f"{FASTLY_BASE_URL}/service?per_page=100"+++class TestNextPageUrl:+ def test_reads_next_link(self) -> None:+ response = MagicMock()+ response.links = {"next": {"url": "https://api.fastly.com/service?page=2"}}+ assert _next_page_url(response) == "https://api.fastly.com/service?page=2"++ def test_no_next_link_returns_none(self) -> None:+ response = MagicMock()+ response.links = {}+ assert _next_page_url(response) is None+++class TestEnsureServiceId:+ def test_injects_missing_service_id(self) -> None:+ assert _ensure_service_id({"name": "www"}, "SVC")["service_id"] == "SVC"++ def test_keeps_existing_service_id(self) -> None:+ assert _ensure_service_id({"service_id": "REAL"}, "SVC")["service_id"] == "REAL"+++class TestActiveVersionNumber:+ @parameterized.expand(+ [+ # The active version is preferred, even when a higher (draft) version number exists.+ ("prefers_active", [{"number": 1, "active": True}, {"number": 2, "active": False}], 1),+ # With no active version, fall back to the highest version number.+ ("falls_back_to_highest", [{"number": 1, "active": False}, {"number": 3, "active": False}], 3),+ ("no_versions", [], None),+ ]+ )+ def test_active_version_number(self, _name: str, versions: list[dict], expected: int | None) -> None:+ session = MagicMock()+ with patch.object(fastly, "_fetch", return_value=_fake_response(versions)):+ assert _active_version_number(session, "SVC", {}, MagicMock()) == expected+++class TestValidateCredentials:+ @parameterized.expand([("ok", 200, True), ("unauthorized", 401, False)])+ def test_validate_credentials_status_mapping(self, _name: str, status_code: int, expected: bool) -> None:+ response = MagicMock()+ response.status_code = status_code+ session = MagicMock()+ session.get.return_value = response+ with patch.object(fastly, "make_tracked_session", return_value=session):+ assert validate_credentials("token") is expected++ def test_validate_credentials_swallows_exceptions(self) -> None:+ session = MagicMock()+ session.get.side_effect = requests.ConnectionError("boom")+ with patch.object(fastly, "make_tracked_session", return_value=session):+ assert validate_credentials("token") is False+++class TestTokenRedaction:+ # The token rides in the custom `Fastly-Key` header, which the transport's name-based scrubber+ # doesn't know about — both entry points must pass it as a redact value or it leaks into samples.+ def test_validate_credentials_redacts_token(self) -> None:+ make_session = MagicMock(return_value=MagicMock())+ with patch.object(fastly, "make_tracked_session", make_session):+ validate_credentials("secret-token")+ assert make_session.call_args.kwargs["redact_values"] == ("secret-token",)++ def test_get_rows_redacts_token(self) -> None:+ make_session = MagicMock(return_value=MagicMock())+ pages = {f"{FASTLY_BASE_URL}/current_user": {"id": "U1"}}++ def fake_fetch(session: Any, url: str, headers: dict[str, str], logger: Any) -> Any:+ return _fake_response(pages[url])++ with (+ patch.object(fastly, "_fetch", side_effect=fake_fetch),+ patch.object(fastly, "make_tracked_session", make_session),+ ):+ list(get_rows("secret-token", "current_user", MagicMock(), _FakeResumableManager())) # type: ignore[arg-type]+ assert make_session.call_args.kwargs["redact_values"] == ("secret-token",)+++class TestFetchRetries:+ @parameterized.expand([("rate_limited", 429), ("server_error", 500), ("bad_gateway", 502)])+ def test_retryable_status_retries_then_succeeds(self, _name: str, status_code: int) -> None:+ bad = MagicMock()+ bad.status_code = status_code+ good = MagicMock()+ good.status_code = 200+ good.ok = True++ session = MagicMock()+ session.get.side_effect = [bad, good]++ with patch.object(fastly._fetch.retry, "sleep", lambda *_: None): # type: ignore[attr-defined]+ result = fastly._fetch(session, f"{FASTLY_BASE_URL}/service", {}, MagicMock())++ assert result is good+ assert session.get.call_count == 2++ @parameterized.expand(+ [+ ("read_timeout", requests.ReadTimeout("Read timed out.")),+ ("connection_error", requests.ConnectionError("Connection reset by peer")),+ ("chunked", requests.exceptions.ChunkedEncodingError("Connection broken")),+ ]+ )+ def test_transient_exceptions_retried(self, _name: str, exc: Exception) -> None:+ good = MagicMock()+ good.status_code = 200+ good.ok = True++ session = MagicMock()+ session.get.side_effect = [exc, good]++ with patch.object(fastly._fetch.retry, "sleep", lambda *_: None): # type: ignore[attr-defined]+ result = fastly._fetch(session, f"{FASTLY_BASE_URL}/service", {}, MagicMock())++ assert result is good+ assert session.get.call_count == 2++ def test_retryable_reraised_after_exhausting_attempts(self) -> None:+ bad = MagicMock()+ bad.status_code = 503+ session = MagicMock()+ session.get.return_value = bad++ with patch.object(fastly._fetch.retry, "sleep", lambda *_: None): # type: ignore[attr-defined]+ with pytest.raises(FastlyRetryableError):+ fastly._fetch(session, f"{FASTLY_BASE_URL}/service", {}, MagicMock())++ assert session.get.call_count == 5+++def _collect(endpoint: str, manager: _FakeResumableManager, pages: dict[str, Any]) -> list[dict]:+ def fake_fetch(session: Any, url: str, headers: dict[str, str], logger: Any) -> Any:+ payload = pages[url]+ if isinstance(payload, tuple):+ body, next_url = payload+ return _fake_response(body, next_url)+ return _fake_response(payload)++ rows: list[dict] = []+ with (+ patch.object(fastly, "_fetch", side_effect=fake_fetch),+ patch.object(fastly, "make_tracked_session", return_value=MagicMock()),+ ):+ for batch in get_rows(+ api_key="token",+ endpoint=endpoint,+ logger=MagicMock(),+ resumable_source_manager=manager, # type: ignore[arg-type]+ ):+ rows.extend(batch)+ return rows+++class TestGetRowsObject:+ def test_single_object_is_wrapped_in_a_list(self) -> None:+ pages = {f"{FASTLY_BASE_URL}/current_user": {"id": "U1", "login": "[email protected]"}}+ rows = _collect("current_user", _FakeResumableManager(), pages)+ assert rows == [{"id": "U1", "login": "[email protected]"}]+++class TestGetRowsServiceList:+ def test_paginates_and_saves_state_after_each_page(self) -> None:+ pages = {+ f"{FASTLY_BASE_URL}/service?per_page=100": ([{"id": "S1"}], f"{FASTLY_BASE_URL}/service?page=2"),+ f"{FASTLY_BASE_URL}/service?page=2": ([{"id": "S2"}], None),+ }+ manager = _FakeResumableManager()+ rows = _collect("services", manager, pages)++ assert rows == [{"id": "S1"}, {"id": "S2"}]+ # State is saved once, after yielding page 1 (which has a next page), pointing at page 2.+ assert [s.next_url for s in manager.saved] == [f"{FASTLY_BASE_URL}/service?page=2"]++ def test_resumes_from_saved_next_url(self) -> None:+ pages = {f"{FASTLY_BASE_URL}/service?page=2": ([{"id": "S2"}], None)}+ manager = _FakeResumableManager(FastlyResumeConfig(next_url=f"{FASTLY_BASE_URL}/service?page=2"))+ rows = _collect("services", manager, pages)+ assert rows == [{"id": "S2"}]+++class TestGetRowsVersionListFanOut:+ def test_fans_out_over_services(self) -> None:+ pages = {+ f"{FASTLY_BASE_URL}/service?per_page=100": ([{"id": "S1"}, {"id": "S2"}], None),+ f"{FASTLY_BASE_URL}/service/S1/version": [{"service_id": "S1", "number": 1}],+ f"{FASTLY_BASE_URL}/service/S2/version": [{"service_id": "S2", "number": 2}],+ }+ manager = _FakeResumableManager()+ rows = _collect("service_versions", manager, pages)++ assert rows == [{"service_id": "S1", "number": 1}, {"service_id": "S2", "number": 2}]+ assert [s.service_id for s in manager.saved] == ["S1", "S2"]++ def test_resumes_from_saved_service_bookmark(self) -> None:+ pages = {+ f"{FASTLY_BASE_URL}/service?per_page=100": ([{"id": "S1"}, {"id": "S2"}], None),+ f"{FASTLY_BASE_URL}/service/S2/version": [{"service_id": "S2", "number": 2}],+ }+ # Bookmarked at S2 — S1 is already synced, so only S2 is (re-)processed.+ manager = _FakeResumableManager(FastlyResumeConfig(service_id="S2"))+ rows = _collect("service_versions", manager, pages)+ assert rows == [{"service_id": "S2", "number": 2}]+++class TestGetRowsVersionResourceFanOut:+ def test_uses_active_version_and_injects_service_id(self) -> None:+ pages = {+ f"{FASTLY_BASE_URL}/service?per_page=100": ([{"id": "S1"}], None),+ f"{FASTLY_BASE_URL}/service/S1/version": [+ {"number": 1, "active": False},+ {"number": 2, "active": True},+ ],+ # Only the active version (2) is read for the resource.+ f"{FASTLY_BASE_URL}/service/S1/version/2/backend": [{"name": "origin", "version": 2}],+ }+ rows = _collect("service_backends", _FakeResumableManager(), pages)+ assert rows == [{"name": "origin", "version": 2, "service_id": "S1"}]++ def test_service_without_versions_is_skipped_but_bookmark_advances(self) -> None:+ # A versionless service yields no rows, but its bookmark must still advance so resume doesn't+ # re-evaluate it on every future run.+ pages = {+ f"{FASTLY_BASE_URL}/service?per_page=100": ([{"id": "S1"}, {"id": "S2"}], None),+ f"{FASTLY_BASE_URL}/service/S1/version": [],+ f"{FASTLY_BASE_URL}/service/S2/version": [{"number": 1, "active": True}],+ f"{FASTLY_BASE_URL}/service/S2/version/1/backend": [{"name": "origin", "version": 1}],+ }+ manager = _FakeResumableManager()+ rows = _collect("service_backends", manager, pages)++ assert rows == [{"name": "origin", "version": 1, "service_id": "S2"}]+ assert [s.service_id for s in manager.saved] == ["S1", "S2"]+++class TestFastlySourceResponse:+ @parameterized.expand([(name,) for name in ENDPOINTS])+ def test_source_response_primary_keys_match_settings(self, endpoint: str) -> None:+ response = fastly_source(+ api_key="token",+ endpoint=endpoint,+ logger=MagicMock(),+ resumable_source_manager=MagicMock(),+ )+ assert response.name == endpoint+ 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:+ response = fastly_source(+ api_key="token",+ endpoint=endpoint,+ logger=MagicMock(),+ resumable_source_manager=MagicMock(),+ )+ assert response.partition_mode == "datetime"+ assert response.partition_keys == ["created_at"]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.pynew file mode 100644index 000000000000..9dcd2b383231--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/fastly/tests/test_fastly_source.py@@ -0,0 +1,130 @@+import pytest+from unittest import mock++from posthog.schema import ReleaseStatus, SourceFieldInputConfig, SourceFieldInputConfigType++from products.warehouse_sources.backend.temporal.data_imports.sources.fastly.settings import ENDPOINTS+from products.warehouse_sources.backend.temporal.data_imports.sources.fastly.source import FastlySource+from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs import FastlySourceConfig+from products.warehouse_sources.backend.types import ExternalDataSourceType+++class TestFastlySource:+ def setup_method(self):+ self.source = FastlySource()+ self.team_id = 123+ self.config = FastlySourceConfig(api_key="token123")++ def test_source_type(self):+ assert self.source.source_type == ExternalDataSourceType.FASTLY++ def test_get_source_config(self):+ config = self.source.get_source_config++ assert config.name.value == "Fastly"+ assert config.label == "Fastly"+ assert config.releaseStatus == ReleaseStatus.ALPHA+ assert config.unreleasedSource is True+ assert config.iconPath == "/static/services/fastly.png"+ assert config.docsUrl == "https://posthog.com/docs/cdp/sources/fastly"++ field_names = [f.name for f in config.fields if isinstance(f, SourceFieldInputConfig)]+ assert field_names == ["api_key"]++ def test_api_token_field_is_secret_password(self):+ config = self.source.get_source_config+ token_field = next(f for f in config.fields if isinstance(f, SourceFieldInputConfig) and f.name == "api_key")+ assert token_field.type == SourceFieldInputConfigType.PASSWORD+ assert token_field.secret is True+ assert token_field.required is True++ def test_lists_tables_without_credentials(self):+ # get_schemas iterates a static endpoint catalog with no I/O, so the public docs render tables.+ assert self.source.lists_tables_without_credentials is True++ @pytest.mark.parametrize(+ "observed_error",+ [+ "401 Client Error: Unauthorized for url: https://api.fastly.com/current_user",+ "403 Client Error: Forbidden for url: https://api.fastly.com/service/abc/version/1/backend",+ ],+ )+ def test_non_retryable_errors_match_auth_failures(self, observed_error):+ non_retryable_errors = self.source.get_non_retryable_errors()+ assert any(key in observed_error for key in non_retryable_errors)++ @pytest.mark.parametrize(+ "other_error",+ [+ "401 Client Error: Unauthorized for url: https://api.stripe.com/v1/customers",+ "500 Server Error for url: https://api.fastly.com/service",+ "429 Client Error: Too Many Requests for url: https://api.fastly.com/service",+ ],+ )+ def test_non_retryable_errors_does_not_match_unrelated(self, other_error):+ 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)++ 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)++ def test_get_schemas_have_descriptions(self):+ schemas = self.source.get_schemas(self.config, self.team_id)+ assert all(schema.description for schema in schemas)++ def test_get_schemas_filtered_by_names(self):+ schemas = self.source.get_schemas(self.config, self.team_id, names=["services"])+ assert len(schemas) == 1+ assert schemas[0].name == "services"++ def test_get_schemas_filtered_unknown_name_returns_empty(self):+ assert self.source.get_schemas(self.config, self.team_id, names=["nope"]) == []++ def test_canonical_descriptions_cover_every_endpoint(self):+ canonical = self.source.get_canonical_descriptions()+ assert set(canonical.keys()) == set(ENDPOINTS)++ @pytest.mark.parametrize(+ "mock_return, expected_valid, expected_message",+ [+ (True, True, None),+ (False, False, "Invalid Fastly API token"),+ ],+ )+ @mock.patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.fastly.source.validate_fastly_credentials"+ )+ def test_validate_credentials(self, mock_validate, mock_return, expected_valid, expected_message):+ mock_validate.return_value = mock_return++ is_valid, error_message = self.source.validate_credentials(self.config, self.team_id)++ assert is_valid is expected_valid+ assert error_message == expected_message+ mock_validate.assert_called_once_with("token123")++ def test_get_resumable_source_manager_bound_to_resume_config(self):+ from products.warehouse_sources.backend.temporal.data_imports.sources.fastly.fastly import FastlyResumeConfig++ inputs = mock.MagicMock()+ manager = self.source.get_resumable_source_manager(inputs)+ assert manager._data_class is FastlyResumeConfig++ @mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.fastly.source.fastly_source")+ def test_source_for_pipeline_plumbs_arguments(self, mock_fastly_source):+ inputs = mock.MagicMock()+ inputs.schema_name = "services"+ manager = mock.MagicMock()++ self.source.source_for_pipeline(self.config, manager, inputs)++ mock_fastly_source.assert_called_once()+ kwargs = mock_fastly_source.call_args.kwargs+ assert kwargs["api_key"] == "token123"+ assert kwargs["endpoint"] == "services"+ assert kwargs["resumable_source_manager"] is managerdiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.py b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.pyindex 6b07f63708c1..3456aae0a0a8 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.py@@ -1140,7 +1140,7 @@ class FastbillSourceConfig(config.Config):@config.configclass FastlySourceConfig(config.Config):- pass+ api_key: str@config.config