: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 netlify import source (#70033)
Tom Owers2b4e9f7a9b63
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.mdindex b09f125b3fc8..33fa2ab00113 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md@@ -266,6 +266,7 @@ the row lists both.| my_hours | HTTP | requests | ✅ || mysql | DB protocol | pymysql | ➖ || n8n | HTTP | requests | ✅ |+| netlify | HTTP | requests | ✅ || new_york_times | HTTP | requests | ✅ || news_api | HTTP | requests | ✅ || newsdata | HTTP | requests | ✅ |@@ -665,7 +666,6 @@ doesn't conflict with concurrent PRs.- navan- nebius_ai- neon-- netlify- netsuite- new_relic- news_apidiff --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 26588273c596..9a9f4ee78a23 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@@ -2451,7 +2451,7 @@ class NetSuiteSourceConfig(config.Config):@config.configclass NetlifySourceConfig(config.Config):- pass+ api_token: str@config.configdiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/netlify/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/netlify/canonical_descriptions.pynew file mode 100644index 000000000000..913310edbe04--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/netlify/canonical_descriptions.py@@ -0,0 +1,128 @@+"""Canonical, documentation-sourced descriptions for Netlify endpoints and columns.++Sourced from the official Netlify API reference (https://open-api.netlify.com/). Keyed by the+endpoint names in `settings.py` `NETLIFY_ENDPOINTS`, which match the `ExternalDataSchema.name` of a+synced Netlify table. Columns absent here fall back to LLM enrichment.+"""++from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (+ CanonicalDescriptions,+)++CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {+ "sites": {+ "description": "A site hosted on Netlify, including its domains, SSL, and published deploy.",+ "docs_url": "https://open-api.netlify.com/#tag/site",+ "columns": {+ "id": "Unique identifier for the site.",+ "name": "The site's name (the subdomain on netlify.app).",+ "state": "Current state of the site.",+ "custom_domain": "The site's custom domain, if configured.",+ "url": "The site's primary URL.",+ "ssl_url": "The site's HTTPS URL.",+ "admin_url": "URL of the site's admin dashboard on Netlify.",+ "account_id": "Identifier of the account that owns the site.",+ "account_slug": "Slug of the account that owns the site.",+ "created_at": "Time at which the site was created.",+ "updated_at": "Time at which the site was last updated.",+ "published_deploy": "The currently published deploy for the site.",+ },+ },+ "deploys": {+ "description": "A deploy of a site: a build of the site's content published to Netlify.",+ "docs_url": "https://open-api.netlify.com/#tag/deploy",+ "columns": {+ "id": "Unique identifier for the deploy.",+ "site_id": "Identifier of the site this deploy belongs to.",+ "build_id": "Identifier of the build that produced this deploy.",+ "state": "Current state of the deploy (e.g. new, building, ready, error).",+ "name": "The site name at the time of the deploy.",+ "url": "URL the deploy is served from.",+ "branch": "The git branch the deploy was built from.",+ "commit_ref": "The git commit SHA the deploy was built from.",+ "error_message": "Error message if the deploy failed.",+ "created_at": "Time at which the deploy was created.",+ "updated_at": "Time at which the deploy was last updated.",+ "published_at": "Time at which the deploy was published.",+ },+ },+ "builds": {+ "description": "A build of a site, producing a deploy. Includes build status and errors.",+ "docs_url": "https://open-api.netlify.com/#tag/build",+ "columns": {+ "id": "Unique identifier for the build.",+ "site_id": "Identifier of the site this build belongs to (injected from the parent site).",+ "deploy_id": "Identifier of the deploy this build produced.",+ "sha": "The git commit SHA the build was triggered from.",+ "done": "Whether the build has finished.",+ "error": "Error message if the build failed.",+ "created_at": "Time at which the build was created.",+ },+ },+ "forms": {+ "description": "A form defined on a Netlify site that collects submissions.",+ "docs_url": "https://open-api.netlify.com/#tag/form",+ "columns": {+ "id": "Unique identifier for the form.",+ "site_id": "Identifier of the site this form belongs to.",+ "name": "The form's name.",+ "paths": "The site paths the form is available on.",+ "submission_count": "Total number of submissions received by the form.",+ "fields": "The form's fields.",+ "created_at": "Time at which the form was created.",+ },+ },+ "submissions": {+ "description": "A single submission to a Netlify form, including the submitted field data.",+ "docs_url": "https://open-api.netlify.com/#tag/submission",+ "columns": {+ "id": "Unique identifier for the submission.",+ "site_id": "Identifier of the site the submission belongs to (injected from the parent site).",+ "number": "Sequential number of the submission within its form.",+ "email": "Email address submitted, if present.",+ "name": "Name submitted, if present.",+ "summary": "A short summary of the submission.",+ "body": "The submission body.",+ "data": "The raw submitted field data as a key/value object.",+ "created_at": "Time at which the submission was received.",+ },+ },+ "dns_zones": {+ "description": "A DNS zone managed by Netlify for a domain.",+ "docs_url": "https://open-api.netlify.com/#tag/dnsZone",+ "columns": {+ "id": "Unique identifier for the DNS zone.",+ "name": "The zone's domain name.",+ "account_id": "Identifier of the account that owns the zone.",+ "account_slug": "Slug of the account that owns the zone.",+ "site_id": "Identifier of the site the zone is linked to, if any.",+ "dns_servers": "The zone's authoritative DNS servers.",+ "created_at": "Time at which the zone was created.",+ "updated_at": "Time at which the zone was last updated.",+ },+ },+ "accounts": {+ "description": "A Netlify account (team) the authenticated user is a member of.",+ "docs_url": "https://open-api.netlify.com/#tag/account",+ "columns": {+ "id": "Unique identifier for the account.",+ "name": "The account's name.",+ "slug": "The account's slug, used in account-scoped API paths.",+ "type": "The account's plan type.",+ "owner_ids": "Identifiers of the account's owners.",+ "created_at": "Time at which the account was created.",+ "updated_at": "Time at which the account was last updated.",+ },+ },+ "members": {+ "description": "A member of a Netlify account, fanned out one row per account.",+ "docs_url": "https://open-api.netlify.com/#tag/member",+ "columns": {+ "id": "Unique identifier for the member.",+ "account_slug": "Slug of the account this membership belongs to (injected from the parent account).",+ "full_name": "The member's full name.",+ "email": "The member's email address.",+ "role": "The member's role within the account.",+ },+ },+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/netlify/netlify.py b/products/warehouse_sources/backend/temporal/data_imports/sources/netlify/netlify.pynew file mode 100644index 000000000000..85e3447802f6--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/netlify/netlify.py@@ -0,0 +1,342 @@+"""Netlify transport layer.++Netlify's REST API (https://open-api.netlify.com/) is a clean JSON surface behind a personal+access token sent as a Bearer header. Lists use 1-based `page`/`per_page` (max 100) pagination with+RFC-5988 `Link` headers (rel="next") for traversal.++No list endpoint accepts a server-side timestamp filter, so every table is full refresh — there is+no reliable server-side cursor to sync incrementally on. The source is still resumable: top-level+lists checkpoint the next page URL, and fan-out tables checkpoint the current parent page so a+resumed run re-fans that page (merge dedupes on the primary key).++Site-scoped tables (deploys, builds, forms, submissions) and account-scoped tables (members) are+fan-outs: we walk the parent list and call the child endpoint once per parent, injecting the parent+identifier onto each child row so the composite primary key stays unique table-wide.+"""++import re+import dataclasses+from collections.abc import Callable, Iterator+from typing import Any+from urllib.parse import urlencode, urljoin, urlparse++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.netlify.settings import (+ NETLIFY_ENDPOINTS,+ NetlifyEndpointConfig,+)++NETLIFY_BASE_URL = "https://api.netlify.com/api/v1"+_NETLIFY_PARSED_BASE = urlparse(NETLIFY_BASE_URL)+++class NetlifyResumeConfig:+ # Next URL to fetch. For top-level tables it's the next page URL; for fan-out tables it's the+ # current parent page URL (resume re-fans that page, merge dedupes on the primary key).+ next_url: str | None = None+++class NetlifyRetryableError(Exception):+ pass+++class NetlifyUntrustedURLError(Exception):+ """Raised when a next-page/resume URL points off the Netlify API host. We attach the account+ token to every request, so following an off-host URL would leak it; refuse instead."""+++class NetlifyPageCapExceededError(Exception):+ """Raised when a fan-out parent exceeds the per-parent page cap. Failing loudly beats silently+ writing an incomplete full-refresh table that later runs would keep re-truncating."""+++def _validate_netlify_url(url: str) -> str:+ """Reject a URL whose scheme or host differs from NETLIFY_BASE_URL.++ The next-page URL comes from a remote `Link` header (and from persisted resume state), and we+ send the account token with it. Pinning the scheme and host stops a tampered link from+ forwarding the token to an attacker-controlled server.+ """+ parsed = urlparse(url)+ if parsed.scheme != _NETLIFY_PARSED_BASE.scheme or parsed.netloc != _NETLIFY_PARSED_BASE.netloc:+ raise NetlifyUntrustedURLError(f"Netlify: refusing to follow off-host URL: {url}")+ return url+++def _get_headers(api_token: str) -> dict[str, str]:+ return {+ "Authorization": f"Bearer {api_token}",+ "Accept": "application/json",+ "User-Agent": "PostHog",+ }+++def _parse_next_url(link_header: str, base_url: str = NETLIFY_BASE_URL) -> str | None:+ """Return the URL with rel="next" from Netlify's RFC-5988 Link header, if any.++ Relative links are resolved against the request URL, and the result is pinned to the Netlify+ host so a tampered link can't redirect the token off-host.+ """+ if not link_header:+ return None+ for part in link_header.split(","):+ part = part.strip()+ match = re.match(r'<([^>]+)>;\s*rel="next"', part)+ if match:+ return _validate_netlify_url(urljoin(base_url, match.group(1)))+ return None+++@retry(+ retry=retry_if_exception_type(+ (+ NetlifyRetryableError,+ requests.ReadTimeout,+ requests.ConnectionError,+ # A chunked response the server truncates mid-body surfaces as ChunkedEncodingError+ # (a direct RequestException subclass); it's transient, so a fresh GET re-fetches the page.+ requests.exceptions.ChunkedEncodingError,+ )+ ),+ stop=stop_after_attempt(5),+ wait=wait_exponential_jitter(initial=1, max=30),+ reraise=True,+)+def _fetch_page(+ session: requests.Session, url: str, headers: dict[str, str], logger: FilteringBoundLogger+) -> requests.Response:+ response = session.get(url, headers=headers, timeout=60)++ # Netlify rate-limits at 500 req/min and returns 429; transient 5xx are retryable too. We don't+ # have a token to confirm the exact Retry-After header shape, so fall back to exponential backoff.+ if response.status_code == 429 or response.status_code >= 500:+ raise NetlifyRetryableError(f"Netlify API error (retryable): status={response.status_code}, url={url}")++ if not response.ok:+ logger.error(f"Netlify API error: status={response.status_code}, body={response.text}, url={url}")+ response.raise_for_status()++ return response+++def _build_url(path: str, page_size: int | None) -> str:+ url = f"{NETLIFY_BASE_URL}{path}"+ if page_size is not None:+ return f"{url}?{urlencode({'per_page': page_size})}"+ return url+++def _iter_pages(+ session: requests.Session,+ url: str,+ headers: dict[str, str],+ logger: FilteringBoundLogger,+ max_pages: int | None = None,+ page_cap_context: dict[str, Any] | None = None,+) -> Iterator[tuple[list[dict[str, Any]], str]]:+ """Yield (items, page_url) for each page of a Netlify list, following the Link header.++ Netlify list responses are top-level JSON arrays. When `max_pages` is set and there are still+ more pages, it raises rather than truncating: a silently short full-refresh table would stay+ incomplete on every later run, so we surface the cap as a hard failure instead.+ """+ page_count = 0+ while True:+ response = _fetch_page(session, url, headers, logger)+ data = response.json()+ if not isinstance(data, list) or not data:+ return+ next_url = _parse_next_url(response.headers.get("Link", ""), url)+ yield data, url+ page_count += 1+ if not next_url:+ return+ if max_pages is not None and page_count >= max_pages:+ logger.error(+ "Netlify: per-parent page cap reached; failing to avoid an incomplete table",+ max_pages=max_pages,+ **(page_cap_context or {}),+ )+ raise NetlifyPageCapExceededError(+ f"Netlify: per-parent page cap of {max_pages} reached with more pages remaining; "+ f"raise max_pages_per_parent to sync this parent fully. context={page_cap_context or {}}"+ )+ url = next_url+++def _redact_key(row: dict[str, Any], dotted_key: str) -> dict[str, Any]:+ """Return `row` with a possibly-nested field removed. `"password"` drops a top-level field;+ `"default_hooks_data.access_token"` walks into `default_hooks_data` and drops its `access_token`.+ Only the nodes on the path are copied, so the upstream item is left unmodified; a missing or+ non-dict node is a no-op."""+ head, _, rest = dotted_key.partition(".")+ if head not in row:+ return row+ if not rest:+ return {key: value for key, value in row.items() if key != head}+ nested = row[head]+ if not isinstance(nested, dict):+ return row+ return {**row, head: _redact_key(nested, rest)}+++def _redact_rows(rows: list[dict[str, Any]], redact_keys: list[str]) -> list[dict[str, Any]]:+ """Drop each configured (possibly-nested) credential field from every row before it's persisted,+ so account secrets in the API response never land in a queryable warehouse table."""+ if not redact_keys:+ return rows+ redacted: list[dict[str, Any]] = []+ for row in rows:+ if isinstance(row, dict):+ for key in redact_keys:+ row = _redact_key(row, key)+ redacted.append(row)+ return redacted+++def _make_parent_field_injector(+ parent: dict[str, Any], field_map: dict[str, str]+) -> Callable[[dict[str, Any]], dict[str, Any]]:+ """Copy the mapped parent fields onto each child row (e.g. the site id onto a build).++ Direct access on the parent fields: the injected columns feed the child's composite primary key,+ so a parent missing one is a broken response that must fail loudly, not corrupt the key with None.+ """+ injected = {child_column: parent[parent_field] for parent_field, child_column in field_map.items()}++ def inject(item: dict[str, Any]) -> dict[str, Any]:+ return {**item, **injected}++ return inject+++def _get_fan_out_rows(+ session: requests.Session,+ headers: dict[str, str],+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[NetlifyResumeConfig],+ config: NetlifyEndpointConfig,+) -> Iterator[list[dict[str, Any]]]:+ """Walk the parent list and emit every child row per parent, checkpointing the parent page URL.++ On resume we re-fan the current parent page from the saved URL and merge dedupes on the composite+ primary key. Full refresh means there's no watermark to advance — we just walk every parent.+ """+ assert config.fan_out_parent is not None and config.fan_out_path_param is not None+ parent_config = NETLIFY_ENDPOINTS[config.fan_out_parent]++ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None+ if resume is not None and resume.next_url:+ parent_url = _validate_netlify_url(resume.next_url)+ logger.debug(f"Netlify: resuming {config.name} fan-out from parent URL: {parent_url}")+ else:+ parent_url = _build_url(parent_config.path, parent_config.page_size)++ for parents, parent_page_url in _iter_pages(session, parent_url, headers, logger):+ for parent in parents:+ parent_value = parent[config.fan_out_parent_field]+ inject = (+ _make_parent_field_injector(parent, config.fan_out_include_parent_fields)+ if config.fan_out_include_parent_fields+ else None+ )+ child_path = config.path.format(**{config.fan_out_path_param: parent_value})+ child_url = _build_url(child_path, config.page_size)+ for child_items, _child_page_url in _iter_pages(+ session,+ child_url,+ headers,+ logger,+ max_pages=config.max_pages_per_parent,+ page_cap_context={config.fan_out_path_param: parent_value},+ ):+ rows = [inject(item) for item in child_items] if inject else child_items+ yield _redact_rows(rows, config.redact_keys)+ # Checkpoint after finishing a parent page so a crash re-fans this page rather than skipping+ # ahead. Save AFTER yielding this page's children; resume re-fans and merge dedupes.+ resumable_source_manager.save_state(NetlifyResumeConfig(next_url=parent_page_url))+++def get_rows(+ api_token: str,+ endpoint: str,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[NetlifyResumeConfig],+) -> Iterator[list[dict[str, Any]]]:+ config = NETLIFY_ENDPOINTS[endpoint]+ headers = _get_headers(api_token)+ # One session reused across every page (and, for fan-out, every parent) so urllib3 keeps the+ # connection alive instead of re-handshaking per request. Redact the token so the tracked+ # adapter never persists it in logged URLs or captured request/response samples.+ session = make_tracked_session(redact_values=(api_token,))++ if config.fan_out_parent is not None:+ yield from _get_fan_out_rows(session, headers, logger, resumable_source_manager, config)+ return++ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None+ if resume is not None and resume.next_url:+ url = _validate_netlify_url(resume.next_url)+ logger.debug(f"Netlify: resuming {endpoint} from URL: {url}")+ else:+ url = _build_url(config.path, config.page_size)++ while True:+ response = _fetch_page(session, url, headers, logger)+ data = response.json()+ if not isinstance(data, list) or not data:+ break+ next_url = _parse_next_url(response.headers.get("Link", ""), url)+ yield _redact_rows(data, config.redact_keys)+ if not next_url:+ break+ # Save AFTER yielding so a crash re-yields the last page rather than skipping it (merge+ # dedupes on the primary key). next_url is the next page to fetch on resume.+ resumable_source_manager.save_state(NetlifyResumeConfig(next_url=next_url))+ url = next_url+++def validate_credentials(api_token: str) -> bool:+ """Probe the token with a cheap single-row /sites request. Netlify personal access tokens have+ full account access (no granular scopes), so one authenticated call confirms the whole token."""+ url = _build_url("/sites", page_size=1)+ try:+ response = make_tracked_session(redact_values=(api_token,)).get(+ url, headers=_get_headers(api_token), timeout=10+ )+ return response.status_code == 200+ except Exception:+ return False+++def netlify_source(+ api_token: str,+ endpoint: str,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[NetlifyResumeConfig],+) -> SourceResponse:+ endpoint_config = NETLIFY_ENDPOINTS[endpoint]++ return SourceResponse(+ name=endpoint,+ items=lambda: get_rows(+ api_token=api_token,+ endpoint=endpoint,+ logger=logger,+ resumable_source_manager=resumable_source_manager,+ ),+ primary_keys=endpoint_config.primary_keys,+ sort_mode=endpoint_config.sort_mode,+ partition_count=1,+ partition_size=1,+ partition_mode="datetime" if endpoint_config.partition_key else None,+ partition_format="month" if endpoint_config.partition_key else None,+ partition_keys=[endpoint_config.partition_key] if endpoint_config.partition_key else None,+ )diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/netlify/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/netlify/settings.pynew file mode 100644index 000000000000..2e51be135491--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/netlify/settings.py@@ -0,0 +1,132 @@+from dataclasses import dataclass, field+from typing import Literal, Optional++from products.warehouse_sources.backend.types import IncrementalField++# Netlify exposes no server-side timestamp filter on any list endpoint (no `since` / `updated_after`+# / `created_gte` param filters the results — they're documented but silently ignored, or absent),+# so every table is full refresh. There is no reliable server-side cursor to sync incrementally on.+# `INCREMENTAL_FIELDS` is therefore empty for all endpoints; see the module docstring in netlify.py.+++@dataclass+class NetlifyEndpointConfig:+ name: str+ # Path template appended to the API base. Fan-out children carry a placeholder filled from the+ # parent: {site_id} for site-scoped tables, {account_slug} for account-scoped tables.+ path: str+ # Primary key columns for upsert dedup. Fan-out children key on the parent identifier too so the+ # key stays unique table-wide (a build/submission id is only guaranteed unique within its site).+ primary_keys: list[str] = field(default_factory=lambda: ["id"])+ # Stable creation-time field to partition by. Never a mutable field (`updated_at`) — partitions+ # must not rewrite on every sync. None for tables the API returns without a timestamp (members).+ partition_key: Optional[str] = None+ # Send `per_page` on the request when set. None for endpoints that document no page/per_page+ # params (forms, dns_zones, accounts, members return a single unpaginated list).+ page_size: Optional[int] = 100+ # Order rows actually arrive in, so SourceResponse.sort_mode reflects reality. Netlify returns+ # deploys/builds/submissions newest-first; the small full-refresh lists are creation-ordered.+ # All tables are full refresh, so this doesn't drive an incremental watermark — it just stays honest.+ sort_mode: Literal["asc", "desc"] = "asc"+ should_sync_default: bool = True+ # Fan-out: the parent endpoint whose rows seed this child's path.+ fan_out_parent: Optional[str] = None+ # Path placeholder filled from the parent (e.g. "site_id") and the parent field read for it.+ fan_out_path_param: Optional[str] = None+ fan_out_parent_field: str = "id"+ # Parent fields copied onto each child row, mapped parent_field -> child_column. Gives fan-out+ # children the parent context their own API response omits (a build/submission carries no site_id).+ fan_out_include_parent_fields: Optional[dict[str, str]] = None+ # Hard cap on pages fetched per parent in a fan-out, bounding a runaway paginator. Logged on hit.+ max_pages_per_parent: int = 100+ # Credential-bearing fields dropped from every row before it's persisted, so they never land in+ # a queryable warehouse table. Dotted paths reach nested objects (e.g. `default_hooks_data.access_token`);+ # a bare name targets a top-level field. A missing key is a no-op.+ redact_keys: list[str] = field(default_factory=list)+++NETLIFY_ENDPOINTS: dict[str, NetlifyEndpointConfig] = {+ "sites": NetlifyEndpointConfig(+ name="sites",+ path="/sites",+ partition_key="created_at",+ # A site object carries account credentials a warehouse user shouldn't read: the site's+ # basic-auth `password`, the `default_hooks_data.access_token`, and the build-time+ # environment variables under `build_settings.env` (which routinely hold API secrets).+ redact_keys=["password", "default_hooks_data.access_token", "build_settings.env"],+ ),+ "deploys": NetlifyEndpointConfig(+ name="deploys",+ path="/sites/{site_id}/deploys",+ # Deploy ids are globally unique, but the composite key keeps us safe if that ever changes+ # and matches how the other site-scoped children key. The deploy already carries site_id;+ # injecting the parent's id under the same column is idempotent.+ primary_keys=["site_id", "id"],+ partition_key="created_at",+ sort_mode="desc", # newest-first+ fan_out_parent="sites",+ fan_out_path_param="site_id",+ fan_out_include_parent_fields={"id": "site_id"},+ ),+ "builds": NetlifyEndpointConfig(+ name="builds",+ path="/sites/{site_id}/builds",+ # A build row carries no site_id of its own, so inject the parent site id and key on it.+ primary_keys=["site_id", "id"],+ partition_key="created_at",+ sort_mode="desc", # newest-first+ fan_out_parent="sites",+ fan_out_path_param="site_id",+ fan_out_include_parent_fields={"id": "site_id"},+ ),+ "forms": NetlifyEndpointConfig(+ name="forms",+ path="/sites/{site_id}/forms",+ primary_keys=["site_id", "id"],+ partition_key="created_at",+ page_size=None, # no page/per_page params; a site has few forms+ fan_out_parent="sites",+ fan_out_path_param="site_id",+ fan_out_include_parent_fields={"id": "site_id"},+ ),+ "submissions": NetlifyEndpointConfig(+ name="submissions",+ path="/sites/{site_id}/submissions",+ # Submission rows carry no site_id, so inject the parent site id and key on it.+ primary_keys=["site_id", "id"],+ partition_key="created_at",+ sort_mode="desc", # newest-first+ fan_out_parent="sites",+ fan_out_path_param="site_id",+ fan_out_include_parent_fields={"id": "site_id"},+ ),+ "dns_zones": NetlifyEndpointConfig(+ name="dns_zones",+ path="/dns_zones",+ partition_key="created_at",+ page_size=None,+ ),+ "accounts": NetlifyEndpointConfig(+ name="accounts",+ path="/accounts",+ partition_key="created_at",+ page_size=None,+ ),+ "members": NetlifyEndpointConfig(+ name="members",+ path="/{account_slug}/members",+ # A member row is a plain user with an id that can recur across accounts, so key on the+ # account too; the account_slug has no member timestamp so this table isn't partitioned.+ primary_keys=["account_slug", "id"],+ page_size=None,+ fan_out_parent="accounts",+ fan_out_path_param="account_slug",+ fan_out_parent_field="slug",+ fan_out_include_parent_fields={"slug": "account_slug"},+ ),+}++ENDPOINTS = tuple(NETLIFY_ENDPOINTS.keys())++# Every endpoint is full refresh: Netlify has no server-side timestamp filter to sync incrementally on.+INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {name: [] for name in NETLIFY_ENDPOINTS}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/netlify/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/netlify/source.pyindex 269417d8b80e..1a80fe2087dd 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/netlify/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/netlify/source.py@@ -1,19 +1,43 @@-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 SourceSchemafrom products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs import NetlifySourceConfig+from products.warehouse_sources.backend.temporal.data_imports.sources.netlify.netlify import (+ NetlifyResumeConfig,+ netlify_source,+ validate_credentials as validate_netlify_credentials,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.netlify.settings import (+ ENDPOINTS,+ INCREMENTAL_FIELDS,+ NETLIFY_ENDPOINTS,+)from products.warehouse_sources.backend.types import ExternalDataSourceType@SourceRegistry.register-class NetlifySource(SimpleSource[NetlifySourceConfig]):+class NetlifySource(ResumableSource[NetlifySourceConfig, NetlifyResumeConfig]):+ lists_tables_without_credentials = True # static endpoint catalog — safe for public docs+@propertydef source_type(self) -> ExternalDataSourceType:return ExternalDataSourceType.NETLIFY@@ -24,8 +48,90 @@ class NetlifySource(SimpleSource[NetlifySourceConfig]):name=SchemaExternalDataSourceType.NETLIFY,category=DataWarehouseSourceCategory.ENGINEERING___MONITORING,label="Netlify",- iconPath="/static/services/netlify.png",- keywords=["hosting", "jamstack", "deploys", "web"],- fields=cast(list[FieldType], []),+ releaseStatus=ReleaseStatus.ALPHA,unreleasedSource=True,+ caption="""Enter your Netlify personal access token to sync your Netlify data into the PostHog Data warehouse.++Create a personal access token under **User settings > Applications > Personal access tokens** in the [Netlify UI](https://app.netlify.com/user/applications). The token has full access to the resources your account can reach, so no extra scopes are needed.+""",+ iconPath="/static/services/netlify.svg",+ docsUrl="https://posthog.com/docs/cdp/sources/netlify",+ keywords=["hosting", "jamstack", "deploys", "web"],+ fields=cast(+ list[FieldType],+ [+ SourceFieldInputConfig(+ name="api_token",+ label="Personal access token",+ type=SourceFieldInputConfigType.PASSWORD,+ required=True,+ placeholder="nfp_...",+ secret=True,+ ),+ ],+ ),+ )++ def get_canonical_descriptions(self) -> CanonicalDescriptions:+ from products.warehouse_sources.backend.temporal.data_imports.sources.netlify.canonical_descriptions import (+ CANONICAL_DESCRIPTIONS,+ )++ return CANONICAL_DESCRIPTIONS++ def get_non_retryable_errors(self) -> dict[str, str | None]:+ return {+ # An invalid or revoked token surfaces as a requests HTTPError when `_fetch_page` calls+ # `raise_for_status()`. Retrying can never satisfy a credential problem, so stop the sync.+ # Match the stable status text and base host, not the per-request path/query.+ "401 Client Error: Unauthorized for url: https://api.netlify.com": "Your Netlify personal access token is invalid or has been revoked. Netlify invalidates tokens on password reset. Create a new token in your Netlify user settings, then reconnect.",+ "403 Client Error: Forbidden for url: https://api.netlify.com": "Your Netlify personal access token does not have access to this resource. Create a token with the required access, then reconnect.",+ }++ def get_schemas(+ self,+ config: NetlifySourceConfig,+ team_id: int,+ with_counts: bool = False,+ names: list[str] | None = None,+ force_refresh: bool = False,+ ) -> list[SourceSchema]:+ # Netlify exposes no server-side timestamp filter, so every table is full refresh.+ schemas = [+ SourceSchema(+ name=endpoint,+ supports_incremental=False,+ supports_append=False,+ incremental_fields=INCREMENTAL_FIELDS.get(endpoint, []),+ should_sync_default=NETLIFY_ENDPOINTS[endpoint].should_sync_default,+ )+ 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: NetlifySourceConfig, team_id: int, schema_name: Optional[str] = None+ ) -> tuple[bool, str | None]:+ if validate_netlify_credentials(config.api_token):+ return True, None++ return False, "Invalid Netlify personal access token"++ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[NetlifyResumeConfig]:+ return ResumableSourceManager[NetlifyResumeConfig](inputs, NetlifyResumeConfig)++ def source_for_pipeline(+ self,+ config: NetlifySourceConfig,+ resumable_source_manager: ResumableSourceManager[NetlifyResumeConfig],+ inputs: SourceInputs,+ ) -> SourceResponse:+ return netlify_source(+ api_token=config.api_token,+ endpoint=inputs.schema_name,+ logger=inputs.logger,+ resumable_source_manager=resumable_source_manager,)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/netlify/tests/test_netlify.py b/products/warehouse_sources/backend/temporal/data_imports/sources/netlify/tests/test_netlify.pynew file mode 100644index 000000000000..ff0a6d11afc6--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/netlify/tests/test_netlify.py@@ -0,0 +1,262 @@+from typing import Any++import pytest+from unittest import mock++import requests+from parameterized import parameterized++from products.warehouse_sources.backend.temporal.data_imports.sources.netlify import netlify+from products.warehouse_sources.backend.temporal.data_imports.sources.netlify.netlify import (+ NetlifyResumeConfig,+ _build_url,+ _make_parent_field_injector,+ _parse_next_url,+ get_rows,+ netlify_source,+ validate_credentials,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.netlify.settings import NETLIFY_ENDPOINTS++BASE = "https://api.netlify.com/api/v1"+++def _resp(data: Any, next_url: str | None = None, status: int = 200) -> mock.Mock:+ response = mock.Mock(spec=requests.Response)+ response.status_code = status+ response.ok = status < 400+ response.text = ""+ response.json.return_value = data+ response.headers = {"Link": f'<{next_url}>; rel="next"'} if next_url else {}+ return response+++def _manager(resume: NetlifyResumeConfig | None = None) -> mock.Mock:+ manager = mock.Mock()+ manager.can_resume.return_value = resume is not None+ manager.load_state.return_value = resume+ return manager+++class TestParseNextUrl:+ @parameterized.expand(+ [+ ("no_header", "", None),+ (+ "next_only",+ f'<{BASE}/sites?page=2&per_page=100>; rel="next"',+ f"{BASE}/sites?page=2&per_page=100",+ ),+ (+ "next_and_last",+ f'<{BASE}/sites?page=2>; rel="next", <{BASE}/sites?page=9>; rel="last"',+ f"{BASE}/sites?page=2",+ ),+ (+ "prev_and_last_no_next",+ f'<{BASE}/sites?page=1>; rel="prev", <{BASE}/sites?page=9>; rel="last"',+ None,+ ),+ ]+ )+ def test_parse_next_url(self, _name: str, header: str, expected: str | None) -> None:+ assert _parse_next_url(header) == expected++ def test_resolves_relative_next_url(self) -> None:+ assert _parse_next_url('</api/v1/sites?page=2>; rel="next"') == f"{BASE}/sites?page=2"++ @parameterized.expand(+ [+ ("off_host", "https://evil.example.com/api/v1/sites?page=2"),+ ("http_scheme", "http://api.netlify.com/api/v1/sites?page=2"),+ ]+ )+ def test_rejects_untrusted_next_url(self, _name: str, target: str) -> None:+ with pytest.raises(netlify.NetlifyUntrustedURLError):+ _parse_next_url(f'<{target}>; rel="next"')+++class TestBuildUrl:+ def test_with_page_size(self) -> None:+ assert _build_url("/sites", 100) == f"{BASE}/sites?per_page=100"++ def test_without_page_size(self) -> None:+ assert _build_url("/accounts", None) == f"{BASE}/accounts"+++class TestParentFieldInjector:+ def test_injects_mapped_parent_fields(self) -> None:+ inject = _make_parent_field_injector({"id": "site-1", "slug": "acme"}, {"id": "site_id"})+ assert inject({"id": "build-1"}) == {"id": "build-1", "site_id": "site-1"}++ def test_missing_parent_field_raises(self) -> None:+ # The injected column feeds the child's composite primary key, so a parent missing it must+ # fail loudly rather than silently write a None into the key.+ with pytest.raises(KeyError):+ _make_parent_field_injector({"slug": "acme"}, {"id": "site_id"})+++class TestGetRowsTopLevel:+ def test_paginates_and_checkpoints_after_each_page(self) -> None:+ manager = _manager()+ session = mock.Mock()+ session.get.side_effect = [+ _resp([{"id": "a"}], next_url=f"{BASE}/sites?page=2&per_page=100"),+ _resp([{"id": "b"}], next_url=None),+ ]+ with mock.patch.object(netlify, "make_tracked_session", return_value=session):+ batches = list(get_rows("tok", "sites", mock.Mock(), manager))++ assert batches == [[{"id": "a"}], [{"id": "b"}]]+ # State saved once — after the first page, pointing at the second. The last page has no+ # next link, so nothing is saved for it.+ manager.save_state.assert_called_once_with(NetlifyResumeConfig(next_url=f"{BASE}/sites?page=2&per_page=100"))++ def test_resumes_from_saved_url(self) -> None:+ resume_url = f"{BASE}/sites?page=3&per_page=100"+ manager = _manager(NetlifyResumeConfig(next_url=resume_url))+ session = mock.Mock()+ session.get.side_effect = [_resp([{"id": "c"}], next_url=None)]+ with mock.patch.object(netlify, "make_tracked_session", return_value=session):+ batches = list(get_rows("tok", "sites", mock.Mock(), manager))++ assert batches == [[{"id": "c"}]]+ assert session.get.call_args_list[0].args[0] == resume_url++ def test_strips_credential_fields_from_sites(self) -> None:+ # A site object carries account credentials that must never reach the queryable table.+ manager = _manager()+ session = mock.Mock()+ site = {+ "id": "s1",+ "name": "acme",+ "password": "hunter2",+ "default_hooks_data": {"access_token": "secret-token", "type": "github"},+ "build_settings": {"env": {"STRIPE_KEY": "sk_live_x"}, "cmd": "build"},+ }+ session.get.side_effect = [_resp([site], next_url=None)]+ with mock.patch.object(netlify, "make_tracked_session", return_value=session):+ batches = list(get_rows("tok", "sites", mock.Mock(), manager))++ assert batches == [+ [+ {+ "id": "s1",+ "name": "acme",+ "default_hooks_data": {"type": "github"},+ "build_settings": {"cmd": "build"},+ }+ ]+ ]++ def test_empty_first_page_yields_nothing(self) -> None:+ manager = _manager()+ session = mock.Mock()+ session.get.side_effect = [_resp([])]+ with mock.patch.object(netlify, "make_tracked_session", return_value=session):+ batches = list(get_rows("tok", "sites", mock.Mock(), manager))++ assert batches == []+ manager.save_state.assert_not_called()+++class TestGetRowsFanOut:+ def test_injects_parent_site_id_and_checkpoints_parent_page(self) -> None:+ manager = _manager()+ session = mock.Mock()++ def get(url: str, **_kwargs: Any) -> mock.Mock:+ if url == f"{BASE}/sites?per_page=100":+ return _resp([{"id": "s1"}], next_url=None)+ if url == f"{BASE}/sites/s1/builds?per_page=100":+ return _resp([{"id": "b1"}], next_url=None)+ raise AssertionError(f"unexpected url: {url}")++ session.get.side_effect = get+ with mock.patch.object(netlify, "make_tracked_session", return_value=session):+ batches = list(get_rows("tok", "builds", mock.Mock(), manager))++ # site_id is injected onto each build row (a build carries no site_id of its own).+ assert batches == [[{"id": "b1", "site_id": "s1"}]]+ manager.save_state.assert_called_once_with(NetlifyResumeConfig(next_url=f"{BASE}/sites?per_page=100"))++ def test_members_fan_out_reads_parent_slug(self) -> None:+ manager = _manager()+ session = mock.Mock()++ def get(url: str, **_kwargs: Any) -> mock.Mock:+ if url == f"{BASE}/accounts":+ return _resp([{"id": "acc-1", "slug": "acme"}], next_url=None)+ if url == f"{BASE}/acme/members":+ return _resp([{"id": "u1", "email": "[email protected]"}], next_url=None)+ raise AssertionError(f"unexpected url: {url}")++ session.get.side_effect = get+ with mock.patch.object(netlify, "make_tracked_session", return_value=session):+ batches = list(get_rows("tok", "members", mock.Mock(), manager))++ # Members fan out over accounts keyed by the account slug, injected as account_slug.+ assert batches == [[{"id": "u1", "email": "[email protected]", "account_slug": "acme"}]]+++class TestIterPagesCap:+ def test_raises_at_max_pages(self) -> None:+ session = mock.Mock()+ # Always advertise a next page so only max_pages bounds the walk. Hitting the cap must fail+ # loudly rather than silently truncate the full-refresh table.+ session.get.return_value = _resp([{"id": "x"}], next_url=f"{BASE}/sites/s1/builds?page=99")+ with pytest.raises(netlify.NetlifyPageCapExceededError):+ list(+ netlify._iter_pages(+ session, f"{BASE}/sites/s1/builds", {}, mock.Mock(), max_pages=2, page_cap_context={"site_id": "s1"}+ )+ )+++class TestFetchPage:+ def test_returns_ok_response(self) -> None:+ session = mock.Mock()+ session.get.return_value = _resp([{"id": "a"}])+ assert netlify._fetch_page(session, f"{BASE}/sites", {}, mock.Mock()).status_code == 200++ def test_raises_on_client_error(self) -> None:+ session = mock.Mock()+ response = _resp({"code": 401, "message": "Access Denied"}, status=401)+ response.raise_for_status.side_effect = requests.HTTPError("401 Client Error", response=response)+ session.get.return_value = response+ with pytest.raises(requests.HTTPError):+ netlify._fetch_page(session, f"{BASE}/sites", {}, mock.Mock())+++class TestValidateCredentials:+ @parameterized.expand([("ok", 200, True), ("unauthorized", 401, False), ("forbidden", 403, False)])+ def test_status_mapping(self, _name: str, status: int, expected: bool) -> None:+ session = mock.Mock()+ response = mock.Mock(status_code=status)+ session.get.return_value = response+ with mock.patch.object(netlify, "make_tracked_session", return_value=session):+ assert validate_credentials("tok") is expected++ def test_exception_is_false(self) -> None:+ session = mock.Mock()+ session.get.side_effect = requests.ConnectionError()+ with mock.patch.object(netlify, "make_tracked_session", return_value=session):+ assert validate_credentials("tok") is False+++class TestNetlifySourceResponse:+ @parameterized.expand(list(NETLIFY_ENDPOINTS.keys()))+ def test_source_response_matches_endpoint_config(self, endpoint: str) -> None:+ config = NETLIFY_ENDPOINTS[endpoint]+ response = netlify_source("tok", endpoint, mock.Mock(), _manager())++ assert response.name == endpoint+ assert response.primary_keys == config.primary_keys+ assert response.sort_mode == config.sort_mode+ # Partition config is present only for endpoints with a stable creation-time field.+ if config.partition_key:+ assert response.partition_mode == "datetime"+ assert response.partition_keys == [config.partition_key]+ else:+ assert response.partition_mode is None+ assert response.partition_keys is Nonediff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/netlify/tests/test_netlify_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/netlify/tests/test_netlify_source.pynew file mode 100644index 000000000000..6cddc61254d3--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/netlify/tests/test_netlify_source.py@@ -0,0 +1,100 @@+from unittest import mock++from posthog.schema import (+ DataWarehouseSourceCategory,+ ReleaseStatus,+ SourceFieldInputConfig,+ SourceFieldInputConfigType,+)++from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from products.warehouse_sources.backend.temporal.data_imports.sources.netlify import source as source_module+from products.warehouse_sources.backend.temporal.data_imports.sources.netlify.netlify import NetlifyResumeConfig+from products.warehouse_sources.backend.temporal.data_imports.sources.netlify.settings import ENDPOINTS+from products.warehouse_sources.backend.temporal.data_imports.sources.netlify.source import NetlifySource+from products.warehouse_sources.backend.types import ExternalDataSourceType+++class TestNetlifySourceConfig:+ def test_source_type(self) -> None:+ assert NetlifySource().source_type == ExternalDataSourceType.NETLIFY++ def test_source_config_shape(self) -> None:+ config = NetlifySource().get_source_config+ assert config.category == DataWarehouseSourceCategory.ENGINEERING___MONITORING+ assert config.releaseStatus == ReleaseStatus.ALPHA+ assert config.unreleasedSource is True+ assert config.docsUrl == "https://posthog.com/docs/cdp/sources/netlify"++ def test_single_password_token_field(self) -> None:+ fields = NetlifySource().get_source_config.fields+ assert len(fields) == 1+ field = fields[0]+ assert isinstance(field, SourceFieldInputConfig)+ assert field.name == "api_token"+ assert field.type == SourceFieldInputConfigType.PASSWORD+ assert field.required is True+ assert field.secret is True+++class TestNetlifyGetSchemas:+ def test_all_endpoints_full_refresh(self) -> None:+ schemas = NetlifySource().get_schemas(mock.Mock(), team_id=1)+ assert {s.name for s in schemas} == set(ENDPOINTS)+ # Netlify has no server-side timestamp filter, so no table supports incremental/append.+ assert all(not s.supports_incremental and not s.supports_append for s in schemas)+ assert all(s.incremental_fields == [] for s in schemas)++ def test_names_filter(self) -> None:+ schemas = NetlifySource().get_schemas(mock.Mock(), team_id=1, names=["sites", "deploys"])+ assert {s.name for s in schemas} == {"sites", "deploys"}+++class TestNetlifyValidateCredentials:+ def test_success(self) -> None:+ with mock.patch.object(source_module, "validate_netlify_credentials", return_value=True):+ assert NetlifySource().validate_credentials(mock.Mock(), team_id=1) == (True, None)++ def test_failure(self) -> None:+ with mock.patch.object(source_module, "validate_netlify_credentials", return_value=False):+ ok, error = NetlifySource().validate_credentials(mock.Mock(), team_id=1)+ assert ok is False+ assert error is not None+++class TestNetlifyNonRetryableErrors:+ def test_auth_errors_present(self) -> None:+ errors = NetlifySource().get_non_retryable_errors()+ assert any(key.startswith("401 Client Error") for key in errors)+ assert any(key.startswith("403 Client Error") for key in errors)+++class TestNetlifyCanonicalDescriptions:+ def test_covers_every_endpoint(self) -> None:+ descriptions = NetlifySource().get_canonical_descriptions()+ assert set(descriptions.keys()) == set(ENDPOINTS)+++class TestNetlifyResumableWiring:+ def test_resumable_manager_bound_to_resume_config(self) -> None:+ inputs = mock.Mock()+ inputs.logger = mock.Mock()+ manager = NetlifySource().get_resumable_source_manager(inputs)+ assert isinstance(manager, ResumableSourceManager)+ assert manager._data_class is NetlifyResumeConfig++ def test_source_for_pipeline_plumbs_arguments(self) -> None:+ config = mock.Mock(api_token="nfp_secret")+ inputs = mock.Mock(schema_name="deploys")+ inputs.logger = mock.Mock()+ manager = mock.Mock()++ with mock.patch.object(source_module, "netlify_source") as netlify_source_mock:+ NetlifySource().source_for_pipeline(config, manager, inputs)++ netlify_source_mock.assert_called_once_with(+ api_token="nfp_secret",+ endpoint="deploys",+ logger=inputs.logger,+ resumable_source_manager=manager,+ )