: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 koyeb import source (#70718)
Tom Owers2aa50ff337dc
diff --git a/frontend/public/services/koyeb.svg b/frontend/public/services/koyeb.svgnew file mode 100644index 000000000000..13c96bd9a56d--- /dev/null+++ b/frontend/public/services/koyeb.svg@@ -0,0 +1 @@+<svg xmlns="http://www.w3.org/2000/svg" fill="#000000" viewBox="0 0 32.47 32"><path d="M16.224 7.778l16.246 9.308V9.318L16.214 0 0 9.329v7.777z"/><path d="m29.871 26.446 2.599-1.52v-4.769L16.214 10.83 0 20.157v4.79l2.598 1.5 13.616-7.84z"/><path d="M16.224 29.632 20.35 32l6.777-3.879-10.913-6.267L5.342 28.12 12.118 32z"/></svg>diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.mdindex 5575c1f0bce2..004f914bc2f8 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md@@ -245,6 +245,7 @@ the row lists both.| katana | HTTP | requests | ✅ || kernel | HTTP | requests | ✅ || klaviyo | HTTP | requests | ✅ |+| koyeb | HTTP | requests | ✅ || lago | HTTP | requests | ✅ || lambda_labs | HTTP | requests | ✅ || langfuse | HTTP | requests | ✅ |diff --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 ad51dc798432..8e4dc7422310 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@@ -2255,7 +2255,7 @@ class KongKonnectSourceConfig(config.Config):@config.configclass KoyebSourceConfig(config.Config):- pass+ api_token: str@config.configdiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/koyeb/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/koyeb/canonical_descriptions.pynew file mode 100644index 000000000000..56c7199212b4--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/koyeb/canonical_descriptions.py@@ -0,0 +1,223 @@+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (+ CanonicalDescriptions,+)++# Descriptions sourced from the Koyeb public API reference (https://developer.koyeb.com/public),+# generated from the spec at https://api.prod.koyeb.com/public.swagger.json.+CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {+ "apps": {+ "description": "Applications in your Koyeb organization. An app groups services and holds the public *.koyeb.app domains assigned to them.",+ "docs_url": "https://developer.koyeb.com/public#tag/apps",+ "columns": {+ "id": "Unique identifier of the app.",+ "name": "Name of the app, used in the auto-assigned <app>-<org>.koyeb.app domain.",+ "organization_id": "Identifier of the organization owning the app.",+ "status": "Current status of the app (e.g. STARTING, HEALTHY, DELETED).",+ "domains": "Domains attached to the app, including the auto-assigned koyeb.app domain.",+ "created_at": "When the app was created.",+ "updated_at": "When the app was last updated.",+ },+ },+ "services": {+ "description": "Services running inside your Koyeb apps: web services, workers, and databases.",+ "docs_url": "https://developer.koyeb.com/public#tag/services",+ "columns": {+ "id": "Unique identifier of the service.",+ "name": "Name of the service.",+ "type": "Type of the service (WEB, WORKER, or DATABASE).",+ "app_id": "Identifier of the app the service belongs to.",+ "organization_id": "Identifier of the organization owning the service.",+ "status": "Current status of the service (e.g. STARTING, HEALTHY, PAUSED, DELETED).",+ "active_deployment_id": "Identifier of the deployment currently serving traffic.",+ "latest_deployment_id": "Identifier of the most recent deployment of the service.",+ "created_at": "When the service was created.",+ "updated_at": "When the service was last updated.",+ },+ },+ "deployments": {+ "description": "Deployments of your Koyeb services. Each deployment captures the full definition of a service version and its rollout status.",+ "docs_url": "https://developer.koyeb.com/public#tag/deployments",+ "columns": {+ "id": "Unique identifier of the deployment.",+ "app_id": "Identifier of the app the deployment belongs to.",+ "service_id": "Identifier of the service the deployment belongs to.",+ "parent_id": "Identifier of the deployment this one was created from.",+ "status": "Current status of the deployment (e.g. PENDING, HEALTHY, ERROR, STOPPED).",+ "definition": "Full definition of the deployment: image or git source, regions, ports, instance types, scaling, and environment.",+ "started_at": "When the deployment started.",+ "succeeded_at": "When the deployment succeeded.",+ "terminated_at": "When the deployment terminated.",+ "created_at": "When the deployment was created.",+ "updated_at": "When the deployment was last updated.",+ },+ },+ "regional_deployments": {+ "description": "Per-region rollouts of a deployment, one row per region a deployment runs in.",+ "docs_url": "https://developer.koyeb.com/public#tag/regional-deployments",+ "columns": {+ "id": "Unique identifier of the regional deployment.",+ "region": "Region the deployment runs in (e.g. fra, was, sin).",+ "status": "Current status of the regional deployment.",+ "created_at": "When the regional deployment was created.",+ "updated_at": "When the regional deployment was last updated.",+ },+ },+ "instances": {+ "description": "Compute instances backing your Koyeb services, one row per instance (replica) of a regional deployment.",+ "docs_url": "https://developer.koyeb.com/public#tag/instances",+ "columns": {+ "id": "Unique identifier of the instance.",+ "app_id": "Identifier of the app the instance belongs to.",+ "service_id": "Identifier of the service the instance belongs to.",+ "regional_deployment_id": "Identifier of the regional deployment the instance belongs to.",+ "replica_index": "Index of the replica within the regional deployment.",+ "region": "Region the instance runs in.",+ "datacenter": "Datacenter the instance runs in.",+ "type": "Instance type (e.g. nano, small, or a GPU type).",+ "status": "Current status of the instance (e.g. ALLOCATING, HEALTHY, STOPPED).",+ "created_at": "When the instance was created.",+ "updated_at": "When the instance was last updated.",+ },+ },+ "domains": {+ "description": "Domains in your Koyeb organization: auto-assigned *.koyeb.app domains and verified custom domains.",+ "docs_url": "https://developer.koyeb.com/public#tag/domains",+ "columns": {+ "id": "Unique identifier of the domain.",+ "name": "Fully qualified domain name.",+ "type": "Type of the domain (AUTOASSIGNED or CUSTOM).",+ "status": "Current status of the domain (e.g. PENDING, ACTIVE, ERROR).",+ "app_id": "Identifier of the app the domain is attached to.",+ "intended_cname": "CNAME record a custom domain must point at to be verified.",+ "verified_at": "When the domain was verified.",+ "created_at": "When the domain was created.",+ },+ },+ "secrets": {+ "description": "Secrets defined in your Koyeb organization. Metadata only — secret values are never returned by the list API and are not synced.",+ "docs_url": "https://developer.koyeb.com/public#tag/secrets",+ "columns": {+ "id": "Unique identifier of the secret.",+ "name": "Name of the secret.",+ "type": "Type of the secret (SIMPLE, REGISTRY, or MANAGED).",+ "created_at": "When the secret was created.",+ "updated_at": "When the secret was last updated.",+ },+ },+ "volumes": {+ "description": "Persistent volumes attached to your Koyeb services.",+ "docs_url": "https://developer.koyeb.com/public#tag/persistent-volumes",+ "columns": {+ "id": "Unique identifier of the volume.",+ "name": "Name of the volume.",+ "service_id": "Identifier of the service the volume is attached to.",+ "region": "Region the volume lives in.",+ "max_size": "Maximum size of the volume in GB.",+ "cur_size": "Current size of the volume in GB.",+ "status": "Current status of the volume (e.g. ATTACHED, DETACHED, DELETED).",+ "created_at": "When the volume was created.",+ },+ },+ "snapshots": {+ "description": "Snapshots of your Koyeb persistent volumes.",+ "docs_url": "https://developer.koyeb.com/public#tag/snapshots",+ "columns": {+ "id": "Unique identifier of the snapshot.",+ "name": "Name of the snapshot.",+ "parent_volume_id": "Identifier of the volume the snapshot was taken from.",+ "region": "Region the snapshot lives in.",+ "size": "Size of the snapshot in GB.",+ "status": "Current status of the snapshot.",+ "type": "Type of the snapshot (LOCAL or REMOTE).",+ "created_at": "When the snapshot was created.",+ },+ },+ "organization_members": {+ "description": "Members of the Koyeb organization the API token is scoped to.",+ "docs_url": "https://developer.koyeb.com/public#tag/organization-members",+ "columns": {+ "id": "Unique identifier of the membership.",+ "user_id": "Identifier of the member's user account.",+ "organization_id": "Identifier of the organization.",+ "role": "Role of the member within the organization (e.g. OWNER, MEMBER).",+ "status": "Current status of the membership.",+ "joined_at": "When the member joined the organization.",+ },+ },+ "activities": {+ "description": "Audit trail of actions performed in your Koyeb organization: who did what to which object.",+ "docs_url": "https://developer.koyeb.com/public#tag/activities",+ "columns": {+ "id": "Unique identifier of the activity.",+ "actor": "User or system that performed the action.",+ "object": "Object the action was performed on.",+ "verb": "Action performed (e.g. created, updated, deleted).",+ "metadata": "Additional context about the action.",+ "created_at": "When the activity occurred.",+ },+ },+ "app_events": {+ "description": "Append-only stream of lifecycle events for your Koyeb apps.",+ "docs_url": "https://developer.koyeb.com/public#tag/apps",+ "columns": {+ "id": "Unique identifier of the event.",+ "app_id": "Identifier of the app the event relates to.",+ "type": "Type of the event.",+ "message": "Human-readable description of the event.",+ "metadata": "Additional context about the event.",+ "when": "When the event occurred.",+ },+ },+ "service_events": {+ "description": "Append-only stream of lifecycle events for your Koyeb services.",+ "docs_url": "https://developer.koyeb.com/public#tag/services",+ "columns": {+ "id": "Unique identifier of the event.",+ "service_id": "Identifier of the service the event relates to.",+ "type": "Type of the event.",+ "message": "Human-readable description of the event.",+ "metadata": "Additional context about the event.",+ "when": "When the event occurred.",+ },+ },+ "deployment_events": {+ "description": "Append-only stream of lifecycle events for your Koyeb deployments.",+ "docs_url": "https://developer.koyeb.com/public#tag/deployments",+ "columns": {+ "id": "Unique identifier of the event.",+ "deployment_id": "Identifier of the deployment the event relates to.",+ "type": "Type of the event.",+ "message": "Human-readable description of the event.",+ "metadata": "Additional context about the event.",+ "when": "When the event occurred.",+ },+ },+ "instance_events": {+ "description": "Append-only stream of lifecycle events for your Koyeb instances.",+ "docs_url": "https://developer.koyeb.com/public#tag/instances",+ "columns": {+ "id": "Unique identifier of the event.",+ "instance_id": "Identifier of the instance the event relates to.",+ "type": "Type of the event.",+ "message": "Human-readable description of the event.",+ "metadata": "Additional context about the event.",+ "when": "When the event occurred.",+ },+ },+ "usage_details": {+ "description": "Per-instance usage records for your Koyeb organization: one row per instance run with its duration, used for billing.",+ "docs_url": "https://developer.koyeb.com/public#tag/usages",+ "columns": {+ "instance_id": "Identifier of the instance the usage relates to.",+ "instance_type": "Instance type the usage was billed as.",+ "app_id": "Identifier of the app the instance belonged to.",+ "app_name": "Name of the app the instance belonged to.",+ "service_id": "Identifier of the service the instance belonged to.",+ "service_name": "Name of the service the instance belonged to.",+ "region": "Region the instance ran in.",+ "duration_seconds": "How long the instance ran, in seconds.",+ "started_at": "When the instance run started.",+ "terminated_at": "When the instance run terminated.",+ },+ },+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/koyeb/koyeb.py b/products/warehouse_sources/backend/temporal/data_imports/sources/koyeb/koyeb.pynew file mode 100644index 000000000000..e636a4dc6f7b--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/koyeb/koyeb.py@@ -0,0 +1,253 @@+import dataclasses+from collections.abc import Iterator+from datetime import UTC, date, datetime+from typing import Any, Optional+from urllib.parse import urlencode++import requests+from structlog.types import FilteringBoundLogger+from tenacity import retry, retry_if_exception_type, stop_after_attempt, wait_exponential_jitter++from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import SourceResponse+from products.warehouse_sources.backend.temporal.data_imports.sources.common.http import make_tracked_session+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from products.warehouse_sources.backend.temporal.data_imports.sources.koyeb.settings import (+ KOYEB_ENDPOINTS,+ KoyebEndpointConfig,+)++KOYEB_BASE_URL = "https://app.koyeb.com"++# Koyeb caps list page sizes at 100 (default 10); request the max to minimize round-trips.+PAGE_SIZE = 100++# Backstop against an endpoint that ignores `offset` (which would otherwise re-serve page one+# forever). Resumable state means an interrupted sync picks back up, so this is a runaway guard,+# not a coverage limit — at 100 rows/page it allows ~1M rows before warning.+MAX_PAGES = 10_000++# /v1/usages/details requires a time window; Koyeb launched in 2019, so this floor covers any+# organization's full usage history.+USAGE_WINDOW_START = "2019-01-01T00:00:00Z"+++class KoyebRetryableError(Exception):+ pass+++class KoyebResumeConfig:+ # The `offset` of the next page to fetch. Rows are requested in ascending order (where the+ # endpoint supports `order`), so rows appended mid-sync land after the offset and can't shift+ # earlier pages underneath it.+ offset: int = 0+++# Placeholder written over plaintext secrets pulled out of deployment definitions, so the column+# still shows a value existed without exposing it.+REDACTED_SECRET = "[redacted by PostHog]"+++def _scrub_definition_secrets(row: dict[str, Any]) -> dict[str, Any]:+ """Redact plaintext secrets embedded in a deployment `definition` in place.++ `definition.env[].value` is a plaintext environment value and `definition.config_files[].content`+ is raw config-file content — both can hold credentials. We keep the surrounding structure (env+ keys, secret *references*, file paths) so the row stays useful, but overwrite the secret-bearing+ values. Anything that isn't shaped as expected is left untouched.+ """+ definition = row.get("definition")+ if not isinstance(definition, dict):+ return row++ env = definition.get("env")+ if isinstance(env, list):+ for var in env:+ # `secret` is only a reference to a Koyeb secret name (safe); `value` is the plaintext.+ if isinstance(var, dict) and var.get("value") is not None:+ var["value"] = REDACTED_SECRET++ config_files = definition.get("config_files")+ if isinstance(config_files, list):+ for config_file in config_files:+ if isinstance(config_file, dict) and config_file.get("content") is not None:+ config_file["content"] = REDACTED_SECRET++ return row+++def _get_headers(api_token: str) -> dict[str, str]:+ return {+ "Authorization": f"Bearer {api_token}",+ "Accept": "application/json",+ }+++def _format_time_value(value: Any) -> str:+ """Format an incremental cursor as the RFC 3339 UTC timestamp Koyeb's date-time params expect."""+ if isinstance(value, datetime):+ utc_value = value.astimezone(UTC) if value.tzinfo else value.replace(tzinfo=UTC)+ return utc_value.strftime("%Y-%m-%dT%H:%M:%SZ")+ if isinstance(value, date):+ return f"{value.isoformat()}T00:00:00Z"+ return str(value)+++def _build_params(+ config: KoyebEndpointConfig,+ offset: int,+ starting_time_value: Any,+ ending_time_value: str | None = None,+) -> dict[str, Any]:+ params: dict[str, Any] = {"limit": PAGE_SIZE, "offset": offset}++ if config.supports_order:+ params["order"] = "asc"++ if config.requires_time_window:+ params["starting_time"] = USAGE_WINDOW_START+ params["ending_time"] = ending_time_value or _format_time_value(datetime.now(UTC))+ elif config.starting_time_param and starting_time_value is not None:+ params[config.starting_time_param] = _format_time_value(starting_time_value)++ return params+++def _build_url(path: str, params: dict[str, Any]) -> str:+ return f"{KOYEB_BASE_URL}{path}?{urlencode(params)}"+++@retry(+ retry=retry_if_exception_type((KoyebRetryableError, requests.ReadTimeout, requests.ConnectionError)),+ 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+) -> dict[str, Any]:+ response = session.get(url, headers=headers, timeout=60)++ # Koyeb publishes no rate limits; treat 429 and any 5xx as transient and let tenacity back+ # off. A bad/revoked token (401/403) is raised below via raise_for_status() and matched by+ # get_non_retryable_errors() so the sync stops.+ if response.status_code == 429 or response.status_code >= 500:+ raise KoyebRetryableError(f"Koyeb API error (retryable): status={response.status_code}, url={url}")++ if not response.ok:+ logger.error(f"Koyeb API error: status={response.status_code}, body={response.text}, url={url}")+ response.raise_for_status()++ return response.json()+++def validate_credentials(api_token: str) -> tuple[bool, str | None]:+ """Confirm the API token is genuine via GET /v1/account/profile — the cheapest authenticated+ probe. Koyeb tokens are organization-scoped with no per-resource permissions, so one probe+ covers every endpoint."""+ try:+ response = make_tracked_session().get(+ f"{KOYEB_BASE_URL}/v1/account/profile", headers=_get_headers(api_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 in (401, 403):+ return False, "Invalid or unauthorized Koyeb API token"+ return False, f"Koyeb API error: {response.status_code}"+++def get_rows(+ api_token: str,+ endpoint: str,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[KoyebResumeConfig],+ should_use_incremental_field: bool = False,+ db_incremental_field_last_value: Any = None,+) -> Iterator[list[dict[str, Any]]]:+ config = KOYEB_ENDPOINTS[endpoint]+ headers = _get_headers(api_token)+ # One session reused across every page so urllib3 keeps the connection alive. Endpoints whose+ # rows get secret-scrubbed also opt out of HTTP sample capture: capture stores the raw response+ # body before _scrub_definition_secrets runs, and the capture path's name-based scrubbers can't+ # recognise plaintext env values or config-file content.+ session = make_tracked_session(capture=not config.scrub_definition_secrets)++ cutoff = (+ db_incremental_field_last_value+ if (should_use_incremental_field and config.starting_time_param and db_incremental_field_last_value is not None)+ else None+ )+ # Fixed once per run so the window (and therefore the row set behind the offsets) doesn't+ # drift while paginating.+ ending_time = _format_time_value(datetime.now(UTC)) if config.requires_time_window else None++ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None+ offset = resume.offset if resume else 0+ if resume is not None:+ logger.debug(f"Koyeb: resuming {endpoint} from offset={offset}")++ page_count = 0+ while True:+ url = _build_url(config.path, _build_params(config, offset, cutoff, ending_time))+ data = _fetch_page(session, url, headers, logger)++ items = data.get(config.response_data_key) or []+ if not items:+ break++ if config.scrub_definition_secrets:+ for item in items:+ if isinstance(item, dict):+ _scrub_definition_secrets(item)++ # Some Koyeb replies carry `has_next`; the rest only echo pagination params, so a short+ # page is the fallback end-of-list signal (an exact-multiple total costs one extra empty+ # page, caught above).+ has_next = data.get("has_next")+ is_last_page = has_next is False or (has_next is None and len(items) < PAGE_SIZE)++ yield items+ offset += len(items)+ page_count += 1++ if is_last_page:+ break+ if page_count >= MAX_PAGES:+ logger.warning(f"Koyeb: {endpoint} hit MAX_PAGES={MAX_PAGES}; remaining pages skipped")+ break+ # Checkpoint AFTER the page has been yielded so a crash re-fetches at most the in-flight+ # page instead of skipping it.+ resumable_source_manager.save_state(KoyebResumeConfig(offset=offset))+++def koyeb_source(+ api_token: str,+ endpoint: str,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[KoyebResumeConfig],+ should_use_incremental_field: bool = False,+ db_incremental_field_last_value: Optional[Any] = None,+) -> SourceResponse:+ endpoint_config = KOYEB_ENDPOINTS[endpoint]++ return SourceResponse(+ name=endpoint,+ items=lambda: get_rows(+ api_token=api_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,+ # Endpoints with an `order` param are requested ascending; the rest are full refresh only,+ # where the watermark is never consulted.+ sort_mode="asc",+ 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/koyeb/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/koyeb/settings.pynew file mode 100644index 000000000000..6bef612d2235--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/koyeb/settings.py@@ -0,0 +1,195 @@+from dataclasses import dataclass, field+from typing import Optional++from products.warehouse_sources.backend.types import IncrementalField, IncrementalFieldType+++@dataclass+class KoyebEndpointConfig:+ name: str+ # Path on https://app.koyeb.com (the canonical Koyeb API host; api.prod.koyeb.com is an alias).+ path: str+ # Key in the JSON response body that holds the list of rows (e.g. {"apps": [...]}).+ response_data_key: str+ primary_keys: list[str]+ # Stable datetime field used for datetime partitioning. Must never change after the row is+ # created (created_at / when / started_at) — an updated_at-style key would rewrite partitions+ # on every sync.+ partition_key: Optional[str] = None+ incremental_fields: list[IncrementalField] = field(default_factory=list)+ # Endpoint accepts an `order` query param ("asc"/"desc"). We always request "asc" so offset+ # pagination stays stable while new rows are appended during a sync.+ supports_order: bool = False+ # Query param that lower-bounds results by time (RFC 3339). Only set where Koyeb documents a+ # genuine server-side time filter — None means full refresh for this endpoint.+ starting_time_param: Optional[str] = None+ # /v1/usages/details requires a starting_time/ending_time window on every request (they are+ # the only list params Koyeb does not mark "(Optional)" in its API spec).+ requires_time_window: bool = False+ # Endpoint rows embed a deployment `definition`, whose `env[].value` and `config_files[].content`+ # carry plaintext application secrets. Redact those before persisting so warehouse-query access+ # can't surface credentials a member can't read in Koyeb itself.+ scrub_definition_secrets: bool = False+++# Every Koyeb list endpoint shares one pagination model: `limit`/`offset` query params, with the+# reply echoing `limit`/`offset` and, on most endpoints, a `has_next` boolean (some replies carry+# only `count`, so a short page is the fallback end-of-list signal). Entity ids are unique across+# the organization the API token is scoped to.+#+# Only `instances` is marked incremental: it is the one entity list with a documented server-side+# time filter (`starting_time`, which bounds the period the instance was running — a superset of+# "created after the watermark", and the merge dedupes the overlap on `id`). The event streams and+# `activities` are append-only but expose no time filter, so re-paging them is a full refresh by+# definition; the remaining config entities are small and ship as full refresh too.+KOYEB_ENDPOINTS: dict[str, KoyebEndpointConfig] = {+ "apps": KoyebEndpointConfig(+ name="apps",+ path="/v1/apps",+ response_data_key="apps",+ primary_keys=["id"],+ partition_key="created_at",+ ),+ "services": KoyebEndpointConfig(+ name="services",+ path="/v1/services",+ response_data_key="services",+ primary_keys=["id"],+ partition_key="created_at",+ ),+ "deployments": KoyebEndpointConfig(+ name="deployments",+ path="/v1/deployments",+ response_data_key="deployments",+ primary_keys=["id"],+ partition_key="created_at",+ scrub_definition_secrets=True,+ ),+ "regional_deployments": KoyebEndpointConfig(+ name="regional_deployments",+ path="/v1/regional_deployments",+ response_data_key="regional_deployments",+ primary_keys=["id"],+ partition_key="created_at",+ # Documented rows carry no definition, but scrub defensively in case a per-region rollout+ # ever echoes the deployment definition it was cut from.+ scrub_definition_secrets=True,+ ),+ "instances": KoyebEndpointConfig(+ name="instances",+ path="/v1/instances",+ response_data_key="instances",+ primary_keys=["id"],+ partition_key="created_at",+ supports_order=True,+ # `starting_time` filters instances by the period they were running, so any instance+ # created after the watermark is included; long-running instances created earlier are+ # re-fetched and deduped by the merge on `id`. We had no live credentials to probe the+ # filter with a future-date cutoff, so the paginator keeps its full termination logic+ # rather than trusting the filter alone.+ starting_time_param="starting_time",+ incremental_fields=[+ {+ "label": "created_at",+ "type": IncrementalFieldType.DateTime,+ "field": "created_at",+ "field_type": IncrementalFieldType.DateTime,+ },+ ],+ ),+ "domains": KoyebEndpointConfig(+ name="domains",+ path="/v1/domains",+ response_data_key="domains",+ primary_keys=["id"],+ partition_key="created_at",+ ),+ # List metadata only — Koyeb never returns secret values from the list endpoint (they require+ # a separate explicit reveal call, which this source never makes).+ "secrets": KoyebEndpointConfig(+ name="secrets",+ path="/v1/secrets",+ response_data_key="secrets",+ primary_keys=["id"],+ partition_key="created_at",+ ),+ "volumes": KoyebEndpointConfig(+ name="volumes",+ path="/v1/volumes",+ response_data_key="volumes",+ primary_keys=["id"],+ partition_key="created_at",+ ),+ "snapshots": KoyebEndpointConfig(+ name="snapshots",+ path="/v1/snapshots",+ response_data_key="snapshots",+ primary_keys=["id"],+ partition_key="created_at",+ ),+ # No partition key: `joined_at` moves if a member is removed and re-invited, and the table is+ # tiny anyway.+ "organization_members": KoyebEndpointConfig(+ name="organization_members",+ path="/v1/organization_members",+ response_data_key="members",+ primary_keys=["id"],+ ),+ "activities": KoyebEndpointConfig(+ name="activities",+ path="/v1/activities",+ response_data_key="activities",+ primary_keys=["id"],+ partition_key="created_at",+ ),+ "app_events": KoyebEndpointConfig(+ name="app_events",+ path="/v1/app_events",+ response_data_key="events",+ primary_keys=["id"],+ partition_key="when",+ supports_order=True,+ ),+ "service_events": KoyebEndpointConfig(+ name="service_events",+ path="/v1/service_events",+ response_data_key="events",+ primary_keys=["id"],+ partition_key="when",+ supports_order=True,+ ),+ "deployment_events": KoyebEndpointConfig(+ name="deployment_events",+ path="/v1/deployment_events",+ response_data_key="events",+ primary_keys=["id"],+ partition_key="when",+ supports_order=True,+ ),+ "instance_events": KoyebEndpointConfig(+ name="instance_events",+ path="/v1/instance_events",+ response_data_key="events",+ primary_keys=["id"],+ partition_key="when",+ supports_order=True,+ ),+ # Usage rows have no id; one row per instance run, keyed by the instance and when that run+ # started. Full refresh only: rows for still-running instances keep accruing+ # `duration_seconds`, so replacing the table each sync is the only shape that stays correct.+ "usage_details": KoyebEndpointConfig(+ name="usage_details",+ path="/v1/usages/details",+ response_data_key="usage_details",+ primary_keys=["instance_id", "started_at"],+ partition_key="started_at",+ supports_order=True,+ requires_time_window=True,+ ),+}++ENDPOINTS = tuple(KOYEB_ENDPOINTS.keys())++INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {+ name: config.incremental_fields for name, config in KOYEB_ENDPOINTS.items()+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/koyeb/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/koyeb/source.pyindex 166d7083cfab..4cfea8102e4b 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/koyeb/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/koyeb/source.py@@ -1,19 +1,45 @@-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 KoyebSourceConfig+from products.warehouse_sources.backend.temporal.data_imports.sources.koyeb.koyeb import (+ KoyebResumeConfig,+ koyeb_source,+ validate_credentials as validate_koyeb_credentials,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.koyeb.settings import (+ ENDPOINTS,+ INCREMENTAL_FIELDS,+ KOYEB_ENDPOINTS,+)from products.warehouse_sources.backend.types import ExternalDataSourceType@SourceRegistry.register-class KoyebSource(SimpleSource[KoyebSourceConfig]):+class KoyebSource(ResumableSource[KoyebSourceConfig, KoyebResumeConfig]):+ # `get_schemas` iterates the static endpoint catalog with no I/O, so the public docs can+ # render the table list without credentials.+ lists_tables_without_credentials = True+@propertydef source_type(self) -> ExternalDataSourceType:return ExternalDataSourceType.KOYEB@@ -24,8 +50,88 @@ class KoyebSource(SimpleSource[KoyebSourceConfig]):name=SchemaExternalDataSourceType.KOYEB,category=DataWarehouseSourceCategory.ENGINEERING___MONITORING,label="Koyeb",- iconPath="/static/services/koyeb.png",+ releaseStatus=ReleaseStatus.ALPHA,+ caption="""Enter a Koyeb API token to pull your Koyeb apps, services, deployments, instances, event streams, and usage details into the PostHog Data warehouse.++Create an API token under [API settings](https://app.koyeb.com/user/settings/api) in the Koyeb console. Tokens are scoped to the organization they were created in.""",+ iconPath="/static/services/koyeb.svg",+ docsUrl="https://posthog.com/docs/cdp/sources/koyeb",keywords=["serverless", "deployments", "hosting", "infrastructure"],- fields=cast(list[FieldType], []),- unreleasedSource=True,+ fields=cast(+ list[FieldType],+ [+ SourceFieldInputConfig(+ name="api_token",+ label="API token",+ type=SourceFieldInputConfigType.PASSWORD,+ required=True,+ placeholder="",+ secret=True,+ ),+ ],+ ),+ )++ def get_canonical_descriptions(self) -> CanonicalDescriptions:+ from products.warehouse_sources.backend.temporal.data_imports.sources.koyeb.canonical_descriptions import (+ CANONICAL_DESCRIPTIONS,+ )++ return CANONICAL_DESCRIPTIONS++ def get_non_retryable_errors(self) -> dict[str, str | None]:+ return {+ # 401/403 surface as a requests HTTPError when `_fetch_page` calls raise_for_status().+ # Retrying never satisfies 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://app.koyeb.com": "Your Koyeb API token is invalid or has been revoked. Create a new token in the Koyeb console under API settings, then reconnect.",+ "403 Client Error: Forbidden for url: https://app.koyeb.com": "Your Koyeb API token is not authorized for this organization. Check the token's organization, then reconnect.",+ }++ def get_schemas(+ self,+ config: KoyebSourceConfig,+ team_id: int,+ with_counts: bool = False,+ names: list[str] | None = None,+ force_refresh: bool = False,+ ) -> list[SourceSchema]:+ schemas = [+ SourceSchema(+ name=endpoint,+ supports_incremental=bool(INCREMENTAL_FIELDS.get(endpoint)),+ supports_append=bool(INCREMENTAL_FIELDS.get(endpoint)),+ incremental_fields=INCREMENTAL_FIELDS.get(endpoint, []),+ detected_primary_keys=KOYEB_ENDPOINTS[endpoint].primary_keys,+ )+ 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: KoyebSourceConfig, team_id: int, schema_name: Optional[str] = None+ ) -> tuple[bool, str | None]:+ return validate_koyeb_credentials(config.api_token)++ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[KoyebResumeConfig]:+ return ResumableSourceManager[KoyebResumeConfig](inputs, KoyebResumeConfig)++ def source_for_pipeline(+ self,+ config: KoyebSourceConfig,+ resumable_source_manager: ResumableSourceManager[KoyebResumeConfig],+ inputs: SourceInputs,+ ) -> SourceResponse:+ return koyeb_source(+ api_token=config.api_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/koyeb/tests/test_koyeb.py b/products/warehouse_sources/backend/temporal/data_imports/sources/koyeb/tests/test_koyeb.pynew file mode 100644index 000000000000..35056b852d9e--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/koyeb/tests/test_koyeb.py@@ -0,0 +1,313 @@+from datetime import UTC, date, datetime, timedelta, timezone+from typing import Any++from unittest.mock import MagicMock, patch++import requests+from parameterized import parameterized++from products.warehouse_sources.backend.temporal.data_imports.sources.koyeb import koyeb+from products.warehouse_sources.backend.temporal.data_imports.sources.koyeb.koyeb import (+ PAGE_SIZE,+ USAGE_WINDOW_START,+ KoyebResumeConfig,+ _build_params,+ _format_time_value,+ get_rows,+ koyeb_source,+ validate_credentials,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.koyeb.settings import KOYEB_ENDPOINTS+++class _FakeResumableManager:+ def __init__(self, state: KoyebResumeConfig | None = None) -> None:+ self._state = state+ self.saved: list[KoyebResumeConfig] = []++ def can_resume(self) -> bool:+ return self._state is not None++ def load_state(self) -> KoyebResumeConfig | None:+ return self._state++ def save_state(self, data: KoyebResumeConfig) -> None:+ self.saved.append(data)+++def _patch_fetch(monkeypatch: Any, responses: list[dict]) -> list[str]:+ """Replace _fetch_page with a queue that returns canned pages in order, recording each URL."""+ calls: list[str] = []+ queue = list(responses)++ def fake_fetch(session: Any, url: str, headers: dict[str, str], logger: Any) -> dict:+ calls.append(url)+ return queue.pop(0)++ monkeypatch.setattr(koyeb, "_fetch_page", fake_fetch)+ return calls+++def _collect(endpoint: str, manager: _FakeResumableManager, monkeypatch: Any, responses: list[dict], **kwargs: Any):+ calls = _patch_fetch(monkeypatch, responses)+ rows: list[dict] = []+ for batch in get_rows(+ api_token="t",+ endpoint=endpoint,+ logger=MagicMock(),+ resumable_source_manager=manager, # type: ignore[arg-type]+ should_use_incremental_field=kwargs.get("should_use_incremental_field", False),+ db_incremental_field_last_value=kwargs.get("db_incremental_field_last_value"),+ ):+ rows.extend(batch)+ return rows, calls+++class TestFormatTimeValue:+ @parameterized.expand(+ [+ ("naive_datetime", datetime(2024, 5, 1, 12, 30, 45), "2024-05-01T12:30:45Z"),+ ("aware_utc", datetime(2024, 5, 1, 12, 30, 45, tzinfo=UTC), "2024-05-01T12:30:45Z"),+ # Non-UTC offsets must be converted, not just re-labelled.+ (+ "aware_offset",+ datetime(2024, 5, 1, 14, 30, 45, tzinfo=timezone(timedelta(hours=2))),+ "2024-05-01T12:30:45Z",+ ),+ ("date", date(2024, 5, 1), "2024-05-01T00:00:00Z"),+ ("string_passthrough", "2024-05-01T00:00:00Z", "2024-05-01T00:00:00Z"),+ ]+ )+ def test_formats_rfc3339_utc(self, _name: str, value: Any, expected: str) -> None:+ assert _format_time_value(value) == expected+++class TestBuildParams:+ @parameterized.expand(+ [+ ("plain_endpoint", "apps", None, {"limit": PAGE_SIZE, "offset": 0}),+ # Endpoints with an `order` param are always requested ascending so offset pagination+ # stays stable while rows are appended mid-sync.+ ("ordered_endpoint", "app_events", None, {"limit": PAGE_SIZE, "offset": 0, "order": "asc"}),+ (+ "incremental_instances",+ "instances",+ datetime(2024, 5, 1, tzinfo=UTC),+ {"limit": PAGE_SIZE, "offset": 0, "order": "asc", "starting_time": "2024-05-01T00:00:00Z"},+ ),+ # apps has no server-side time filter, so a watermark must not become a query param.+ (+ "no_time_filter_drops_cutoff",+ "apps",+ datetime(2024, 5, 1, tzinfo=UTC),+ {"limit": PAGE_SIZE, "offset": 0},+ ),+ ]+ )+ def test_build_params(self, _name: str, endpoint: str, cutoff: Any, expected: dict[str, Any]) -> None:+ assert _build_params(KOYEB_ENDPOINTS[endpoint], 0, cutoff) == expected++ def test_usage_details_always_sends_required_window(self) -> None:+ # /v1/usages/details rejects requests without a time window, so both bounds must be present+ # even on a full refresh.+ params = _build_params(KOYEB_ENDPOINTS["usage_details"], 200, None, "2026-01-01T00:00:00Z")+ assert params["starting_time"] == USAGE_WINDOW_START+ assert params["ending_time"] == "2026-01-01T00:00:00Z"+ assert params["offset"] == 200+ assert params["order"] == "asc"+++class TestValidateCredentials:+ @parameterized.expand([(200, True), (401, False), (403, False), (500, False)])+ def test_status_mapping(self, status: int, expected_ok: bool) -> None:+ response = requests.Response()+ response.status_code = status+ session = MagicMock()+ session.get.return_value = response+ with patch.object(koyeb, "make_tracked_session", lambda *a, **k: session):+ ok, error = validate_credentials("token")++ assert ok is expected_ok, f"status={status}"+ assert (error is None) is expected_ok, f"status={status}"++ def test_request_exception_is_handled(self, monkeypatch: Any) -> None:+ session = MagicMock()+ session.get.side_effect = requests.ConnectionError("boom")+ monkeypatch.setattr(koyeb, "make_tracked_session", lambda *a, **k: session)++ ok, error = validate_credentials("token")+ assert ok is False+ assert error == "boom"+++class TestGetRows:+ def test_follows_offset_pagination_with_has_next(self, monkeypatch: Any) -> None:+ responses = [+ {"apps": [{"id": str(i)} for i in range(PAGE_SIZE)], "has_next": True},+ {"apps": [{"id": "last"}], "has_next": False},+ ]+ rows, calls = _collect("apps", _FakeResumableManager(), monkeypatch, responses)++ assert len(rows) == PAGE_SIZE + 1+ assert "offset=0" in calls[0]+ assert f"offset={PAGE_SIZE}" in calls[1]+ assert len(calls) == 2++ def test_short_page_without_has_next_terminates(self, monkeypatch: Any) -> None:+ # Some replies (e.g. secrets) carry no has_next; a short page is the end-of-list signal.+ responses = [{"secrets": [{"id": "s1"}, {"id": "s2"}]}]+ rows, calls = _collect("secrets", _FakeResumableManager(), monkeypatch, responses)++ assert [r["id"] for r in rows] == ["s1", "s2"]+ assert len(calls) == 1++ def test_full_page_without_has_next_fetches_until_empty_page(self, monkeypatch: Any) -> None:+ # An exact-multiple total with no has_next only stops on the following empty page.+ responses: list[dict] = [+ {"secrets": [{"id": str(i)} for i in range(PAGE_SIZE)]},+ {"secrets": []},+ ]+ rows, calls = _collect("secrets", _FakeResumableManager(), monkeypatch, responses)++ assert len(rows) == PAGE_SIZE+ assert len(calls) == 2++ def test_saves_offset_after_each_completed_page(self, monkeypatch: Any) -> None:+ responses = [+ {"apps": [{"id": str(i)} for i in range(PAGE_SIZE)], "has_next": True},+ {"apps": [{"id": str(i)} for i in range(PAGE_SIZE)], "has_next": True},+ {"apps": [{"id": "last"}], "has_next": False},+ ]+ manager = _FakeResumableManager()+ _collect("apps", manager, monkeypatch, responses)++ # No checkpoint after the final page — the walk is complete, nothing left to resume into.+ assert manager.saved == [KoyebResumeConfig(offset=PAGE_SIZE), KoyebResumeConfig(offset=PAGE_SIZE * 2)]++ def test_resumes_from_saved_offset(self, monkeypatch: Any) -> None:+ responses = [{"apps": [{"id": "1"}], "has_next": False}]+ manager = _FakeResumableManager(KoyebResumeConfig(offset=300))+ rows, calls = _collect("apps", manager, monkeypatch, responses)++ assert [r["id"] for r in rows] == ["1"]+ assert "offset=300" in calls[0]++ def test_incremental_instances_sends_starting_time(self, monkeypatch: Any) -> None:+ responses = [{"instances": [{"id": "i1"}], "has_next": False}]+ _, calls = _collect(+ "instances",+ _FakeResumableManager(),+ monkeypatch,+ responses,+ should_use_incremental_field=True,+ db_incremental_field_last_value=datetime(2024, 5, 1, tzinfo=UTC),+ )++ assert "starting_time=2024-05-01T00%3A00%3A00Z" in calls[0]+ assert "order=asc" in calls[0]++ def test_full_refresh_instances_omits_starting_time(self, monkeypatch: Any) -> None:+ responses = [{"instances": [{"id": "i1"}], "has_next": False}]+ _, calls = _collect(+ "instances",+ _FakeResumableManager(),+ monkeypatch,+ responses,+ should_use_incremental_field=False,+ db_incremental_field_last_value=datetime(2024, 5, 1, tzinfo=UTC),+ )++ assert "starting_time" not in calls[0]++ def test_deployment_definition_secrets_are_redacted(self, monkeypatch: Any) -> None:+ # Deployment definitions embed plaintext env values and config-file content; leaving them+ # in place would expose credentials to anyone with warehouse-query access.+ responses = [+ {+ "deployments": [+ {+ "id": "d1",+ "definition": {+ "env": [+ {"key": "DB_PASSWORD", "value": "hunter2"},+ {"key": "API_KEY", "secret": "my-secret-ref"},+ ],+ "config_files": [{"path": "/etc/app.conf", "content": "token=abc123"}],+ },+ }+ ],+ "has_next": False,+ }+ ]+ rows, _ = _collect("deployments", _FakeResumableManager(), monkeypatch, responses)++ env = rows[0]["definition"]["env"]+ assert env[0] == {"key": "DB_PASSWORD", "value": "[redacted by PostHog]"}+ # A secret *reference* is just a name, not the value, so it survives untouched.+ assert env[1] == {"key": "API_KEY", "secret": "my-secret-ref"}+ assert rows[0]["definition"]["config_files"][0] == {+ "path": "/etc/app.conf",+ "content": "[redacted by PostHog]",+ }++ def test_non_deployment_rows_pass_through_untouched(self, monkeypatch: Any) -> None:+ # Only definition-bearing endpoints are scrubbed; a stray `value`/`content` elsewhere stays.+ responses = [{"secrets": [{"id": "s1", "value": "keep-me"}]}]+ rows, _ = _collect("secrets", _FakeResumableManager(), monkeypatch, responses)++ assert rows[0] == {"id": "s1", "value": "keep-me"}++ def test_sample_capture_disabled_only_for_secret_scrubbed_endpoints(self, monkeypatch: Any) -> None:+ # HTTP sample capture stores the raw response body before the definition scrub runs, so+ # secret-scrubbed endpoints must opt their session out of capture while the rest stay in.+ session_kwargs: list[dict] = []++ def fake_session(**kwargs: Any) -> Any:+ session_kwargs.append(kwargs)+ return MagicMock()++ monkeypatch.setattr(koyeb, "make_tracked_session", fake_session)+ _patch_fetch(monkeypatch, [{"deployments": [], "has_next": False}, {"apps": [], "has_next": False}])+ for endpoint in ("deployments", "apps"):+ list(+ get_rows(+ api_token="t",+ endpoint=endpoint,+ logger=MagicMock(),+ resumable_source_manager=_FakeResumableManager(), # type: ignore[arg-type]+ )+ )++ assert session_kwargs == [{"capture": False}, {"capture": True}]++ def test_uses_response_data_key_per_endpoint(self, monkeypatch: Any) -> None:+ # Event streams all return their rows under "events", not the endpoint name.+ responses = [{"events": [{"id": "e1"}], "has_next": False}]+ rows, calls = _collect("deployment_events", _FakeResumableManager(), monkeypatch, responses)++ assert [r["id"] for r in rows] == ["e1"]+ assert "/v1/deployment_events" in calls[0]+++class TestKoyebSource:+ @parameterized.expand([(name,) for name in KOYEB_ENDPOINTS])+ def test_source_response_per_endpoint(self, endpoint: str) -> None:+ config = KOYEB_ENDPOINTS[endpoint]+ response = koyeb_source(+ api_token="t",+ endpoint=endpoint,+ logger=MagicMock(),+ resumable_source_manager=MagicMock(),+ )+ assert response.name == endpoint+ assert response.primary_keys == config.primary_keys+ assert response.sort_mode == "asc"+ if config.partition_key:+ assert response.partition_keys == [config.partition_key]+ assert response.partition_mode == "datetime"+ else:+ assert response.partition_keys is None++ def test_usage_details_composite_primary_key(self) -> None:+ # Usage rows have no id; dropping either half of the composite key would multi-match merges.+ assert KOYEB_ENDPOINTS["usage_details"].primary_keys == ["instance_id", "started_at"]diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/koyeb/tests/test_koyeb_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/koyeb/tests/test_koyeb_source.pynew file mode 100644index 000000000000..6733a250a27b--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/koyeb/tests/test_koyeb_source.py@@ -0,0 +1,149 @@+from typing import Any, cast++from unittest import mock+from unittest.mock import MagicMock++from parameterized import parameterized++from posthog.schema import DataWarehouseSourceCategory, ReleaseStatus, SourceFieldInputConfig++from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import SourceInputs+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs import KoyebSourceConfig+from products.warehouse_sources.backend.temporal.data_imports.sources.koyeb import source as koyeb_source_module+from products.warehouse_sources.backend.temporal.data_imports.sources.koyeb.koyeb import KoyebResumeConfig+from products.warehouse_sources.backend.temporal.data_imports.sources.koyeb.settings import ENDPOINTS+from products.warehouse_sources.backend.temporal.data_imports.sources.koyeb.source import KoyebSource+from products.warehouse_sources.backend.types import ExternalDataSourceType, IncrementalFieldType+++def _source_inputs(schema_name: str, **overrides: Any) -> SourceInputs:+ defaults: dict[str, Any] = {+ "schema_name": schema_name,+ "schema_id": "schema-id",+ "source_id": "source-id",+ "team_id": 1,+ "should_use_incremental_field": False,+ "db_incremental_field_last_value": None,+ "db_incremental_field_earliest_value": None,+ "incremental_field": None,+ "incremental_field_type": None,+ "job_id": "job-id",+ "logger": MagicMock(),+ "reset_pipeline": False,+ }+ defaults.update(overrides)+ return SourceInputs(**defaults)+++class TestKoyebSource:+ def setup_method(self) -> None:+ self.source = KoyebSource()+ self.config = KoyebSourceConfig(api_token="token")++ def test_source_type(self) -> None:+ assert self.source.source_type == ExternalDataSourceType.KOYEB++ def test_source_config_metadata(self) -> None:+ config = self.source.get_source_config+ assert config.label == "Koyeb"+ assert config.category == DataWarehouseSourceCategory.ENGINEERING___MONITORING+ assert config.releaseStatus == ReleaseStatus.ALPHA+ # Slug must agree with the posthog.com doc filename.+ assert config.docsUrl == "https://posthog.com/docs/cdp/sources/koyeb"+ # get_schemas is a static catalog, so the public docs can list tables credential-free.+ assert self.source.lists_tables_without_credentials is True++ def test_source_config_fields(self) -> None:+ fields = {f.name: cast(SourceFieldInputConfig, f) for f in self.source.get_source_config.fields}+ assert set(fields) == {"api_token"}+ assert fields["api_token"].required is True+ assert fields["api_token"].secret is True++ def test_get_schemas_incremental_only_for_instances(self) -> None:+ schemas = {s.name: s for s in self.source.get_schemas(self.config, team_id=1)}+ assert set(schemas) == set(ENDPOINTS)++ instances = schemas["instances"]+ assert instances.supports_incremental is True+ assert instances.supports_append is True+ assert [f["field"] for f in instances.incremental_fields] == ["created_at"]+ assert instances.incremental_fields[0]["field_type"] == IncrementalFieldType.DateTime++ for name, schema in schemas.items():+ if name == "instances":+ continue+ assert schema.supports_incremental is False, name+ assert schema.incremental_fields == [], name++ def test_get_schemas_filters_by_names(self) -> None:+ schemas = self.source.get_schemas(self.config, team_id=1, names=["apps"])+ assert [s.name for s in schemas] == ["apps"]++ @parameterized.expand([("valid", (True, None)), ("invalid", (False, "Invalid or unauthorized Koyeb API token"))])+ def test_validate_credentials_delegates(self, _name: str, result: tuple) -> None:+ with mock.patch.object(koyeb_source_module, "validate_koyeb_credentials", lambda token: result):+ assert self.source.validate_credentials(self.config, team_id=1) == result++ @parameterized.expand(+ [+ ("unauthorized", "401 Client Error: Unauthorized for url: https://app.koyeb.com/v1/apps?limit=100"),+ ("forbidden", "403 Client Error: Forbidden for url: https://app.koyeb.com/v1/instances?limit=100"),+ ]+ )+ def test_credential_errors_are_non_retryable(self, _name: str, observed_error: str) -> None:+ non_retryable = self.source.get_non_retryable_errors()+ assert any(key in observed_error for key in non_retryable)++ @parameterized.expand(+ [+ ("rate_limit", "429 Client Error: Too Many Requests for url: https://app.koyeb.com/v1/apps"),+ ("server_error", "500 Server Error: Internal Server Error for url: https://app.koyeb.com/v1/apps"),+ ("read_timeout", "HTTPSConnectionPool(host='app.koyeb.com', port=443): Read timed out."),+ ]+ )+ def test_transient_errors_remain_retryable(self, _name: str, other_error: str) -> None:+ non_retryable = self.source.get_non_retryable_errors()+ assert not any(key in other_error for key in non_retryable)++ def test_get_resumable_source_manager_binds_data_class(self) -> None:+ manager = self.source.get_resumable_source_manager(_source_inputs("apps"))+ assert isinstance(manager, ResumableSourceManager)+ assert manager._data_class is KoyebResumeConfig++ def test_source_for_pipeline_plumbs_arguments(self) -> None:+ captured: dict[str, Any] = {}++ def fake_koyeb_source(**kwargs: Any):+ captured.update(kwargs)+ return MagicMock(name="source_response")++ manager = MagicMock()+ inputs = _source_inputs(+ "instances",+ should_use_incremental_field=True,+ db_incremental_field_last_value="2024-05-01T00:00:00Z",+ incremental_field="created_at",+ )++ with mock.patch.object(koyeb_source_module, "koyeb_source", fake_koyeb_source):+ self.source.source_for_pipeline(self.config, manager, inputs)++ assert captured["api_token"] == "token"+ assert captured["endpoint"] == "instances"+ assert captured["should_use_incremental_field"] is True+ assert captured["db_incremental_field_last_value"] == "2024-05-01T00:00:00Z"+ assert captured["resumable_source_manager"] is manager++ def test_source_for_pipeline_omits_last_value_when_not_incremental(self) -> None:+ captured: dict[str, Any] = {}++ def fake_koyeb_source(**kwargs: Any):+ captured.update(kwargs)+ return MagicMock()++ inputs = _source_inputs("apps", should_use_incremental_field=False, db_incremental_field_last_value="stale")+ with mock.patch.object(koyeb_source_module, "koyeb_source", fake_koyeb_source):+ self.source.source_for_pipeline(self.config, MagicMock(), inputs)++ assert captured["db_incremental_field_last_value"] is None