: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 deno_deploy import source (#70030)
Tom Owers635db370a9d0
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.mdindex c90154ed7c0d..62333eadd9e8 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md@@ -137,6 +137,7 @@ the row lists both.| deel | HTTP | requests | ✅ || deepgram | HTTP | requests | ✅ || delighted | HTTP | requests | ✅ |+| deno_deploy | HTTP | requests | ✅ || devin_ai | HTTP | requests | ✅ || ding_connect | HTTP | requests | ✅ || dixa | HTTP | requests | ✅ |diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/deno_deploy/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/deno_deploy/canonical_descriptions.pynew file mode 100644index 000000000000..eaf304c9714f--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/deno_deploy/canonical_descriptions.py@@ -0,0 +1,92 @@+"""Canonical, documentation-sourced descriptions for Deno Deploy endpoints and columns.++Sourced from the official Deno Deploy v2 API reference (https://docs.deno.com/deploy/api/ and the+OpenAPI spec at https://api.deno.com/v2/openapi.json). Keyed by the endpoint names in `settings.py`+`DENO_DEPLOY_ENDPOINTS`, which match the `ExternalDataSchema.name` of a synced 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 = {+ "apps": {+ "description": "A Deno Deploy application: a web service that serves traffic within the organization, identified by a unique slug.",+ "docs_url": "https://docs.deno.com/deploy/reference/apps/",+ "columns": {+ "id": "Unique identifier (UUID) for the app.",+ "slug": "Human-readable slug, unique within the organization and used in default domain names.",+ "labels": "Key/value labels attached to the app.",+ "layers": "Shared configuration layers applied to the app.",+ "created_at": "Time at which the app was created.",+ "updated_at": "Time at which the app was last updated.",+ },+ },+ "revisions": {+ "description": "A single version (build) of an app's code. When deploying from GitHub, revisions generally map one-to-one to git commits.",+ "docs_url": "https://docs.deno.com/deploy/reference/builds/",+ "columns": {+ "id": "Unique identifier for the revision.",+ "app_id": "Identifier of the app this revision belongs to (added by PostHog when fanning out over apps).",+ "app_slug": "Slug of the app this revision belongs to (added by PostHog).",+ "status": "Current build/deployment status of the revision.",+ "failure_reason": "Why the build failed, if it did (error, cancelled, timed_out, or skipped).",+ "labels": "Key/value labels attached to the revision.",+ "created_at": "Time at which the revision was created.",+ "cancellation_requested_at": "Time at which cancellation was requested, if any.",+ "build_finished_at": "Time at which the build finished, if it has.",+ "deleted_at": "Time at which the revision was deleted, if it has been.",+ },+ },+ "domains": {+ "description": "A custom domain mapped to the organization's deployments, with its verification and TLS certificate state.",+ "docs_url": "https://docs.deno.com/deploy/reference/domains/",+ "columns": {+ "id": "Unique identifier for the domain.",+ "organization_id": "Identifier of the organization that owns the domain.",+ "domain": "The custom domain name (e.g. mycompany.com).",+ "kind": "The kind of domain mapping.",+ "verification_token": "Token used to verify ownership of the domain.",+ "is_validated": "Whether ownership of the domain has been validated.",+ "dns_records": "DNS records that must be configured for the domain.",+ "provisioning_status": "Status of TLS certificate provisioning for the domain.",+ "certificates": "TLS certificates provisioned or uploaded for the domain.",+ "created_at": "Time at which the domain was added.",+ "updated_at": "Time at which the domain was last updated.",+ },+ },+ "analytics": {+ "description": "Per-app usage metrics in 15-minute buckets (request count, CPU, bandwidth, KV units), reshaped from the columnar API response into one row per time bucket.",+ "docs_url": "https://docs.deno.com/deploy/api/",+ "columns": {+ "app_id": "Identifier of the app the metrics belong to (added by PostHog when fanning out over apps).",+ "app_slug": "Slug of the app the metrics belong to (added by PostHog).",+ "time": "Start of the 15-minute analytics bucket.",+ "request_count": "Number of requests served in the bucket.",+ "cpu_seconds": "CPU time consumed in the bucket, in seconds.",+ "runtime_seconds": "Wall-clock runtime in the bucket, in seconds.",+ "memory_time_byte_seconds": "Memory usage integrated over time (byte-seconds) in the bucket.",+ "network_ingress_bytes": "Inbound network bytes in the bucket.",+ "network_egress_bytes": "Outbound network bytes in the bucket.",+ "kv_read_units": "Deno KV read units consumed in the bucket.",+ "kv_write_units": "Deno KV write units consumed in the bucket.",+ },+ },+ "logs": {+ "description": "Runtime log lines emitted by an app over a time window. Each row is given a synthesized content-hash id since Deno Deploy runtime logs carry no natural identifier.",+ "docs_url": "https://docs.deno.com/deploy/api/",+ "columns": {+ "id": "Synthesized content-hash identifier (added by PostHog so log lines can be deduplicated on re-sync).",+ "app_id": "Identifier of the app that emitted the log (added by PostHog when fanning out over apps).",+ "app_slug": "Slug of the app that emitted the log (added by PostHog).",+ "timestamp": "Time at which the log line was emitted.",+ "level": "Severity level of the log line.",+ "message": "The log message text.",+ "revision_id": "Identifier of the revision that emitted the log.",+ "region": "Edge region the log was emitted from.",+ "trace_id": "Trace identifier for the request that emitted the log, if any.",+ "span_id": "Span identifier for the request that emitted the log, if any.",+ },+ },+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/deno_deploy/deno_deploy.py b/products/warehouse_sources/backend/temporal/data_imports/sources/deno_deploy/deno_deploy.pynew file mode 100644index 000000000000..75d6d40bb175--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/deno_deploy/deno_deploy.py@@ -0,0 +1,412 @@+import re+import hashlib+import dataclasses+from collections.abc import Iterator+from datetime import UTC, date, datetime, timedelta+from typing import Any, Optional+from urllib.parse import parse_qsl, urlencode, urlsplit, urlunsplit++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.deno_deploy.settings import (+ DENO_DEPLOY_ENDPOINTS,+ DenoDeployEndpointConfig,+)++DENO_DEPLOY_HOST = "api.deno.com"+DENO_DEPLOY_BASE_URL = f"https://{DENO_DEPLOY_HOST}"++# Default page size for the cursor-paginated list endpoints (API default is 30, max 100).+DEFAULT_LIST_PAGE_SIZE = 100+++class DenoDeployRetryableError(Exception):+ pass+++def _require_deno_deploy_url(url: str) -> str:+ """SSRF guard for every authenticated request. The bearer token is attached to whatever URL we+ fetch, and both pagination `Link` headers and persisted resume URLs are attacker-influenceable, so+ only accept HTTPS URLs whose host is exactly `api.deno.com` before the token can be forwarded."""+ try:+ parts = urlsplit(url)+ except ValueError as e:+ raise ValueError(f"Refusing to fetch malformed Deno Deploy URL: {e}")+ if parts.scheme != "https" or parts.hostname != DENO_DEPLOY_HOST:+ raise ValueError(f"Refusing to fetch off-host Deno Deploy URL (host={parts.hostname!r})")+ return url+++def _make_session(access_token: str) -> requests.Session:+ """A tracked session that (1) masks the bearer token in logged URLs and captured samples and+ (2) never follows redirects, so a tampered response can't bounce the `Authorization` header to an+ attacker-controlled host."""+ return make_tracked_session(redact_values=(access_token,), allow_redirects=False)+++class DenoDeployResumeConfig:+ # Full URL of the next page to fetch. None means "start this app's endpoint at its first page" —+ # used when the bookmark advances to a fan-out app whose first-page URL isn't known until built.+ next_url: str | None = None+ # The fan-out app currently being processed, as a stable app id (not a positional index) so apps+ # added/removed between a crash and the retry can't resume into the wrong app. None for the+ # top-level (non-fan-out) endpoints.+ app_id: str | None = None+++def _get_headers(access_token: str) -> dict[str, str]:+ return {+ "Authorization": f"Bearer {access_token}",+ "Accept": "application/json",+ }+++def _format_rfc3339(dt: datetime) -> str:+ """Format a datetime as RFC 3339 / ISO 8601 with a `Z` suffix, which Deno Deploy's time filters+ accept. isoformat() emits `+00:00`; we normalize to `Z` to match the API's documented examples."""+ utc_dt = dt.replace(tzinfo=UTC) if dt.tzinfo is None else dt.astimezone(UTC)+ return utc_dt.strftime("%Y-%m-%dT%H:%M:%S") + "Z"+++def _as_utc_datetime(value: Any) -> datetime | None:+ if isinstance(value, datetime):+ return value if value.tzinfo is not None else value.replace(tzinfo=UTC)+ if isinstance(value, date):+ return datetime.combine(value, datetime.min.time(), tzinfo=UTC)+ return None+++def _build_url(path: str, params: dict[str, Any]) -> str:+ if not params:+ return f"{DENO_DEPLOY_BASE_URL}{path}"+ return f"{DENO_DEPLOY_BASE_URL}{path}?{urlencode(params)}"+++def _parse_next_link(link_header: str) -> str | None:+ """Return the URL with rel="next" from Deno Deploy's Link header, if any.++ The header looks like: `Link: </v2/apps?cursor=eyJ...&limit=30>; rel="next"`. The URL may be+ relative to the API host, so resolve it against the base URL."""+ if not link_header:+ return None+ for part in link_header.split(","):+ match = re.search(r'<([^>]+)>;\s*rel="next"', part.strip())+ if match:+ url = match.group(1)+ if url.startswith("/"):+ return f"{DENO_DEPLOY_BASE_URL}{url}"+ return url+ return None+++@retry(+ retry=retry_if_exception_type(+ (+ DenoDeployRetryableError,+ 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:+ # Validate every URL at the single choke point where the token is attached: this covers freshly+ # built URLs, `Link`-header continuations, logs cursors, and persisted resume URLs alike.+ _require_deno_deploy_url(url)+ response = session.get(url, headers=headers, timeout=60)++ # Rate limits aren't documented in the spec; treat 429 and 5xx as transient and retry.+ if response.status_code == 429 or response.status_code >= 500:+ raise DenoDeployRetryableError(f"Deno Deploy API error (retryable): status={response.status_code}, url={url}")++ if not response.ok:+ logger.error(f"Deno Deploy API error: status={response.status_code}, body={response.text}, url={url}")+ response.raise_for_status()++ return response+++def validate_credentials(access_token: str) -> tuple[bool, str | None]:+ """Confirm the org access token is genuine with one cheap probe against the apps list."""+ url = _require_deno_deploy_url(_build_url("/v2/apps", {"limit": 1}))+ try:+ response = _make_session(access_token).get(url, headers=_get_headers(access_token), timeout=10)+ except requests.exceptions.RequestException as e:+ return False, str(e)++ if response.status_code == 200:+ return True, None+ if response.status_code == 401:+ return False, "Invalid Deno Deploy access token. Create a new organization access token and reconnect."+ if response.status_code == 403:+ return False, "Your Deno Deploy access token does not have permission to read this organization's data."++ try:+ message = response.json().get("message", response.text)+ except ValueError:+ message = response.text+ return False, message+++def _iter_app_refs(+ session: requests.Session, headers: dict[str, str], logger: FilteringBoundLogger+) -> Iterator[tuple[str, str]]:+ """Page through /v2/apps and yield each app's (id, slug), following the Link header cursor."""+ url: str | None = _build_url("/v2/apps", {"limit": DEFAULT_LIST_PAGE_SIZE})+ while url:+ response = _fetch(session, url, headers, logger)+ data = response.json()+ for app in data if isinstance(data, list) else []:+ yield app["id"], app.get("slug", "")+ url = _parse_next_link(response.headers.get("Link", ""))+++def _log_row_id(app_id: str, log: dict[str, Any]) -> str:+ """Runtime log lines carry no natural id, so synthesize a stable content hash. Merging on it makes+ re-pulling the overlapping boundary window idempotent (identical lines collapse to one row). Two+ genuinely distinct lines identical across every field would also collapse — an accepted, rare loss+ for a source without log ids."""+ parts = [+ app_id,+ str(log.get("timestamp", "")),+ str(log.get("level", "")),+ str(log.get("message", "")),+ str(log.get("revision_id", "")),+ str(log.get("region", "")),+ str(log.get("trace_id", "")),+ str(log.get("span_id", "")),+ ]+ return hashlib.sha256("|".join(parts).encode("utf-8")).hexdigest()+++def _shape_log(log: dict[str, Any], app_id: str, app_slug: str) -> dict[str, Any]:+ return {**log, "app_id": app_id, "app_slug": app_slug, "id": _log_row_id(app_id, log)}+++def _reshape_analytics(body: dict[str, Any], app_id: str, app_slug: str) -> list[dict[str, Any]]:+ """Deno returns analytics as a columnar {fields: [{name}], values: [[...], ...]} payload. Reshape+ it into one dict per time bucket keyed by field name (the docs say to map by name, not position)."""+ field_names = [f["name"] for f in body.get("fields", [])]+ rows: list[dict[str, Any]] = []+ for value_row in body.get("values", []):+ row: dict[str, Any] = dict(zip(field_names, value_row))+ row["app_id"] = app_id+ row["app_slug"] = app_slug+ rows.append(row)+ return rows+++def _time_window_params(+ config: DenoDeployEndpointConfig,+ should_use_incremental_field: bool,+ db_incremental_field_last_value: Any,+) -> tuple[str, str]:+ """Resolve the [start, end] window for the time-ranged endpoints (logs, analytics).++ `end` is always `now` — never omitted, since the logs endpoint switches to real-time streaming+ without it. `start` is the incremental watermark (minus a small lookback for boundary/clock-skew+ slack, clamped to never exceed now) or, on the first sync / full refresh, `now - default_lookback`.+ Because each run fetches every app up to `now`, consecutive windows overlap and leave no gap."""+ now = datetime.now(UTC)+ last = _as_utc_datetime(db_incremental_field_last_value) if should_use_incremental_field else None+ if last is not None:+ start = min(last, now)+ if config.incremental_lookback:+ start = start - config.incremental_lookback+ else:+ start = now - timedelta(days=config.default_lookback_days or 7)+ return _format_rfc3339(start), _format_rfc3339(now)+++def _initial_child_url(+ config: DenoDeployEndpointConfig,+ app_id: str,+ should_use_incremental_field: bool,+ db_incremental_field_last_value: Any,+) -> str:+ path = config.path.format(app=app_id)+ if config.kind == "logs":+ start, end = _time_window_params(config, should_use_incremental_field, db_incremental_field_last_value)+ return _build_url(path, {"start": start, "end": end, "limit": config.page_size or 1000})+ if config.kind == "analytics":+ since, until = _time_window_params(config, should_use_incremental_field, db_incremental_field_last_value)+ return _build_url(path, {"since": since, "until": until})+ # Plain list child (revisions).+ return _build_url(path, {"limit": config.page_size or DEFAULT_LIST_PAGE_SIZE})+++def _logs_next_url(current_url: str, next_cursor: str) -> str:+ """The logs endpoint returns its cursor in the body (`next_cursor`), not a Link header. Rebuild the+ next-page URL by swapping the `cursor` query param on the current URL, preserving start/end/limit.++ `parse_qsl` decodes the existing (already percent-encoded) query values so `urlencode` re-encodes+ them exactly once — splitting the raw query string by hand would double-encode `start`/`end`."""+ parts = urlsplit(current_url)+ params = [(k, v) for k, v in parse_qsl(parts.query, keep_blank_values=True) if k != "cursor"]+ params.append(("cursor", next_cursor))+ return urlunsplit((parts.scheme, parts.netloc, parts.path, urlencode(params), ""))+++def _parse_page(+ config: DenoDeployEndpointConfig, response: requests.Response, app_id: str, app_slug: str+) -> tuple[list[dict[str, Any]], str | None]:+ """Return (rows, next_url) for one fetched page, shaped per endpoint kind."""+ if config.kind == "logs":+ body = response.json()+ rows = [_shape_log(log, app_id, app_slug) for log in body.get("logs", [])]+ next_cursor = body.get("next_cursor")+ next_url = _logs_next_url(response.url, next_cursor) if next_cursor else None+ return rows, next_url+ if config.kind == "analytics":+ return _reshape_analytics(response.json(), app_id, app_slug), None+ # Plain list child (revisions): inject the parent app context the child response omits.+ data = response.json()+ rows = [{**item, "app_id": app_id, "app_slug": app_slug} for item in (data if isinstance(data, list) else [])]+ return rows, _parse_next_link(response.headers.get("Link", ""))+++def _list_rows(+ session: requests.Session,+ headers: dict[str, str],+ config: DenoDeployEndpointConfig,+ resumable_source_manager: ResumableSourceManager[DenoDeployResumeConfig],+ logger: FilteringBoundLogger,+) -> Iterator[list[dict[str, Any]]]:+ """Top-level cursor-paginated list (apps, domains), following the Link header."""+ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None+ if resume is not None and resume.next_url:+ url: str | None = resume.next_url+ logger.debug(f"Deno Deploy: resuming {config.name} from URL: {url}")+ else:+ url = _build_url(config.path, {"limit": config.page_size or DEFAULT_LIST_PAGE_SIZE})++ while url:+ response = _fetch(session, url, headers, logger)+ data = response.json()+ rows = data if isinstance(data, list) else []+ next_url = _parse_next_link(response.headers.get("Link", ""))+ if rows:+ yield rows+ if not next_url:+ break+ # Save AFTER yielding so a crash mid-yield re-fetches this page rather than skipping it; merge+ # dedupes the re-pulled rows on the primary key.+ resumable_source_manager.save_state(DenoDeployResumeConfig(next_url=next_url))+ url = next_url+++def _fan_out_rows(+ session: requests.Session,+ headers: dict[str, str],+ config: DenoDeployEndpointConfig,+ resumable_source_manager: ResumableSourceManager[DenoDeployResumeConfig],+ logger: FilteringBoundLogger,+ should_use_incremental_field: bool,+ db_incremental_field_last_value: Any,+) -> Iterator[list[dict[str, Any]]]:+ """Fan out over every app in the org, walking the child endpoint (revisions, analytics, logs) per+ app. A stable app-id bookmark lets a retry resume mid-fan-out without re-walking finished apps."""+ app_refs = list(_iter_app_refs(session, headers, logger))+ app_ids = [ref[0] for ref in app_refs]++ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None+ start_index = 0+ resume_url: str | None = None+ if resume is not None and resume.app_id is not None and resume.app_id in app_ids:+ start_index = app_ids.index(resume.app_id)+ resume_url = resume.next_url+ logger.debug(f"Deno Deploy: resuming {config.name} fan-out from app_id={resume.app_id}, url={resume_url}")++ for index in range(start_index, len(app_refs)):+ app_id, app_slug = app_refs[index]+ url: str | None = resume_url or _initial_child_url(+ config, app_id, should_use_incremental_field, db_incremental_field_last_value+ )+ resume_url = None # only the resumed-into app uses the saved URL; the rest start fresh++ while url:+ response = _fetch(session, url, headers, logger)+ rows, next_url = _parse_page(config, response, app_id, app_slug)+ if rows:+ yield rows+ if not next_url:+ break+ resumable_source_manager.save_state(DenoDeployResumeConfig(next_url=next_url, app_id=app_id))+ url = next_url++ # Advance the bookmark to the next app so a crash between apps resumes there; its first-page+ # URL is rebuilt fresh when the loop reaches it.+ if index + 1 < len(app_refs):+ resumable_source_manager.save_state(DenoDeployResumeConfig(next_url=None, app_id=app_refs[index + 1][0]))+++def get_rows(+ access_token: str,+ endpoint: str,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[DenoDeployResumeConfig],+ should_use_incremental_field: bool = False,+ db_incremental_field_last_value: Any = None,+) -> Iterator[list[dict[str, Any]]]:+ config = DENO_DEPLOY_ENDPOINTS[endpoint]+ headers = _get_headers(access_token)+ session = _make_session(access_token)++ if config.fan_out_over_apps:+ yield from _fan_out_rows(+ session,+ headers,+ config,+ resumable_source_manager,+ logger,+ should_use_incremental_field,+ db_incremental_field_last_value,+ )+ return++ yield from _list_rows(session, headers, config, resumable_source_manager, logger)+++def deno_deploy_source(+ access_token: str,+ endpoint: str,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[DenoDeployResumeConfig],+ should_use_incremental_field: bool = False,+ db_incremental_field_last_value: Optional[Any] = None,+) -> SourceResponse:+ endpoint_config = DENO_DEPLOY_ENDPOINTS[endpoint]++ return SourceResponse(+ name=endpoint,+ items=lambda: get_rows(+ access_token=access_token,+ endpoint=endpoint,+ logger=logger,+ resumable_source_manager=resumable_source_manager,+ should_use_incremental_field=should_use_incremental_field,+ db_incremental_field_last_value=db_incremental_field_last_value,+ ),+ primary_keys=endpoint_config.primary_keys,+ # Every endpoint emits ascending by its partition/incremental field: the list endpoints are+ # full-refresh (order only needs to be stable), and the time-windowed endpoints (logs,+ # analytics) return oldest-first within the [start, end] window, matching the watermark's+ # forward advance.+ sort_mode="asc",+ partition_count=1,+ partition_size=1,+ partition_mode="datetime" if endpoint_config.partition_key else None,+ partition_format="week" 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/deno_deploy/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/deno_deploy/settings.pynew file mode 100644index 000000000000..c37f24bf5ff5--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/deno_deploy/settings.py@@ -0,0 +1,127 @@+from dataclasses import dataclass, field+from datetime import timedelta+from typing import Literal, Optional++from products.warehouse_sources.backend.types import IncrementalField, IncrementalFieldType++# How the transport should page and shape a given endpoint's response:+# - "list": a plain paginated list (Link: <url>; rel="next" header), rows used as-is.+# - "logs": the runtime-logs endpoint — cursor lives in the body (`next_cursor`), rows carry+# no natural id, so the transport synthesizes a stable one for merge dedup.+# - "analytics": the columnar {fields, values} usage payload, reshaped into one row per time bucket.+EndpointKind = Literal["list", "logs", "analytics"]+++@dataclass+class DenoDeployEndpointConfig:+ name: str+ path: str # Path template; fan-out endpoints carry a {app} placeholder.+ kind: EndpointKind+ incremental_fields: list[IncrementalField]+ default_incremental_field: Optional[str] = None+ partition_key: Optional[str] = None+ # Primary key columns for dedup. A list declares a composite key, required for fan-out children+ # whose row id is only unique within a parent app.+ primary_keys: list[str] = field(default_factory=lambda: ["id"])+ # Fan out over every app in the org, substituting each app's id into the {app} path placeholder.+ fan_out_over_apps: bool = False+ page_size: Optional[int] = None+ # First-sync/full-refresh floor for the time-windowed endpoints (logs, analytics): only pull the+ # last N days instead of the whole (potentially unbounded) history. `start`/`since` are the only+ # way to bound these, and the logs endpoint requires `start`, so a default window is mandatory.+ default_lookback_days: Optional[int] = None+ # Safety overlap subtracted from the incremental watermark on every run. Because each run fetches+ # every app up to `now`, consecutive [start, now] windows already overlap and leave no gap; this+ # just re-pulls a small trailing window to absorb boundary-second and clock-skew effects. Merge+ # dedupes the re-pulled rows on the primary key.+ incremental_lookback: Optional[timedelta] = None+ should_sync_default: bool = True+++DENO_DEPLOY_ENDPOINTS: dict[str, DenoDeployEndpointConfig] = {+ # Every app in the organization the access token is scoped to. Small catalog, no server-side+ # updated-since filter, so full refresh; created_at is immutable and partitions stably.+ "apps": DenoDeployEndpointConfig(+ name="apps",+ path="/v2/apps",+ kind="list",+ partition_key="created_at",+ incremental_fields=[],+ ),+ # Deployment/build history per app. Fans out over apps. The list endpoint exposes only a `status`+ # filter (no updated-since), so full refresh; created_at is immutable. The row id is globally+ # addressable (/v2/revisions/{id}) but we keep app_id in the key defensively so a fan-out child+ # is unique table-wide regardless.+ "revisions": DenoDeployEndpointConfig(+ name="revisions",+ path="/v2/apps/{app}/revisions",+ kind="list",+ partition_key="created_at",+ primary_keys=["app_id", "id"],+ fan_out_over_apps=True,+ incremental_fields=[],+ ),+ # Custom domains for the organization. Small catalog, no updated-since filter, full refresh.+ "domains": DenoDeployEndpointConfig(+ name="domains",+ path="/v2/domains",+ kind="list",+ partition_key="created_at",+ incremental_fields=[],+ ),+ # Per-app usage metrics in 15-minute buckets. Fans out over apps. `since`/`until` are genuine+ # server-side RFC 3339 time filters, so this syncs incrementally on the bucket start `time`.+ # Merge on [app_id, time] dedupes the re-pulled boundary bucket.+ "analytics": DenoDeployEndpointConfig(+ name="analytics",+ path="/v2/apps/{app}/analytics",+ kind="analytics",+ partition_key="time",+ primary_keys=["app_id", "time"],+ fan_out_over_apps=True,+ default_incremental_field="time",+ default_lookback_days=30,+ incremental_lookback=timedelta(minutes=30), # one bucket of slack+ incremental_fields=[+ {+ "label": "time",+ "type": IncrementalFieldType.DateTime,+ "field": "time",+ "field_type": IncrementalFieldType.DateTime,+ },+ ],+ ),+ # Time-ranged runtime logs per app. Fans out over apps. `start` is a required server-side ISO 8601+ # filter (and `end` must be passed or the endpoint switches to real-time streaming), so this syncs+ # incrementally on `timestamp`. Runtime log lines carry no natural id, so the transport synthesizes+ # a content hash `id` and merges on it — re-pulled boundary lines dedupe instead of duplicating.+ "logs": DenoDeployEndpointConfig(+ name="logs",+ path="/v2/apps/{app}/logs",+ kind="logs",+ partition_key="timestamp",+ primary_keys=["id"],+ fan_out_over_apps=True,+ page_size=1000, # logs endpoint max+ default_incremental_field="timestamp",+ default_lookback_days=7,+ incremental_lookback=timedelta(minutes=5),+ incremental_fields=[+ {+ "label": "timestamp",+ "type": IncrementalFieldType.DateTime,+ "field": "timestamp",+ "field_type": IncrementalFieldType.DateTime,+ },+ ],+ # Logs are high volume; leave them deselected by default so a fresh connection doesn't backfill+ # a week of every app's logs unless the user opts in.+ should_sync_default=False,+ ),+}++ENDPOINTS = tuple(DENO_DEPLOY_ENDPOINTS.keys())++INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {+ name: config.incremental_fields for name, config in DENO_DEPLOY_ENDPOINTS.items()+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/deno_deploy/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/deno_deploy/source.pyindex 94d923fd5a8e..5c7a044e1e35 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/deno_deploy/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/deno_deploy/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 SourceSchema+from products.warehouse_sources.backend.temporal.data_imports.sources.deno_deploy.deno_deploy import (+ DenoDeployResumeConfig,+ deno_deploy_source,+ validate_credentials as validate_deno_deploy_credentials,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.deno_deploy.settings import (+ DENO_DEPLOY_ENDPOINTS,+ ENDPOINTS,+ INCREMENTAL_FIELDS,+)from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs import DenoDeploySourceConfigfrom products.warehouse_sources.backend.types import ExternalDataSourceType@SourceRegistry.register-class DenoDeploySource(SimpleSource[DenoDeploySourceConfig]):+class DenoDeploySource(ResumableSource[DenoDeploySourceConfig, DenoDeployResumeConfig]):+ lists_tables_without_credentials = True # static endpoint catalog — safe for public docs+@propertydef source_type(self) -> ExternalDataSourceType:return ExternalDataSourceType.DENODEPLOY@@ -24,8 +48,91 @@ class DenoDeploySource(SimpleSource[DenoDeploySourceConfig]):name=SchemaExternalDataSourceType.DENO_DEPLOY,category=DataWarehouseSourceCategory.ENGINEERING___MONITORING,label="Deno Deploy",+ releaseStatus=ReleaseStatus.ALPHA,+ caption="""Enter a Deno Deploy organization access token to sync your apps, revisions, domains, analytics, and runtime logs into the PostHog Data warehouse.++Create an organization access token in your [Deno Deploy dashboard](https://app.deno.com) under **Settings > Access Tokens**. The token is scoped to a single organization, so one connection syncs one Deno Deploy organization.""",iconPath="/static/services/deno_deploy.png",+ docsUrl="https://posthog.com/docs/cdp/sources/deno-deploy",keywords=["deno", "deploy", "serverless", "edge"],- fields=cast(list[FieldType], []),unreleasedSource=True,+ fields=cast(+ list[FieldType],+ [+ SourceFieldInputConfig(+ name="access_token",+ label="Access token",+ type=SourceFieldInputConfigType.PASSWORD,+ required=True,+ placeholder="ddo_...",+ secret=True,+ ),+ ],+ ),+ )++ def get_canonical_descriptions(self) -> CanonicalDescriptions:+ from products.warehouse_sources.backend.temporal.data_imports.sources.deno_deploy.canonical_descriptions import (+ CANONICAL_DESCRIPTIONS,+ )++ return CANONICAL_DESCRIPTIONS++ def get_non_retryable_errors(self) -> dict[str, str | None]:+ return {+ # An invalid, revoked, or expired token surfaces as a requests HTTPError when `_fetch`+ # 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.deno.com": "Your Deno Deploy access token is invalid or has been revoked. Create a new organization access token in your Deno Deploy dashboard, then reconnect.",+ "403 Client Error: Forbidden for url: https://api.deno.com": "Your Deno Deploy access token does not have permission to read this organization's data. Check the token's permissions, then reconnect.",+ }++ def get_schemas(+ self,+ config: DenoDeploySourceConfig,+ team_id: int,+ with_counts: bool = False,+ names: list[str] | None = None,+ force_refresh: bool = False,+ ) -> list[SourceSchema]:+ def _build_schema(endpoint: str) -> SourceSchema:+ endpoint_config = DENO_DEPLOY_ENDPOINTS[endpoint]+ has_incremental = bool(INCREMENTAL_FIELDS.get(endpoint))+ return SourceSchema(+ name=endpoint,+ supports_incremental=has_incremental,+ supports_append=has_incremental,+ incremental_fields=INCREMENTAL_FIELDS.get(endpoint, []),+ should_sync_default=endpoint_config.should_sync_default,+ )++ 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: DenoDeploySourceConfig, team_id: int, schema_name: Optional[str] = None+ ) -> tuple[bool, str | None]:+ return validate_deno_deploy_credentials(config.access_token)++ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[DenoDeployResumeConfig]:+ return ResumableSourceManager[DenoDeployResumeConfig](inputs, DenoDeployResumeConfig)++ def source_for_pipeline(+ self,+ config: DenoDeploySourceConfig,+ resumable_source_manager: ResumableSourceManager[DenoDeployResumeConfig],+ inputs: SourceInputs,+ ) -> SourceResponse:+ return deno_deploy_source(+ access_token=config.access_token,+ endpoint=inputs.schema_name,+ logger=inputs.logger,+ resumable_source_manager=resumable_source_manager,+ should_use_incremental_field=inputs.should_use_incremental_field,+ db_incremental_field_last_value=inputs.db_incremental_field_last_value+ if inputs.should_use_incremental_field+ else None,)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/deno_deploy/tests/test_deno_deploy.py b/products/warehouse_sources/backend/temporal/data_imports/sources/deno_deploy/tests/test_deno_deploy.pynew file mode 100644index 000000000000..fff8aae5b343--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/deno_deploy/tests/test_deno_deploy.py@@ -0,0 +1,386 @@+from datetime import UTC, date, datetime+from typing import Any, cast+from urllib.parse import parse_qsl, urlsplit++import pytest+from freezegun import freeze_time+from unittest.mock import MagicMock, patch++import requests+from parameterized import parameterized++from products.warehouse_sources.backend.temporal.data_imports.sources.deno_deploy import deno_deploy+from products.warehouse_sources.backend.temporal.data_imports.sources.deno_deploy.deno_deploy import (+ DENO_DEPLOY_ENDPOINTS,+ DenoDeployResumeConfig,+ _format_rfc3339,+ _initial_child_url,+ _log_row_id,+ _logs_next_url,+ _parse_next_link,+ _require_deno_deploy_url,+ _reshape_analytics,+ _shape_log,+ _time_window_params,+ deno_deploy_source,+ get_rows,+ validate_credentials,+)+++class FakeResponse:+ def __init__(+ self,+ json_data: Any,+ headers: dict[str, str] | None = None,+ status_code: int = 200,+ url: str = "https://api.deno.com/v2/apps",+ ) -> None:+ self._json = json_data+ self.headers = headers or {}+ self.status_code = status_code+ self.ok = status_code < 400+ self.url = url+ self.text = "" if json_data is None else str(json_data)++ def json(self) -> Any:+ return self._json++ def raise_for_status(self) -> None:+ if not self.ok:+ raise requests.HTTPError(f"{self.status_code} Client Error", response=cast(requests.Response, self))+++class FakeSession:+ def __init__(self, responses: list[FakeResponse]) -> None:+ self._responses = list(responses)+ self.urls: list[str] = []++ def get(self, url: str, headers: dict[str, str] | None = None, timeout: int | None = None) -> FakeResponse:+ self.urls.append(url)+ return self._responses.pop(0)+++class FakeManager:+ """Stand-in for ResumableSourceManager that records saved state and can seed a resume state."""++ def __init__(self, state: DenoDeployResumeConfig | None = None) -> None:+ self._state = state+ self.saved: list[DenoDeployResumeConfig] = []++ def can_resume(self) -> bool:+ return self._state is not None++ def load_state(self) -> DenoDeployResumeConfig | None:+ return self._state++ def save_state(self, state: DenoDeployResumeConfig) -> None:+ self.saved.append(state)+++def _run(endpoint: str, session: FakeSession, manager: FakeManager, **kwargs: Any) -> list[dict[str, Any]]:+ with patch.object(deno_deploy, "make_tracked_session", return_value=session):+ rows: list[dict[str, Any]] = []+ for batch in get_rows(+ access_token="ddo_test",+ endpoint=endpoint,+ logger=MagicMock(),+ resumable_source_manager=manager, # type: ignore[arg-type]+ **kwargs,+ ):+ rows.extend(batch)+ return rows+++class TestParseNextLink:+ @parameterized.expand(+ [+ (+ "absolute",+ '<https://api.deno.com/v2/apps?cursor=abc&limit=30>; rel="next"',+ "https://api.deno.com/v2/apps?cursor=abc&limit=30",+ ),+ ("relative", '</v2/apps?cursor=abc>; rel="next"', "https://api.deno.com/v2/apps?cursor=abc"),+ ("empty", "", None),+ ("no_next_rel", '<https://api.deno.com/v2/apps?cursor=abc>; rel="prev"', None),+ ]+ )+ def test_parse_next_link(self, _name: str, header: str, expected: str | None) -> None:+ assert _parse_next_link(header) == expected+++class TestFormatRfc3339:+ @parameterized.expand(+ [+ ("utc", datetime(2026, 3, 4, 2, 58, 14, tzinfo=UTC), "2026-03-04T02:58:14Z"),+ ("naive_treated_as_utc", datetime(2026, 3, 4, 2, 58, 14), "2026-03-04T02:58:14Z"),+ ]+ )+ def test_format(self, _name: str, value: datetime, expected: str) -> None:+ result = _format_rfc3339(value)+ assert result == expected+ assert "+00:00" not in result+++class TestLogRowId:+ def test_stable_and_content_addressed(self) -> None:+ log = {"timestamp": "2026-01-01T00:00:00Z", "level": "info", "message": "hi", "trace_id": "t1"}+ first = _log_row_id("app-1", log)+ # Same content -> same id (idempotent merge on re-pull of the boundary window).+ assert first == _log_row_id("app-1", dict(log))+ # Different app or content -> different id.+ assert first != _log_row_id("app-2", log)+ assert first != _log_row_id("app-1", {**log, "message": "bye"})+++class TestReshapeAnalytics:+ def test_columnar_to_rows(self) -> None:+ body = {+ "fields": [{"name": "time", "type": "time"}, {"name": "request_count", "type": "number"}],+ "values": [["2026-01-01T00:00:00Z", 5], ["2026-01-01T00:15:00Z", 9]],+ }+ rows = _reshape_analytics(body, "app-1", "my-app")+ assert rows == [+ {"time": "2026-01-01T00:00:00Z", "request_count": 5, "app_id": "app-1", "app_slug": "my-app"},+ {"time": "2026-01-01T00:15:00Z", "request_count": 9, "app_id": "app-1", "app_slug": "my-app"},+ ]++ def test_empty_values(self) -> None:+ assert _reshape_analytics({"fields": [{"name": "time", "type": "time"}], "values": []}, "a", "s") == []+++class TestShapeLog:+ def test_injects_context_and_id(self) -> None:+ row = _shape_log({"timestamp": "2026-01-01T00:00:00Z", "message": "hi"}, "app-1", "my-app")+ assert row["app_id"] == "app-1"+ assert row["app_slug"] == "my-app"+ assert row["message"] == "hi"+ assert isinstance(row["id"], str) and len(row["id"]) == 64 # sha256 hexdigest+++class TestTimeWindowParams:+ @freeze_time("2026-06-01T12:00:00Z")+ def test_first_sync_uses_lookback(self) -> None:+ # No watermark -> start = now - default_lookback_days (7 for logs).+ start, end = _time_window_params(+ DENO_DEPLOY_ENDPOINTS["logs"], should_use_incremental_field=True, db_incremental_field_last_value=None+ )+ assert end == "2026-06-01T12:00:00Z"+ assert start == "2026-05-25T12:00:00Z"++ @freeze_time("2026-06-01T12:00:00Z")+ def test_incremental_subtracts_lookback(self) -> None:+ # Watermark present -> start = watermark - incremental_lookback (5 min for logs).+ start, _ = _time_window_params(+ DENO_DEPLOY_ENDPOINTS["logs"],+ should_use_incremental_field=True,+ db_incremental_field_last_value=datetime(2026, 6, 1, 10, 0, 0, tzinfo=UTC),+ )+ assert start == "2026-06-01T09:55:00Z"++ @freeze_time("2026-06-01T12:00:00Z")+ def test_future_watermark_clamped_to_now(self) -> None:+ # A future-dated watermark can't push start past now.+ start, end = _time_window_params(+ DENO_DEPLOY_ENDPOINTS["analytics"],+ should_use_incremental_field=True,+ db_incremental_field_last_value=datetime(2027, 1, 1, tzinfo=UTC),+ )+ # start = min(future, now) - 30min lookback = now - 30min+ assert start == "2026-06-01T11:30:00Z"+ assert end == "2026-06-01T12:00:00Z"+++class TestInitialChildUrl:+ @freeze_time("2026-06-01T12:00:00Z")+ def test_logs_url_has_bounded_window(self) -> None:+ url = _initial_child_url(DENO_DEPLOY_ENDPOINTS["logs"], "app-1", True, None)+ assert url.startswith("https://api.deno.com/v2/apps/app-1/logs?")+ # end must always be present (omitting it switches the endpoint to real-time streaming).+ assert "start=" in url and "end=" in url and "limit=1000" in url++ @freeze_time("2026-06-01T12:00:00Z")+ def test_analytics_url_uses_since_until(self) -> None:+ url = _initial_child_url(DENO_DEPLOY_ENDPOINTS["analytics"], "app-1", True, None)+ assert "since=" in url and "until=" in url++ def test_revisions_url_uses_limit(self) -> None:+ url = _initial_child_url(DENO_DEPLOY_ENDPOINTS["revisions"], "app-1", False, None)+ assert url == "https://api.deno.com/v2/apps/app-1/revisions?limit=100"+++class TestLogsNextUrl:+ def test_swaps_cursor_preserving_window(self) -> None:+ current = "https://api.deno.com/v2/apps/app-1/logs?start=2026-01-01T00%3A00%3A00Z&end=2026-01-02T00%3A00%3A00Z&limit=1000&cursor=old"+ nxt = _logs_next_url(current, "new")+ assert "cursor=new" in nxt+ assert "cursor=old" not in nxt+ assert "start=" in nxt and "end=" in nxt and "limit=1000" in nxt+ # The already-encoded start/end must be encoded exactly once, not doubled (`%253A`); parsing the+ # rebuilt URL must recover the original timestamps.+ assert "%253A" not in nxt+ params = dict(parse_qsl(urlsplit(nxt).query))+ assert params["start"] == "2026-01-01T00:00:00Z"+ assert params["end"] == "2026-01-02T00:00:00Z"+++class TestRequireDenoDeployUrl:+ @parameterized.expand(+ [+ ("https_apex", "https://api.deno.com/v2/apps?limit=1", True),+ ("http_scheme_rejected", "http://api.deno.com/v2/apps", False),+ ("other_host_rejected", "https://evil.example.com/v2/apps", False),+ ("subdomain_rejected", "https://api.deno.com.evil.com/v2/apps", False),+ ("host_as_userinfo_rejected", "https://[email protected]/v2/apps", False),+ ]+ )+ def test_only_https_deno_host_allowed(self, _name: str, url: str, allowed: bool) -> None:+ if allowed:+ assert _require_deno_deploy_url(url) == url+ else:+ with pytest.raises(ValueError):+ _require_deno_deploy_url(url)+++class TestValidateCredentials:+ @parameterized.expand(+ [+ ("ok", 200, True),+ ("unauthorized", 401, False),+ ("forbidden", 403, False),+ ]+ )+ def test_status_mapping(self, _name: str, status: int, expected_ok: bool) -> None:+ session = MagicMock()+ session.get.return_value = FakeResponse({"message": "x"}, status_code=status)+ with patch.object(deno_deploy, "make_tracked_session", return_value=session):+ ok, error = validate_credentials("ddo_test")+ assert ok is expected_ok+ assert (error is None) is expected_ok++ def test_network_error(self) -> None:+ session = MagicMock()+ session.get.side_effect = requests.ConnectionError("boom")+ with patch.object(deno_deploy, "make_tracked_session", return_value=session):+ ok, error = validate_credentials("ddo_test")+ assert ok is False+ assert error is not None+++class TestListEndpointPagination:+ def test_apps_follows_link_header_and_checkpoints(self) -> None:+ session = FakeSession(+ [+ FakeResponse(+ [{"id": "a1", "slug": "one"}],+ headers={"Link": '<https://api.deno.com/v2/apps?cursor=p2&limit=100>; rel="next"'},+ ),+ FakeResponse([{"id": "a2", "slug": "two"}], headers={}),+ ]+ )+ manager = FakeManager()+ rows = _run("apps", session, manager)+ assert [r["id"] for r in rows] == ["a1", "a2"]+ # Saved state points at the not-yet-yielded next page (checkpoint after yielding page one).+ assert manager.saved == [DenoDeployResumeConfig(next_url="https://api.deno.com/v2/apps?cursor=p2&limit=100")]++ def test_apps_resumes_from_saved_url(self) -> None:+ session = FakeSession([FakeResponse([{"id": "a2", "slug": "two"}], headers={})])+ manager = FakeManager(state=DenoDeployResumeConfig(next_url="https://api.deno.com/v2/apps?cursor=p2"))+ rows = _run("apps", session, manager)+ assert [r["id"] for r in rows] == ["a2"]+ # It resumed from the saved URL rather than the default first page.+ assert session.urls[0] == "https://api.deno.com/v2/apps?cursor=p2"+++class TestFanOut:+ def test_revisions_inject_parent_app_context(self) -> None:+ session = FakeSession(+ [+ FakeResponse([{"id": "a1", "slug": "one"}, {"id": "a2", "slug": "two"}], headers={}), # /v2/apps+ FakeResponse([{"id": "r1", "status": "success"}], headers={}), # a1 revisions+ FakeResponse([{"id": "r2", "status": "failed"}], headers={}), # a2 revisions+ ]+ )+ rows = _run("revisions", session, FakeManager())+ assert rows == [+ {"id": "r1", "status": "success", "app_id": "a1", "app_slug": "one"},+ {"id": "r2", "status": "failed", "app_id": "a2", "app_slug": "two"},+ ]++ @freeze_time("2026-06-01T12:00:00Z")+ def test_logs_paginate_via_next_cursor(self) -> None:+ session = FakeSession(+ [+ FakeResponse([{"id": "a1", "slug": "one"}], headers={}), # /v2/apps+ FakeResponse(+ {"logs": [{"timestamp": "2026-06-01T10:00:00Z", "message": "m1"}], "next_cursor": "c2"},+ url="https://api.deno.com/v2/apps/a1/logs?start=x&end=y&limit=1000",+ ),+ FakeResponse(+ {"logs": [{"timestamp": "2026-06-01T11:00:00Z", "message": "m2"}], "next_cursor": None},+ url="https://api.deno.com/v2/apps/a1/logs?start=x&end=y&limit=1000&cursor=c2",+ ),+ ]+ )+ manager = FakeManager()+ rows = _run("logs", session, manager, should_use_incremental_field=True, db_incremental_field_last_value=None)+ assert [r["message"] for r in rows] == ["m1", "m2"]+ assert all("id" in r and r["app_id"] == "a1" for r in rows)+ # Second logs fetch followed the body cursor.+ assert "cursor=c2" in session.urls[-1]+ # Checkpoint carried the app id for mid-fan-out resume.+ assert manager.saved[0].app_id == "a1"++ def test_fanout_resumes_from_saved_app(self) -> None:+ session = FakeSession(+ [+ FakeResponse([{"id": "a1", "slug": "one"}, {"id": "a2", "slug": "two"}], headers={}), # /v2/apps+ FakeResponse([{"id": "r2", "status": "success"}], headers={}), # a2 revisions only+ ]+ )+ manager = FakeManager(state=DenoDeployResumeConfig(next_url=None, app_id="a2"))+ rows = _run("revisions", session, manager)+ # a1 skipped: resume started at a2.+ assert [r["id"] for r in rows] == ["r2"]+ assert rows[0]["app_id"] == "a2"+++class TestSourceResponse:+ @parameterized.expand(+ [+ ("apps", ["id"], "created_at", False),+ ("revisions", ["app_id", "id"], "created_at", False),+ ("domains", ["id"], "created_at", False),+ ("analytics", ["app_id", "time"], "time", True),+ ("logs", ["id"], "timestamp", True),+ ]+ )+ def test_response_shape(self, endpoint: str, pk: list[str], partition: str, incremental: bool) -> None:+ response = deno_deploy_source(+ access_token="ddo_test",+ endpoint=endpoint,+ logger=MagicMock(),+ resumable_source_manager=MagicMock(),+ should_use_incremental_field=incremental,+ db_incremental_field_last_value=None,+ )+ assert response.name == endpoint+ assert response.primary_keys == pk+ assert response.partition_keys == [partition]+ assert response.partition_mode == "datetime"+ assert response.sort_mode == "asc"++ @parameterized.expand([("date", date(2026, 1, 1)), ("string", "cursor")])+ def test_format_rfc3339_non_datetime_paths(self, _name: str, value: Any) -> None:+ # _time_window_params only calls _format_rfc3339 on datetimes it resolves, so exercise the+ # _as_utc_datetime coercion directly to lock in date handling.+ from products.warehouse_sources.backend.temporal.data_imports.sources.deno_deploy.deno_deploy import (+ _as_utc_datetime,+ )++ result = _as_utc_datetime(value)+ if isinstance(value, date):+ assert result is not None and result.tzinfo is UTC+ else:+ assert result is Nonediff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/deno_deploy/tests/test_deno_deploy_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/deno_deploy/tests/test_deno_deploy_source.pynew file mode 100644index 000000000000..000c928f6dbd--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/deno_deploy/tests/test_deno_deploy_source.py@@ -0,0 +1,122 @@+from typing import Any, cast++from unittest.mock import MagicMock, patch++from parameterized import parameterized++from posthog.schema import DataWarehouseSourceCategory, ReleaseStatus, SourceFieldInputConfig++from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from products.warehouse_sources.backend.temporal.data_imports.sources.deno_deploy import source as source_module+from products.warehouse_sources.backend.temporal.data_imports.sources.deno_deploy.deno_deploy import (+ DenoDeployResumeConfig,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.deno_deploy.source import DenoDeploySource+from products.warehouse_sources.backend.types import ExternalDataSourceType+++def _config() -> Any:+ config = MagicMock()+ config.access_token = "ddo_test"+ return config+++class TestDenoDeploySourceConfig:+ def test_source_type(self) -> None:+ assert DenoDeploySource().source_type == ExternalDataSourceType.DENODEPLOY++ def test_source_config_metadata(self) -> None:+ config = DenoDeploySource().get_source_config+ assert config.label == "Deno Deploy"+ assert config.category == DataWarehouseSourceCategory.ENGINEERING___MONITORING+ assert config.releaseStatus == ReleaseStatus.ALPHA+ assert config.docsUrl == "https://posthog.com/docs/cdp/sources/deno-deploy"+ field_names = [f.name for f in config.fields]+ assert field_names == ["access_token"]+ # The token is a secret, rendered as a password input.+ assert cast(SourceFieldInputConfig, config.fields[0]).secret is True++ def test_lists_tables_without_credentials(self) -> None:+ # get_schemas is a static endpoint catalog (no I/O), so the public docs catalog opts in.+ assert DenoDeploySource.lists_tables_without_credentials is True+ assert len(DenoDeploySource().get_documented_tables()) == 5+++class TestGetSchemas:+ def test_all_endpoints_present(self) -> None:+ schemas = DenoDeploySource().get_schemas(_config(), team_id=1)+ assert {s.name for s in schemas} == {"apps", "revisions", "domains", "analytics", "logs"}++ @parameterized.expand(+ [+ # Only the time-windowed endpoints with genuine server-side filters are incremental.+ ("apps", False, True),+ ("revisions", False, True),+ ("domains", False, True),+ ("analytics", True, True),+ # Logs are high volume, so they're deselected by default.+ ("logs", True, False),+ ]+ )+ def test_schema_flags(self, name: str, incremental: bool, should_sync_default: bool) -> None:+ schema = next(s for s in DenoDeploySource().get_schemas(_config(), team_id=1) if s.name == name)+ assert schema.supports_incremental is incremental+ assert schema.supports_append is incremental+ assert schema.should_sync_default is should_sync_default++ def test_names_filter(self) -> None:+ schemas = DenoDeploySource().get_schemas(_config(), team_id=1, names=["apps", "logs"])+ assert {s.name for s in schemas} == {"apps", "logs"}+++class TestValidateCredentials:+ @parameterized.expand([("valid", (True, None)), ("invalid", (False, "bad token"))])+ def test_delegates_to_transport(self, _name: str, result: tuple[bool, str | None]) -> None:+ with patch.object(source_module, "validate_deno_deploy_credentials", return_value=result) as mock_validate:+ assert DenoDeploySource().validate_credentials(_config(), team_id=1) == result+ mock_validate.assert_called_once_with("ddo_test")+++class TestNonRetryableErrors:+ def test_auth_errors_are_non_retryable(self) -> None:+ errors = DenoDeploySource().get_non_retryable_errors()+ assert any("401 Client Error" in key for key in errors)+ assert any("403 Client Error" in key for key in errors)+ # Matches the base host, not a per-request path, so it survives any URL.+ assert all("https://api.deno.com" in key for key in errors)+++class TestResumableWiring:+ def test_manager_bound_to_resume_config(self) -> None:+ inputs = MagicMock()+ manager = DenoDeploySource().get_resumable_source_manager(inputs)+ assert isinstance(manager, ResumableSourceManager)+ assert manager._data_class is DenoDeployResumeConfig++ def test_source_for_pipeline_plumbs_inputs(self) -> None:+ inputs = MagicMock()+ inputs.schema_name = "logs"+ inputs.should_use_incremental_field = True+ inputs.db_incremental_field_last_value = "2026-01-01T00:00:00Z"+ inputs.logger = MagicMock()+ manager = MagicMock()+ with patch.object(source_module, "deno_deploy_source", return_value="response") as mock_source:+ result = DenoDeploySource().source_for_pipeline(_config(), manager, inputs)+ assert cast(Any, result) == "response"+ _, kwargs = mock_source.call_args+ assert kwargs["access_token"] == "ddo_test"+ assert kwargs["endpoint"] == "logs"+ assert kwargs["should_use_incremental_field"] is True+ assert kwargs["db_incremental_field_last_value"] == "2026-01-01T00:00:00Z"++ def test_source_for_pipeline_drops_watermark_when_not_incremental(self) -> None:+ inputs = MagicMock()+ inputs.schema_name = "apps"+ inputs.should_use_incremental_field = False+ inputs.db_incremental_field_last_value = "2026-01-01T00:00:00Z"+ inputs.logger = MagicMock()+ with patch.object(source_module, "deno_deploy_source", return_value="response") as mock_source:+ DenoDeploySource().source_for_pipeline(_config(), MagicMock(), inputs)+ _, kwargs = mock_source.call_args+ # A full-refresh endpoint must not pass a stale watermark through.+ assert kwargs["db_incremental_field_last_value"] is Nonediff --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 7c459bbdbc8d..0741ec458919 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@@ -1039,7 +1039,7 @@ class DelightedSourceConfig(config.Config):@config.configclass DenoDeploySourceConfig(config.Config):- pass+ access_token: str@config.config