: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 fly_io import source (#70000)
Tom Owers182dd44d7693
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.mdindex 40fecfa90ac7..4bf9fcf3ab20 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md@@ -178,6 +178,7 @@ the row lists both.| firehydrant | HTTP | requests | ✅ || flexmail | HTTP | requests | ✅ || float_app | HTTP | requests | ✅ |+| fly_io | HTTP | requests | ✅ || front | HTTP | requests | ✅ || fulcrum | HTTP | requests | ✅ || fullstory | HTTP | requests | ✅ |@@ -562,7 +563,6 @@ doesn't conflict with concurrent PRs.- flexmail- flexport- flowlu-- fly_io- formbricks- freeagent- freightviewdiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/fly_io/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/fly_io/canonical_descriptions.pynew file mode 100644index 000000000000..3d742613a8d3--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/fly_io/canonical_descriptions.py@@ -0,0 +1,68 @@+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (+ CanonicalDescriptions,+)++# Descriptions sourced from the Fly.io Machines API docs (https://fly.io/docs/machines/api/).+# Keyed by endpoint/schema name (matching ENDPOINTS). Any column not listed here falls back to+# LLM enrichment, which is given the source name, endpoint, docs_url, and column data types.+CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {+ "apps": {+ "description": "Fly.io apps in the organization. An app is the top-level unit that groups machines, volumes, and networking.",+ "docs_url": "https://fly.io/docs/machines/api/apps-resource/",+ "columns": {+ "id": "Unique identifier for the app.",+ "internal_numeric_id": "Fly.io internal numeric identifier for the app.",+ "name": "The app name (globally unique across Fly.io).",+ "machine_count": "Number of machines currently belonging to the app.",+ "volume_count": "Number of volumes currently belonging to the app.",+ "network": "Name of the private network the app's machines are attached to.",+ "organization": "Organization the app belongs to (slug, name, and internal numeric id).",+ "status": "Current status of the app (e.g. deployed, suspended, pending).",+ },+ },+ "machines": {+ "description": "Fly.io machines (Firecracker microVMs) across the organization, one row per machine with its owning app.",+ "docs_url": "https://fly.io/docs/machines/api/machines-resource/",+ "columns": {+ "id": "Unique identifier for the machine.",+ "app_name": "Name of the app this machine belongs to.",+ "name": "Human-readable machine name.",+ "state": "Current lifecycle state (e.g. started, stopped, suspended, destroyed).",+ "region": "Fly.io region the machine runs in (e.g. iad, lhr, syd).",+ "private_ip": "The machine's private IPv6 address on the app's network.",+ "config": "The machine configuration overview (guest resources, image, and services). Secret-bearing fields are excluded: environment variables, secrets, inline file contents, user-defined metadata (only Fly's own platform keys are kept), and request headers on services and checks.",+ "version": "Version identifier of the machine's current configuration.",+ "created_at": "Timestamp the machine was created (RFC 3339).",+ "updated_at": "Timestamp the machine was last updated (RFC 3339).",+ },+ },+ "volumes": {+ "description": "Fly.io volumes (persistent storage) across the organization, one row per volume with its owning app.",+ "docs_url": "https://fly.io/docs/machines/api/volumes-resource/",+ "columns": {+ "id": "Unique identifier for the volume.",+ "app_name": "Name of the app this volume belongs to.",+ "name": "Human-readable volume name.",+ "state": "Current state of the volume (e.g. created, pending_destroy).",+ "region": "Fly.io region the volume is stored in.",+ "zone": "Hardware zone within the region hosting the volume.",+ "size_gb": "Provisioned size of the volume in gigabytes.",+ "encrypted": "Whether the volume is encrypted at rest.",+ "fstype": "Filesystem type of the volume (e.g. ext4).",+ "auto_backup_enabled": "Whether automatic daily snapshots are enabled.",+ "snapshot_retention": "Number of days snapshots are retained.",+ "attached_machine_id": "ID of the machine the volume is currently attached to, if any.",+ "attached_alloc_id": "ID of the allocation the volume is attached to (legacy apps).",+ "block_size": "Block size of the volume's filesystem, in bytes.",+ "blocks": "Total number of filesystem blocks.",+ "blocks_free": "Number of free filesystem blocks.",+ "blocks_avail": "Number of filesystem blocks available to unprivileged users.",+ "bytes_total": "Total capacity of the volume in bytes.",+ "bytes_used": "Bytes currently used on the volume.",+ "host_status": "Status of the host machine backing the volume.",+ "type": "Storage type of the volume.",+ "created_at": "Timestamp the volume was created (RFC 3339).",+ "updated_at": "Timestamp the volume was last updated (RFC 3339).",+ },+ },+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/fly_io/fly_io.py b/products/warehouse_sources/backend/temporal/data_imports/sources/fly_io/fly_io.pynew file mode 100644index 000000000000..28e6c92e33f4--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/fly_io/fly_io.py@@ -0,0 +1,262 @@+from collections.abc import Iterator+from typing import Any+from urllib.parse import quote, 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.fly_io.settings import (+ FLY_IO_ENDPOINTS,+ FlyIoEndpointConfig,+)++FLY_IO_BASE_URL = "https://api.machines.dev/v1"++# Advisory page size for the cursor-paginated org endpoints (the API caps it at 1000).+_PAGE_SIZE = 1000++# Hard cap on pages walked per stream so a misbehaving cursor can't loop forever.+_MAX_PAGES = 1000++# A Fly machine's `config` can embed deployment secrets, so we sync only an operational+# allowlist (the "overview" the canonical description promises) rather than the raw object.+# Anything not listed here — notably `env`, `files` (whose entries carry inline file+# contents in `raw_value`), and `secrets` — is dropped before the row reaches the warehouse.+_SAFE_MACHINE_CONFIG_KEYS = frozenset(+ {+ "guest",+ "image",+ "metadata",+ "services",+ "checks",+ "restart",+ "mounts",+ "metrics",+ "init",+ "processes",+ "auto_destroy",+ "schedule",+ "dns",+ "size",+ "standbys",+ "statics",+ "stop_config",+ }+)++# A machine's per-process config entries repeat the same secret vectors as the top level.+_PROCESS_SECRET_KEYS = frozenset({"env", "secrets"})++# `metadata` is a free-form user key/value map, so a value like `metadata.api_token` would+# otherwise reach the warehouse. Only Fly's own platform-set keys are known-safe; everything+# else is dropped.+_SAFE_METADATA_KEYS = frozenset(+ {+ "fly_platform_version",+ "fly_process_group",+ "fly_release_id",+ "fly_release_version",+ "fly_flyctl_version",+ "fly_managed_postgres",+ }+)+++class FlyIoRetryableError(Exception):+ pass+++def _strip_headers(value: Any) -> Any:+ """Recursively drop every `headers` mapping from a nested structure. Fly service and check+ definitions can carry request headers (e.g. a health-check `Authorization`), a credential+ vector we never want to land in the warehouse."""+ if isinstance(value, dict):+ return {key: _strip_headers(item) for key, item in value.items() if key != "headers"}+ if isinstance(value, list):+ return [_strip_headers(item) for item in value]+ return value+++def _sanitize_machine_config(config: dict[str, Any]) -> dict[str, Any]:+ safe = {key: value for key, value in config.items() if key in _SAFE_MACHINE_CONFIG_KEYS}+ # `metadata` is user-defined free-form key/values; keep only Fly's own platform keys so a+ # user-set secret (e.g. `metadata.api_token`) can't slip through the allowlist.+ metadata = safe.get("metadata")+ if isinstance(metadata, dict):+ safe["metadata"] = {key: value for key, value in metadata.items() if key in _SAFE_METADATA_KEYS}+ # `processes` is operational (cmd/entrypoint/guest) but each entry can carry its own+ # `env`/`secrets`, so strip those while keeping the rest of the process definition.+ processes = safe.get("processes")+ if isinstance(processes, list):+ safe["processes"] = [+ {key: value for key, value in process.items() if key not in _PROCESS_SECRET_KEYS}+ if isinstance(process, dict)+ else process+ for process in processes+ ]+ # Final defensive pass: `services`/`checks` (and anything nested under them) can embed+ # request-header maps that carry credentials — drop them wherever they appear.+ return _strip_headers(safe)+++def _sanitize_machine(row: dict[str, Any]) -> dict[str, Any]:+ config = row.get("config")+ if isinstance(config, dict):+ return {**row, "config": _sanitize_machine_config(config)}+ return row+++def _get_headers(api_token: str) -> dict[str, str]:+ return {+ "Authorization": f"Bearer {api_token}",+ "Accept": "application/json",+ }+++def _build_url(config: FlyIoEndpointConfig, org_slug: str, params: dict[str, Any]) -> str:+ """Build the request URL for an endpoint. Org-scoped endpoints carry the org in the path;+ the apps endpoint takes it as a required query param instead."""+ if "{org_slug}" in config.path:+ # Encode the slug so a reserved character (e.g. `/`) can't retarget the request to a+ # different API path than the one credential validation checked.+ path = config.path.format(org_slug=quote(org_slug, safe=""))+ query = dict(params)+ else:+ path = config.path+ query = {"org_slug": org_slug, **params}+ url = f"{FLY_IO_BASE_URL}{path}"+ if query:+ url = f"{url}?{urlencode(query)}"+ return url+++@retry(+ # ChunkedEncodingError is a mid-stream connection break (a truncated chunked body); it's+ # transient like ConnectionError/ReadTimeout but not a ConnectionError subclass.+ retry=retry_if_exception_type(+ (+ FlyIoRetryableError,+ requests.ReadTimeout,+ requests.ConnectionError,+ requests.exceptions.ChunkedEncodingError,+ )+ ),+ stop=stop_after_attempt(5),+ wait=wait_exponential_jitter(initial=1, max=30),+ reraise=True,+)+def _fetch_page(+ session: requests.Session, url: str, headers: dict[str, str], logger: FilteringBoundLogger+) -> dict[str, Any]:+ response = session.get(url, headers=headers, timeout=60)++ # 429 (rate limited) and 5xx are transient — retry with backoff.+ if response.status_code == 429 or response.status_code >= 500:+ raise FlyIoRetryableError(f"Fly.io API error (retryable): status={response.status_code}, url={url}")++ if not response.ok:+ logger.error(f"Fly.io API error: status={response.status_code}, body={response.text}, url={url}")+ response.raise_for_status()++ data = response.json()+ # Every list endpoint we sync wraps its rows in an object ({"apps": [...]} etc.). A bare list+ # or scalar is an unexpected shape: fail loudly rather than silently syncing zero rows, which+ # would look like a successful-but-empty sync if Fly.io ever changed the wrapper.+ if not isinstance(data, dict):+ raise ValueError(f"Fly.io API returned an unexpected response shape: {type(data).__name__}")+ return data+++def validate_credentials(api_token: str, org_slug: str) -> tuple[bool, str | None]:+ """Probe the apps endpoint to confirm the token is genuine and the org is reachable."""+ url = _build_url(FLY_IO_ENDPOINTS["apps"], org_slug, {})+ try:+ response = make_tracked_session().get(url, 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 == 401:+ return False, "Invalid Fly.io API token. Create a new token with `fly tokens create org` and reconnect."+ if response.status_code in (403, 404):+ return False, f"Organization '{org_slug}' was not found or is not accessible with this token."++ try:+ message = response.json().get("error", response.text)+ except ValueError:+ message = response.text+ return False, message+++def get_rows(+ api_token: str,+ endpoint: str,+ org_slug: str,+ logger: FilteringBoundLogger,+) -> Iterator[list[dict[str, Any]]]:+ """Yield one page of rows at a time. The org machines/volumes endpoints paginate with an+ opaque `next_cursor`; the apps endpoint returns everything in a single response. Rows are+ yielded in the shape the API returns them (flat objects, with nested config/organization kept+ as-is) — the pipeline batches and writes them."""+ config = FLY_IO_ENDPOINTS[endpoint]+ headers = _get_headers(api_token)+ # One session reused across pages so urllib3 keeps the connection alive between requests.+ # A stream whose bodies can carry secrets opts out of HTTP sample capture (still logged+ # and metered) so those secrets never land in the sample-capture pipeline.+ session = make_tracked_session(capture=not config.redact_secrets)++ params: dict[str, Any] = {"limit": _PAGE_SIZE} if config.paginated else {}+ url = _build_url(config, org_slug, params)++ pages = 0+ while True:+ data = _fetch_page(session, url, headers, logger)++ items = data.get(config.response_data_path) or []+ if config.redact_secrets:+ items = [_sanitize_machine(item) for item in items]+ if items:+ yield items++ if not config.paginated:+ break++ next_cursor = data.get("next_cursor")+ if not next_cursor:+ break++ pages += 1+ if pages >= _MAX_PAGES:+ logger.warning(+ "Fly.io: pagination cap reached; remaining pages skipped",+ endpoint=endpoint,+ max_pages=_MAX_PAGES,+ )+ break++ url = _build_url(config, org_slug, {**params, "cursor": next_cursor})+++def fly_io_source(+ api_token: str,+ endpoint: str,+ org_slug: str,+ logger: FilteringBoundLogger,+) -> SourceResponse:+ config = FLY_IO_ENDPOINTS[endpoint]++ return SourceResponse(+ name=endpoint,+ items=lambda: get_rows(api_token=api_token, endpoint=endpoint, org_slug=org_slug, logger=logger),+ primary_keys=config.primary_keys,+ sort_mode="asc",+ partition_count=1,+ partition_size=1,+ partition_mode="datetime" if config.partition_key else None,+ partition_format="week" if config.partition_key else None,+ partition_keys=[config.partition_key] if config.partition_key else None,+ )diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/fly_io/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/fly_io/settings.pynew file mode 100644index 000000000000..0414674c6f18--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/fly_io/settings.py@@ -0,0 +1,67 @@+from dataclasses import dataclass, field+from typing import Optional++from products.warehouse_sources.backend.types import IncrementalField+++@dataclass+class FlyIoEndpointConfig:+ name: str+ # Path template relative to the API base. `{org_slug}` is substituted with the configured+ # organization for the org-scoped endpoints; the apps endpoint takes org_slug as a query+ # param instead (see `_build_url` in fly_io.py).+ path: str+ # Body key the list of rows lives under (e.g. {"apps": [...]}, {"machines": [...]}).+ response_data_path: str+ primary_keys: list[str] = field(default_factory=lambda: ["id"])+ # Stable creation timestamp used for datetime partitioning. None disables partitioning —+ # Fly.io app objects carry no timestamp at all.+ partition_key: Optional[str] = None+ # True when the endpoint returns a `next_cursor` and accepts a `cursor` query param.+ paginated: bool = False+ # True when rows can embed deployment secrets (a machine's `config` carries env vars,+ # per-process env, and inline file contents). Such a stream is reduced to a safe+ # operational allowlist before it's yielded and excluded from HTTP sample capture, so+ # secrets never reach the warehouse or the sample-capture pipeline.+ redact_secrets: bool = False+++# Fly.io streams. We use the org-level aggregate endpoints for machines and volumes+# (GET /orgs/{org_slug}/machines, GET /orgs/{org_slug}/volumes) rather than fanning out+# per app: each returns every resource in the org in one cursor-paginated call and stamps+# `app_name` onto each row, so it carries the app context without an extra request per app+# (which also stays well within Fly.io's per-action rate limits for orgs with many apps).+FLY_IO_ENDPOINTS: dict[str, FlyIoEndpointConfig] = {+ "apps": FlyIoEndpointConfig(+ name="apps",+ path="/apps",+ response_data_path="apps",+ # App objects have no created_at/updated_at, so datetime partitioning isn't possible.+ partition_key=None,+ paginated=False,+ ),+ "machines": FlyIoEndpointConfig(+ name="machines",+ path="/orgs/{org_slug}/machines",+ response_data_path="machines",+ partition_key="created_at",+ paginated=True,+ redact_secrets=True,+ ),+ "volumes": FlyIoEndpointConfig(+ name="volumes",+ path="/orgs/{org_slug}/volumes",+ response_data_path="volumes",+ partition_key="created_at",+ paginated=True,+ ),+}++ENDPOINTS = tuple(FLY_IO_ENDPOINTS.keys())++# Fly.io exposes no verified server-side timestamp filter for these streams. The org+# machines/volumes endpoints document an `updated_after` param, but the API states `cursor`+# takes precedence over it (so it can only bound the first page) and we could not curl-verify+# it actually filters. So every stream is full-refresh only and advertises no incremental+# fields. Resource counts per org are small, so a full refresh each sync is cheap.+INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {name: [] for name in FLY_IO_ENDPOINTS}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/fly_io/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/fly_io/source.pyindex b355aae215c4..61b6372ef752 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/fly_io/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/fly_io/source.py@@ -1,31 +1,134 @@-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.pipelines.pipeline.typings import (+ SourceInputs,+ SourceResponse,+)from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, SimpleSource+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.schema import SourceSchema+from products.warehouse_sources.backend.temporal.data_imports.sources.fly_io.fly_io import (+ fly_io_source,+ validate_credentials as validate_fly_io_credentials,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.fly_io.settings import FLY_IO_ENDPOINTSfrom products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs import FlyIoSourceConfigfrom products.warehouse_sources.backend.types import ExternalDataSourceType@SourceRegistry.registerclass FlyIoSource(SimpleSource[FlyIoSourceConfig]):+ lists_tables_without_credentials = True # static endpoint catalog — safe for public docs+@propertydef source_type(self) -> ExternalDataSourceType:return ExternalDataSourceType.FLYIO+ @property+ def connection_host_fields(self) -> list[str]:+ # The stored token is scoped to an org, but the slug decides which org's apps/machines/volumes+ # get synced. Changing it must re-require the token so an editor can't retarget the preserved+ # token at another org it happens to reach.+ return ["organization_slug"]+@propertydef get_source_config(self) -> SourceConfig:return SourceConfig(name=SchemaExternalDataSourceType.FLY_IO,category=DataWarehouseSourceCategory.ENGINEERING___MONITORING,label="Fly.io",+ releaseStatus=ReleaseStatus.ALPHA,+ caption="""Sync your Fly.io apps, machines, and volumes into the PostHog Data warehouse.++Create an organization-scoped token with `fly tokens create org` (or from the **Tokens** section of your Fly.io dashboard) and paste it below. A read-only org token is sufficient.""",iconPath="/static/services/fly_io.png",+ docsUrl="https://posthog.com/docs/cdp/sources/fly-io",keywords=["fly", "machines", "infrastructure", "cloud"],- fields=cast(list[FieldType], []),- unreleasedSource=True,+ fields=cast(+ list[FieldType],+ [+ SourceFieldInputConfig(+ name="api_token",+ label="API token",+ type=SourceFieldInputConfigType.PASSWORD,+ required=True,+ placeholder="FlyV1 ...",+ secret=True,+ ),+ SourceFieldInputConfig(+ name="organization_slug",+ label="Organization slug",+ type=SourceFieldInputConfigType.TEXT,+ required=True,+ placeholder="personal",+ caption="Your Fly.io organization slug — use `personal` for your personal org. Find it with `fly orgs list`.",+ secret=False,+ ),+ ],+ ),+ )++ def get_canonical_descriptions(self) -> CanonicalDescriptions:+ from products.warehouse_sources.backend.temporal.data_imports.sources.fly_io.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 an HTTPError when `_fetch_page`+ # calls `raise_for_status()`. Retrying can never satisfy a credential problem, so stop+ # the sync. Match the stable status text and base host, not the per-request path.+ "401 Client Error: Unauthorized for url: https://api.machines.dev": "Your Fly.io API token is invalid or expired. Create a new token with `fly tokens create org` and reconnect.",+ "403 Client Error: Forbidden for url: https://api.machines.dev": "Your Fly.io API token does not have access to this organization or resource. Check the token's scope and reconnect.",+ }++ def get_schemas(+ self,+ config: FlyIoSourceConfig,+ team_id: int,+ with_counts: bool = False,+ names: list[str] | None = None,+ force_refresh: bool = False,+ ) -> list[SourceSchema]:+ schemas = [+ SourceSchema(+ name=name,+ # Fly.io has no verified server-side time filter for any stream, so full refresh only.+ supports_incremental=False,+ supports_append=False,+ incremental_fields=[],+ detected_primary_keys=endpoint_config.primary_keys,+ )+ for name, endpoint_config in FLY_IO_ENDPOINTS.items()+ ]+ 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: FlyIoSourceConfig, team_id: int, schema_name: Optional[str] = None+ ) -> tuple[bool, str | None]:+ return validate_fly_io_credentials(config.api_token, config.organization_slug)++ def source_for_pipeline(self, config: FlyIoSourceConfig, inputs: SourceInputs) -> SourceResponse:+ return fly_io_source(+ api_token=config.api_token,+ endpoint=inputs.schema_name,+ org_slug=config.organization_slug,+ logger=inputs.logger,)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/fly_io/tests/test_fly_io.py b/products/warehouse_sources/backend/temporal/data_imports/sources/fly_io/tests/test_fly_io.pynew file mode 100644index 000000000000..5a1976b03a29--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/fly_io/tests/test_fly_io.py@@ -0,0 +1,312 @@+from typing import Any++import pytest+from unittest.mock import MagicMock, patch++import requests+from parameterized import parameterized++from products.warehouse_sources.backend.temporal.data_imports.sources.fly_io import fly_io+from products.warehouse_sources.backend.temporal.data_imports.sources.fly_io.fly_io import (+ FLY_IO_ENDPOINTS,+ _build_url,+ _sanitize_machine,+ fly_io_source,+ get_rows,+ validate_credentials,+)+++class TestBuildUrl:+ @parameterized.expand(+ [+ # Org-scoped endpoints carry the org in the path; getting this wrong (leaving the+ # {org_slug} placeholder, or putting the org in a query param) 404s every request.+ ("machines", "https://api.machines.dev/v1/orgs/acme/machines?limit=1000"),+ ("volumes", "https://api.machines.dev/v1/orgs/acme/volumes?limit=1000"),+ ]+ )+ def test_org_scoped_endpoint_puts_org_in_path(self, endpoint: str, expected: str) -> None:+ config = FLY_IO_ENDPOINTS[endpoint]+ url = _build_url(config, "acme", {"limit": 1000})+ assert url == expected++ def test_apps_endpoint_puts_org_in_query(self) -> None:+ # The apps endpoint takes org_slug as a required query param, not a path segment.+ url = _build_url(FLY_IO_ENDPOINTS["apps"], "acme", {})+ assert url == "https://api.machines.dev/v1/apps?org_slug=acme"++ def test_reserved_char_in_slug_is_encoded_in_path(self) -> None:+ # A slug carrying a path-reserved char must be percent-encoded, otherwise it could retarget+ # the request to a different API path than the one credential validation checked.+ url = _build_url(FLY_IO_ENDPOINTS["machines"], "ac/me", {"limit": 1000})+ assert url == "https://api.machines.dev/v1/orgs/ac%2Fme/machines?limit=1000"+++class TestValidateCredentials:+ @parameterized.expand(+ [+ (200, True),+ (401, False),+ (403, False),+ (404, False),+ (500, False),+ ]+ )+ def test_status_maps_to_validity(self, status_code: int, expected_valid: bool) -> None:+ response = MagicMock()+ response.status_code = status_code+ response.json.return_value = {"error": "boom"}+ session = MagicMock()+ session.get.return_value = response+ with patch.object(fly_io, "make_tracked_session", return_value=session):+ valid, error = validate_credentials("tok", "acme")+ assert valid is expected_valid+ assert (error is None) is expected_valid++ def test_network_error_is_not_valid(self) -> None:+ session = MagicMock()+ session.get.side_effect = requests.ConnectionError("no route")+ with patch.object(fly_io, "make_tracked_session", return_value=session):+ valid, error = validate_credentials("tok", "acme")+ assert valid is False+ assert error is not None+++class TestFetchPageRetries:+ @parameterized.expand(+ [+ ("rate_limited", 429),+ ("server_error", 503),+ ]+ )+ def test_retryable_status_retries_then_succeeds(self, _name: str, bad_status: int) -> None:+ # A 429/5xx on the first attempt must retry rather than fail the whole sync.+ bad = MagicMock()+ bad.status_code = bad_status+ good = MagicMock()+ good.status_code = 200+ good.ok = True+ good.json.return_value = {"machines": []}+ session = MagicMock()+ session.get.side_effect = [bad, good]++ with patch.object(fly_io._fetch_page.retry, "sleep", lambda *_: None): # type: ignore[attr-defined]+ result = fly_io._fetch_page(session, "https://api.machines.dev/v1/orgs/a/machines", {}, MagicMock())++ assert result == {"machines": []}+ assert session.get.call_count == 2++ def test_client_error_raises_and_is_not_retried(self) -> None:+ # A 401 is a credential problem — surface it immediately (get_non_retryable_errors handles it),+ # never burn 5 retries on it.+ response = MagicMock()+ response.status_code = 401+ response.ok = False+ response.raise_for_status.side_effect = requests.HTTPError("401 Client Error", response=response)+ session = MagicMock()+ session.get.return_value = response++ with pytest.raises(requests.HTTPError):+ fly_io._fetch_page(session, "https://api.machines.dev/v1/orgs/a/machines", {}, MagicMock())+ assert session.get.call_count == 1++ def test_unexpected_response_shape_raises(self) -> None:+ # A bare list where an object wrapper is expected must fail loudly, not silently sync zero rows.+ response = MagicMock()+ response.status_code = 200+ response.ok = True+ response.json.return_value = [{"id": "x"}]+ session = MagicMock()+ session.get.return_value = response++ with pytest.raises(ValueError):+ fly_io._fetch_page(session, "https://api.machines.dev/v1/apps", {}, MagicMock())+++class TestGetRows:+ @staticmethod+ def _collect(endpoint: str, pages: dict[str, dict[str, Any]]) -> list[dict]:+ def fake_fetch(session: Any, url: str, headers: dict[str, str], logger: Any) -> dict:+ return pages[url]++ rows: list[dict] = []+ with patch.object(fly_io, "make_tracked_session", return_value=MagicMock()):+ with patch.object(fly_io, "_fetch_page", side_effect=fake_fetch):+ for batch in get_rows(api_token="tok", endpoint=endpoint, org_slug="acme", logger=MagicMock()):+ rows.extend(batch)+ return rows++ def test_apps_is_single_request_and_ignores_cursor(self) -> None:+ # The apps endpoint isn't paginated; a stray next_cursor must not trigger a second request+ # against a cursor the endpoint doesn't accept.+ pages = {+ "https://api.machines.dev/v1/apps?org_slug=acme": {+ "apps": [{"id": "app1"}, {"id": "app2"}],+ "next_cursor": "should-be-ignored",+ },+ }+ assert self._collect("apps", pages) == [{"id": "app1"}, {"id": "app2"}]++ def test_machines_follows_cursor_until_exhausted(self) -> None:+ # Not advancing the cursor loops forever; not following it silently drops later pages.+ pages = {+ "https://api.machines.dev/v1/orgs/acme/machines?limit=1000": {+ "machines": [{"id": "m1", "app_name": "app1"}],+ "next_cursor": "c2",+ },+ "https://api.machines.dev/v1/orgs/acme/machines?limit=1000&cursor=c2": {+ "machines": [{"id": "m2", "app_name": "app2"}],+ "next_cursor": "",+ },+ }+ rows = self._collect("machines", pages)+ assert [r["id"] for r in rows] == ["m1", "m2"]++ def test_empty_response_yields_no_rows(self) -> None:+ pages: dict[str, dict[str, Any]] = {+ "https://api.machines.dev/v1/orgs/acme/volumes?limit=1000": {"volumes": [], "next_cursor": None},+ }+ assert self._collect("volumes", pages) == []+++class TestMachineSecretRedaction:+ def test_sanitize_strips_secret_bearing_config_fields(self) -> None:+ # env, files (inline file contents), and secrets would land deployment credentials in the+ # warehouse where any project member with query access could read them — they must be dropped.+ row = {+ "id": "m1",+ "config": {+ "image": "flyio/app:latest",+ "guest": {"cpus": 1, "memory_mb": 256},+ "env": {"DATABASE_URL": "postgres://user:pass@host/db"},+ "secrets": [{"name": "STRIPE_KEY"}],+ "files": [{"guest_path": "/etc/cert.pem", "raw_value": "c3VwZXItc2VjcmV0"}],+ "processes": [+ {"cmd": ["run"], "env": {"TOKEN": "shhh"}, "secrets": [{"name": "X"}]},+ ],+ },+ }+ sanitized = _sanitize_machine(row)+ config = sanitized["config"]+ assert config["image"] == "flyio/app:latest"+ assert config["guest"] == {"cpus": 1, "memory_mb": 256}+ assert "env" not in config+ assert "secrets" not in config+ assert "files" not in config+ # Processes stay (cmd is operational) but their nested secret vectors are stripped.+ assert config["processes"] == [{"cmd": ["run"]}]+ # The original row is not mutated in place.+ assert "env" in row["config"]++ def test_sanitize_keeps_only_platform_metadata_keys(self) -> None:+ # Fly metadata is a free-form user map, so a user-set secret must not survive; only Fly's+ # own platform keys are known-safe and kept.+ row = {+ "id": "m1",+ "config": {+ "image": "app",+ "metadata": {+ "fly_process_group": "web",+ "fly_release_id": "rel_123",+ "api_token": "FlyV1 super-secret",+ "DATABASE_PASSWORD": "hunter2",+ },+ },+ }+ metadata = _sanitize_machine(row)["config"]["metadata"]+ assert metadata == {"fly_process_group": "web", "fly_release_id": "rel_123"}++ def test_sanitize_strips_request_headers_from_services_and_checks(self) -> None:+ # Service/check request headers can carry an Authorization credential, so every nested+ # `headers` map must be dropped while the rest of the networking config is kept.+ row = {+ "id": "m1",+ "config": {+ "image": "app",+ "services": [+ {+ "internal_port": 8080,+ "checks": [+ {+ "type": "http",+ "path": "/health",+ "headers": [{"name": "Authorization", "value": "Bearer secret"}],+ }+ ],+ }+ ],+ "checks": {"web": {"type": "http", "path": "/", "headers": [{"name": "X-Token", "value": "shhh"}]}},+ },+ }+ config = _sanitize_machine(row)["config"]+ assert config["services"] == [{"internal_port": 8080, "checks": [{"type": "http", "path": "/health"}]}]+ assert config["checks"] == {"web": {"type": "http", "path": "/"}}++ def test_sanitize_leaves_row_without_config_untouched(self) -> None:+ row = {"id": "m1", "state": "started"}+ assert _sanitize_machine(row) == row++ def test_machines_stream_sanitizes_rows_and_disables_sample_capture(self) -> None:+ # End-to-end wiring: the machines stream must both redact secrets from every yielded row and+ # opt out of HTTP sample capture, so secrets reach neither the warehouse nor the sample pipeline.+ pages = {+ "https://api.machines.dev/v1/orgs/acme/machines?limit=1000": {+ "machines": [{"id": "m1", "config": {"image": "app", "env": {"SECRET": "x"}}}],+ "next_cursor": None,+ },+ }++ def fake_fetch(session: Any, url: str, headers: dict[str, str], logger: Any) -> dict:+ return pages[url]++ rows: list[dict] = []+ with patch.object(fly_io, "make_tracked_session", return_value=MagicMock()) as mock_session:+ with patch.object(fly_io, "_fetch_page", side_effect=fake_fetch):+ for batch in get_rows(api_token="tok", endpoint="machines", org_slug="acme", logger=MagicMock()):+ rows.extend(batch)++ assert rows == [{"id": "m1", "config": {"image": "app"}}]+ mock_session.assert_called_once_with(capture=False)++ def test_non_secret_stream_keeps_sample_capture_and_rows_verbatim(self) -> None:+ # Volumes carry no secrets, so their session must keep capture on and rows pass through unchanged.+ pages = {+ "https://api.machines.dev/v1/orgs/acme/volumes?limit=1000": {+ "volumes": [{"id": "v1", "encrypted": True}],+ "next_cursor": None,+ },+ }++ def fake_fetch(session: Any, url: str, headers: dict[str, str], logger: Any) -> dict:+ return pages[url]++ rows: list[dict] = []+ with patch.object(fly_io, "make_tracked_session", return_value=MagicMock()) as mock_session:+ with patch.object(fly_io, "_fetch_page", side_effect=fake_fetch):+ for batch in get_rows(api_token="tok", endpoint="volumes", org_slug="acme", logger=MagicMock()):+ rows.extend(batch)++ assert rows == [{"id": "v1", "encrypted": True}]+ mock_session.assert_called_once_with(capture=True)+++class TestFlyIoSourceResponse:+ @parameterized.expand(+ [+ ("machines", "created_at"),+ ("volumes", "created_at"),+ ]+ )+ def test_timestamped_endpoints_partition_on_created_at(self, endpoint: str, partition_key: str) -> None:+ response = fly_io_source(api_token="tok", endpoint=endpoint, org_slug="acme", logger=MagicMock())+ assert response.partition_mode == "datetime"+ assert response.partition_keys == [partition_key]+ assert response.primary_keys == ["id"]++ def test_apps_has_no_partitioning(self) -> None:+ # App objects carry no timestamp, so partitioning on a nonexistent column would break the sync.+ response = fly_io_source(api_token="tok", endpoint="apps", org_slug="acme", logger=MagicMock())+ assert response.partition_mode is None+ assert response.partition_keys is None+ assert response.primary_keys == ["id"]diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/fly_io/tests/test_fly_io_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/fly_io/tests/test_fly_io_source.pynew file mode 100644index 000000000000..51df60d96c13--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/fly_io/tests/test_fly_io_source.py@@ -0,0 +1,121 @@+from unittest.mock import MagicMock, patch++from parameterized import parameterized++from posthog.schema import (+ DataWarehouseSourceCategory,+ ReleaseStatus,+ SourceFieldInputConfig,+ SourceFieldInputConfigType,+)++from products.warehouse_sources.backend.temporal.data_imports.sources.fly_io import source as source_module+from products.warehouse_sources.backend.temporal.data_imports.sources.fly_io.settings import ENDPOINTS+from products.warehouse_sources.backend.temporal.data_imports.sources.fly_io.source import FlyIoSource+from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs import FlyIoSourceConfig+from products.warehouse_sources.backend.types import ExternalDataSourceType+++def _config() -> FlyIoSourceConfig:+ return FlyIoSourceConfig(api_token="FlyV1 secret", organization_slug="acme")+++class TestSourceConfig:+ def test_source_type(self) -> None:+ assert FlyIoSource().source_type == ExternalDataSourceType.FLYIO++ def test_config_metadata(self) -> None:+ config = FlyIoSource().get_source_config+ assert config.label == "Fly.io"+ assert config.category == DataWarehouseSourceCategory.ENGINEERING___MONITORING+ assert config.releaseStatus == ReleaseStatus.ALPHA+ # docsUrl filename must match the posthog.com doc (fly-io).+ assert config.docsUrl == "https://posthog.com/docs/cdp/sources/fly-io"++ def test_org_slug_requires_credential_reentry(self) -> None:+ # Changing which org the token points at must re-require the token, so a preserved token+ # can't be retargeted at another org it happens to reach.+ assert FlyIoSource().connection_host_fields == ["organization_slug"]++ def test_config_fields(self) -> None:+ fields = {f.name: f for f in FlyIoSource().get_source_config.fields}+ assert set(fields) == {"api_token", "organization_slug"}+ token = fields["api_token"]+ assert isinstance(token, SourceFieldInputConfig)+ # The token is a secret — rendering it as plaintext would leak it in the form.+ assert token.type == SourceFieldInputConfigType.PASSWORD+ assert token.secret is True+ assert fields["organization_slug"].type == SourceFieldInputConfigType.TEXT+++class TestGetSchemas:+ def test_returns_all_endpoints_full_refresh(self) -> None:+ schemas = {s.name: s for s in FlyIoSource().get_schemas(_config(), team_id=1)}+ assert set(schemas) == set(ENDPOINTS) == {"apps", "machines", "volumes"}+ # No verified server-side time filter, so every stream is full refresh only.+ for schema in schemas.values():+ assert schema.supports_incremental is False+ assert schema.supports_append is False+ assert schema.detected_primary_keys == ["id"]++ def test_names_filter(self) -> None:+ schemas = FlyIoSource().get_schemas(_config(), team_id=1, names=["machines"])+ assert [s.name for s in schemas] == ["machines"]+++class TestValidateCredentials:+ @parameterized.expand([(True, None), (False, "bad token")])+ def test_delegates_to_transport(self, valid: bool, error: str | None) -> None:+ with patch.object(source_module, "validate_fly_io_credentials", return_value=(valid, error)) as mock_validate:+ result = FlyIoSource().validate_credentials(_config(), team_id=1)+ assert result == (valid, error)+ mock_validate.assert_called_once_with("FlyV1 secret", "acme")+++class TestSourceForPipeline:+ def test_plumbs_config_and_schema_into_transport(self) -> None:+ inputs = MagicMock()+ inputs.schema_name = "machines"+ with patch.object(source_module, "fly_io_source") as mock_source:+ FlyIoSource().source_for_pipeline(_config(), inputs)+ mock_source.assert_called_once()+ kwargs = mock_source.call_args.kwargs+ assert kwargs["api_token"] == "FlyV1 secret"+ assert kwargs["org_slug"] == "acme"+ assert kwargs["endpoint"] == "machines"+++class TestCanonicalDescriptionsAndDocs:+ def test_canonical_descriptions_cover_every_endpoint(self) -> None:+ # A stream missing a canonical entry silently falls back to LLM enrichment; keep them aligned.+ descriptions = FlyIoSource().get_canonical_descriptions()+ assert set(descriptions) == set(ENDPOINTS)++ def test_documented_tables_render_without_credentials(self) -> None:+ # lists_tables_without_credentials=True is what makes the posthog.com Supported tables section+ # render; if get_schemas ever needed I/O this would hang the public docs endpoint.+ assert FlyIoSource().lists_tables_without_credentials is True+ tables = FlyIoSource().get_documented_tables()+ assert {t["name"] for t in tables} == set(ENDPOINTS)+++class TestNonRetryableErrors:+ @parameterized.expand(+ [+ ("unauthorized", "401 Client Error: Unauthorized for url: https://api.machines.dev/v1/orgs/acme/machines"),+ ("forbidden", "403 Client Error: Forbidden for url: https://api.machines.dev/v1/apps?org_slug=acme"),+ ]+ )+ def test_credential_errors_are_non_retryable(self, _name: str, observed_error: str) -> None:+ non_retryable = FlyIoSource().get_non_retryable_errors()+ assert any(key in observed_error for key in non_retryable)++ @parameterized.expand(+ [+ ("read_timeout", "HTTPSConnectionPool(host='api.machines.dev', port=443): Read timed out."),+ ("server_error", "500 Server Error: Internal Server Error for url: https://api.machines.dev/v1/apps"),+ ]+ )+ def test_transient_errors_remain_retryable(self, _name: str, other_error: str) -> None:+ non_retryable = FlyIoSource().get_non_retryable_errors()+ assert not any(key in other_error for key in non_retryable)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 5a8882aab265..b2a2eee35602 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@@ -1366,7 +1366,8 @@ class FlowluSourceConfig(config.Config):@config.configclass FlyIoSourceConfig(config.Config):- pass+ api_token: str+ organization_slug: str@config.config