: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 digitalocean import source (#70001)
Tom Owers4552014bd4f3
diff --git a/frontend/public/services/digitalocean.svg b/frontend/public/services/digitalocean.svgnew file mode 100644index 000000000000..6ff6346c63e3--- /dev/null+++ b/frontend/public/services/digitalocean.svg@@ -0,0 +1,3 @@+<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 81 80" height="80" width="81">+<path fill="#0069FF" d="M40.4443 80C62.5366 80 80.4443 62.0917 80.4443 40C80.4443 17.9083 62.5366 0 40.4443 0C18.3521 0 0.444336 17.9083 0.444336 40H16.001C16.001 26.4996 26.9458 15.5554 40.4443 15.5554C53.9453 15.5554 64.8901 26.4996 64.8901 40C64.8901 53.5004 53.9453 64.4446 40.4443 64.4446V80ZM40.2222 49.1113H24.8877V64.4446H13.1104V54.6667H3.33252V64.4446H13.1104V76.4447H25.1099V64.4446H40.2222V49.1113Z" clip-rule="evenodd" fill-rule="evenodd"></path>+</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 c9be0bc7c901..40fecfa90ac7 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md@@ -142,6 +142,7 @@ the row lists both.| deno_deploy | HTTP | requests | ✅ || devin_ai | HTTP | requests | ✅ || ding_connect | HTTP | requests | ✅ |+| digitalocean | HTTP | requests + `rest_source.RESTClient` | ✅ || dixa | HTTP | requests | ✅ || dockerhub | HTTP | requests | ✅ || docuseal | HTTP | requests | ✅ |@@ -535,7 +536,6 @@ doesn't conflict with concurrent PRs.- dbt- deno_deploy- deputy-- digitalocean- display_video_360- docusign- dolibarrdiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/digitalocean/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/digitalocean/canonical_descriptions.pynew file mode 100644index 000000000000..3a7ceb58e673--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/digitalocean/canonical_descriptions.py@@ -0,0 +1,199 @@+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (+ CanonicalDescriptions,+)++# Curated from the DigitalOcean API v2 reference (https://docs.digitalocean.com/reference/api/).+# Applied directly as authoritative column/table descriptions; any endpoint or column not+# covered here falls back to LLM enrichment.+CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {+ "droplets": {+ "description": "Virtual machines (Droplets) running in your account.",+ "docs_url": "https://docs.digitalocean.com/reference/api/api-reference/#tag/Droplets",+ "columns": {+ "id": "Unique numeric identifier for the Droplet.",+ "name": "Human-readable name of the Droplet.",+ "memory": "RAM allocated to the Droplet, in megabytes.",+ "vcpus": "Number of virtual CPUs.",+ "disk": "Disk size allocated to the Droplet, in gigabytes.",+ "region": "Region object the Droplet is deployed in.",+ "image": "Base image the Droplet was created from.",+ "size_slug": "Slug identifying the Droplet's size plan.",+ "status": "Current status (e.g. new, active, off, archive).",+ "created_at": "Time when the Droplet was created (ISO 8601).",+ "tags": "Tags applied to the Droplet.",+ },+ },+ "apps": {+ "description": "App Platform applications and their current specification.",+ "docs_url": "https://docs.digitalocean.com/reference/api/api-reference/#tag/Apps",+ "columns": {+ "id": "Unique identifier for the app.",+ "spec": "The app's specification (services, static sites, and settings).",+ "default_ingress": "Default URL where the app is reachable.",+ "created_at": "Time when the app was created (ISO 8601).",+ "updated_at": "Time when the app was last updated (ISO 8601).",+ "active_deployment": "The currently live deployment.",+ },+ },+ "kubernetes_clusters": {+ "description": "DigitalOcean Kubernetes (DOKS) clusters.",+ "docs_url": "https://docs.digitalocean.com/reference/api/api-reference/#tag/Kubernetes",+ "columns": {+ "id": "Unique identifier for the cluster.",+ "name": "Human-readable name of the cluster.",+ "region": "Region slug the cluster runs in.",+ "version": "Kubernetes version running on the cluster.",+ "node_pools": "Worker node pools attached to the cluster.",+ "status": "Current cluster status.",+ "created_at": "Time when the cluster was created (ISO 8601).",+ },+ },+ "databases": {+ "description": "Managed database clusters (Postgres, MySQL, Redis, MongoDB, Kafka).",+ "docs_url": "https://docs.digitalocean.com/reference/api/api-reference/#tag/Databases",+ "columns": {+ "id": "Unique identifier for the database cluster.",+ "name": "Human-readable name of the cluster.",+ "engine": "Database engine (e.g. pg, mysql, redis).",+ "version": "Engine version.",+ "region": "Region slug the cluster runs in.",+ "status": "Current cluster status.",+ "num_nodes": "Number of nodes in the cluster.",+ "created_at": "Time when the cluster was created (ISO 8601).",+ },+ },+ "volumes": {+ "description": "Block storage volumes.",+ "docs_url": "https://docs.digitalocean.com/reference/api/api-reference/#tag/Block-Storage",+ "columns": {+ "id": "Unique identifier for the volume.",+ "name": "Human-readable name of the volume.",+ "size_gigabytes": "Size of the volume, in gigabytes.",+ "region": "Region the volume is available in.",+ "droplet_ids": "Droplets the volume is attached to.",+ "created_at": "Time when the volume was created (ISO 8601).",+ },+ },+ "snapshots": {+ "description": "Snapshots of Droplets and volumes.",+ "docs_url": "https://docs.digitalocean.com/reference/api/api-reference/#tag/Snapshots",+ "columns": {+ "id": "Unique identifier for the snapshot.",+ "name": "Human-readable name of the snapshot.",+ "resource_id": "Identifier of the resource the snapshot was taken from.",+ "resource_type": "Type of resource (droplet or volume).",+ "regions": "Regions the snapshot is available in.",+ "min_disk_size": "Minimum disk size required to use the snapshot, in gigabytes.",+ "size_gigabytes": "Size of the snapshot, in gigabytes.",+ "created_at": "Time when the snapshot was created (ISO 8601).",+ },+ },+ "load_balancers": {+ "description": "Load balancers distributing traffic across Droplets.",+ "docs_url": "https://docs.digitalocean.com/reference/api/api-reference/#tag/Load-Balancers",+ "columns": {+ "id": "Unique identifier for the load balancer.",+ "name": "Human-readable name of the load balancer.",+ "ip": "Public IP address of the load balancer.",+ "region": "Region the load balancer runs in.",+ "status": "Current status of the load balancer.",+ "forwarding_rules": "Rules mapping inbound to backend traffic.",+ "created_at": "Time when the load balancer was created (ISO 8601).",+ },+ },+ "projects": {+ "description": "Projects used to organize resources in your account.",+ "docs_url": "https://docs.digitalocean.com/reference/api/api-reference/#tag/Projects",+ "columns": {+ "id": "Unique identifier for the project.",+ "name": "Human-readable name of the project.",+ "purpose": "Stated purpose of the project.",+ "environment": "Environment label (Development, Staging, Production).",+ "is_default": "Whether this is the account's default project.",+ "created_at": "Time when the project was created (ISO 8601).",+ },+ },+ "vpcs": {+ "description": "Virtual Private Cloud networks.",+ "docs_url": "https://docs.digitalocean.com/reference/api/api-reference/#tag/VPCs",+ "columns": {+ "id": "Unique identifier for the VPC.",+ "name": "Human-readable name of the VPC.",+ "region": "Region slug the VPC is scoped to.",+ "ip_range": "Private IP address range in CIDR notation.",+ "default": "Whether this is the region's default VPC.",+ "created_at": "Time when the VPC was created (ISO 8601).",+ },+ },+ "images": {+ "description": "User-owned images (snapshots, backups, and custom images).",+ "docs_url": "https://docs.digitalocean.com/reference/api/api-reference/#tag/Images",+ "columns": {+ "id": "Unique numeric identifier for the image.",+ "name": "Human-readable name of the image.",+ "type": "Type of image (snapshot, backup, or custom).",+ "distribution": "Base distribution of the image.",+ "regions": "Regions the image is available in.",+ "size_gigabytes": "Size of the image, in gigabytes.",+ "created_at": "Time when the image was created (ISO 8601).",+ },+ },+ "domains": {+ "description": "DNS domains managed by DigitalOcean.",+ "docs_url": "https://docs.digitalocean.com/reference/api/api-reference/#tag/Domains",+ "columns": {+ "name": "The domain name (used as the primary key).",+ "ttl": "Default time-to-live for the domain's records, in seconds.",+ "zone_file": "The domain's complete zone file.",+ },+ },+ "ssh_keys": {+ "description": "SSH public keys registered on the account.",+ "docs_url": "https://docs.digitalocean.com/reference/api/api-reference/#tag/SSH-Keys",+ "columns": {+ "id": "Unique numeric identifier for the key.",+ "fingerprint": "Fingerprint of the SSH public key.",+ "public_key": "The SSH public key.",+ "name": "Human-readable name of the key.",+ },+ },+ "reserved_ips": {+ "description": "Reserved (formerly floating) IP addresses.",+ "docs_url": "https://docs.digitalocean.com/reference/api/api-reference/#tag/Reserved-IPs",+ "columns": {+ "ip": "The reserved IP address (used as the primary key).",+ "region": "Region the reserved IP is available in.",+ "droplet": "Droplet the reserved IP is currently assigned to, if any.",+ "project_id": "Project the reserved IP belongs to.",+ },+ },+ "tags": {+ "description": "Tags used to label and group resources.",+ "docs_url": "https://docs.digitalocean.com/reference/api/api-reference/#tag/Tags",+ "columns": {+ "name": "The tag name (used as the primary key).",+ "resources": "Summary of resources the tag is applied to.",+ },+ },+ "invoices": {+ "description": "Billing invoices for the account.",+ "docs_url": "https://docs.digitalocean.com/reference/api/api-reference/#tag/Billing",+ "columns": {+ "invoice_uuid": "Unique identifier for the invoice.",+ "amount": "Total amount of the invoice.",+ "invoice_period": "Billing period the invoice covers (YYYY-MM).",+ },+ },+ "billing_history": {+ "description": "Append-only ledger of billing events (invoices, payments, credits).",+ "docs_url": "https://docs.digitalocean.com/reference/api/api-reference/#tag/Billing",+ "columns": {+ "description": "Description of the billing event.",+ "amount": "Amount associated with the event.",+ "invoice_id": "Identifier of the related invoice, when applicable.",+ "invoice_uuid": "UUID of the related invoice, when applicable.",+ "date": "Time the billing event occurred (ISO 8601).",+ "type": "Type of billing event (e.g. Invoice, Payment).",+ },+ },+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/digitalocean/digitalocean.py b/products/warehouse_sources/backend/temporal/data_imports/sources/digitalocean/digitalocean.pynew file mode 100644index 000000000000..481f81ada29e--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/digitalocean/digitalocean.py@@ -0,0 +1,116 @@+from collections.abc import Callable+from typing import Any++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.rest_source import (+ ClientConfig,+ RESTAPIConfig,+ rest_api_resource,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.paginators import (+ JSONLinkPaginator,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.resource import Resource+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.typing import EndpointResource+from products.warehouse_sources.backend.temporal.data_imports.sources.digitalocean.settings import (+ DIGITALOCEAN_ENDPOINTS,+ PAGE_SIZE,+ DigitalOceanEndpointConfig,+)++DIGITALOCEAN_BASE_URL = "https://api.digitalocean.com"+++def _paginator() -> JSONLinkPaginator:+ # DigitalOcean returns the next page as a full URL under `links.pages.next`; it's+ # absent on the final page, which terminates pagination.+ return JSONLinkPaginator(next_url_path="links.pages.next")+++def get_resource(endpoint_config: DigitalOceanEndpointConfig) -> EndpointResource:+ params: dict[str, object] = {"per_page": PAGE_SIZE}+ params.update(endpoint_config.extra_params)++ return {+ "name": endpoint_config.name,+ "table_name": endpoint_config.name,+ # No server-side timestamp filter exists on any DigitalOcean list endpoint, so we+ # always replace the whole table rather than merge on an incremental cursor.+ "write_disposition": "replace",+ "endpoint": {+ "data_selector": endpoint_config.data_selector,+ "path": endpoint_config.path,+ "paginator": _paginator(),+ "params": params,+ },+ "table_format": "delta",+ }+++def _strip_sensitive_fields(sensitive_fields: frozenset[str]) -> Callable[[dict[str, Any]], dict[str, Any]]:+ # Drop credential-bearing keys from each record before it's stored. Recurses through nested+ # dicts and lists because some secrets live inside spec/deployment objects, not at the top+ # level. Runs as a resource map, so it's the last thing to touch a record before persistence.+ def _scrub(value: Any) -> Any:+ if isinstance(value, dict):+ return {key: _scrub(item) for key, item in value.items() if key not in sensitive_fields}+ if isinstance(value, list):+ return [_scrub(item) for item in value]+ return value++ def _strip(record: dict[str, Any]) -> dict[str, Any]:+ return _scrub(record)++ return _strip+++def digitalocean_source(api_key: str, endpoint: str, team_id: int, job_id: str) -> Resource:+ endpoint_config = DIGITALOCEAN_ENDPOINTS[endpoint]++ client_config: ClientConfig = {+ "base_url": DIGITALOCEAN_BASE_URL,+ "auth": {+ "type": "bearer",+ "token": api_key,+ },+ "paginator": _paginator(),+ }+ # Endpoints that return secrets (e.g. `databases`) must not have their raw responses+ # captured into HTTP samples, which happens before resource maps run. Opt them out of+ # sample capture while keeping the request metered, logged, and token-redacted.+ if endpoint_config.sensitive_fields:+ client_config["session"] = make_tracked_session(redact_values=(api_key,), capture=False)++ config: RESTAPIConfig = {+ "client": client_config,+ "resource_defaults": {+ "write_disposition": "replace",+ },+ "resources": [get_resource(endpoint_config)],+ }++ # No incremental support, so `db_incremental_field_last_value` is always None.+ resource = rest_api_resource(config, team_id, job_id, None)+ if endpoint_config.sensitive_fields:+ resource.add_map(_strip_sensitive_fields(endpoint_config.sensitive_fields))+ return resource+++def validate_credentials(api_key: str) -> tuple[bool, int | None]:+ """Probe `/v2/account` to confirm the token is genuine.++ `/v2/account` is the cheapest authenticated probe and every token can read it, so it+ confirms the token without depending on any resource-specific scope. Returns+ ``(ok, status_code)``; ``status_code`` is ``None`` on a transport error. The caller+ distinguishes an auth rejection (401/403) from a transient failure so it never tells the+ user their token is invalid when DigitalOcean was merely rate-limited or unavailable.+ """+ try:+ response = make_tracked_session(redact_values=(api_key,)).get(+ f"{DIGITALOCEAN_BASE_URL}/v2/account",+ headers={"Authorization": f"Bearer {api_key}"},+ timeout=10,+ )+ except Exception:+ return False, None+ return response.status_code == 200, response.status_codediff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/digitalocean/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/digitalocean/settings.pynew file mode 100644index 000000000000..d27b78263db9--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/digitalocean/settings.py@@ -0,0 +1,161 @@+from dataclasses import dataclass, field+from typing import Optional++from products.warehouse_sources.backend.types import IncrementalField++# DigitalOcean caps `per_page` at 200; use the max to minimize round trips against the+# 5,000 req/hour + 250 req/minute rate limits.+PAGE_SIZE = 200+++@dataclass+class DigitalOceanEndpointConfig:+ name: str+ # Path relative to the API root (https://api.digitalocean.com).+ path: str+ # Key the list of records is nested under in the JSON response body+ # (e.g. `{"droplets": [...]}` → "droplets").+ data_selector: str+ # Columns that uniquely identify a record table-wide. DigitalOcean resource ids are+ # globally unique; keyless resources (domains, tags) use their natural name/ip key.+ primary_keys: list[str] = field(default_factory=lambda: ["id"])+ # Stable creation timestamp to partition by. `None` for resources the API doesn't stamp+ # with a creation time. Never a mutable field like `updated_at`.+ partition_key: Optional[str] = None+ # Extra query params merged into every request for this endpoint.+ extra_params: dict[str, str] = field(default_factory=dict)+ # Response keys carrying secrets (connection URIs, passwords, env-var values, log-shipping+ # credentials). Dropped from every record before it's stored — recursively, at any depth,+ # since some live nested inside spec/deployment objects — and their presence also disables+ # HTTP sample capture for the endpoint so the raw response can't leak into HTTP samples.+ sensitive_fields: frozenset[str] = frozenset()+++# DigitalOcean's list endpoints all share the same page-based pagination+# (`links.pages.next` full URLs, `meta.total`) and none expose a server-side+# `updated_since`/`created_since` filter, so every endpoint is full-refresh only.+DIGITALOCEAN_ENDPOINTS: dict[str, DigitalOceanEndpointConfig] = {+ "droplets": DigitalOceanEndpointConfig(+ name="droplets",+ path="/v2/droplets",+ data_selector="droplets",+ partition_key="created_at",+ ),+ # `GET /v2/apps` returns full app specs whose components carry environment-variable values+ # and log-destination credentials (Datadog/Papertrail/OpenSearch). Those `envs` and+ # `log_destinations` blocks live nested inside `spec` (and the deployment spec copies), so+ # they're stripped recursively; the surrounding app/service metadata is kept.+ "apps": DigitalOceanEndpointConfig(+ name="apps",+ path="/v2/apps",+ data_selector="apps",+ partition_key="created_at",+ sensitive_fields=frozenset({"envs", "log_destinations"}),+ ),+ "kubernetes_clusters": DigitalOceanEndpointConfig(+ name="kubernetes_clusters",+ path="/v2/kubernetes/clusters",+ data_selector="kubernetes_clusters",+ partition_key="created_at",+ ),+ # `GET /v2/databases` embeds live cluster credentials (connection URIs + passwords and+ # the per-database `users` list) alongside the metadata we want. Strip those fields so+ # they never land in a queryable warehouse table.+ "databases": DigitalOceanEndpointConfig(+ name="databases",+ path="/v2/databases",+ data_selector="databases",+ partition_key="created_at",+ sensitive_fields=frozenset(+ {+ "connection",+ "private_connection",+ "standby_connection",+ "standby_private_connection",+ "users",+ }+ ),+ ),+ "volumes": DigitalOceanEndpointConfig(+ name="volumes",+ path="/v2/volumes",+ data_selector="volumes",+ partition_key="created_at",+ ),+ "snapshots": DigitalOceanEndpointConfig(+ name="snapshots",+ path="/v2/snapshots",+ data_selector="snapshots",+ partition_key="created_at",+ ),+ "load_balancers": DigitalOceanEndpointConfig(+ name="load_balancers",+ path="/v2/load_balancers",+ data_selector="load_balancers",+ partition_key="created_at",+ ),+ "projects": DigitalOceanEndpointConfig(+ name="projects",+ path="/v2/projects",+ data_selector="projects",+ partition_key="created_at",+ ),+ "vpcs": DigitalOceanEndpointConfig(+ name="vpcs",+ path="/v2/vpcs",+ data_selector="vpcs",+ partition_key="created_at",+ ),+ # User-owned images only; the unfiltered list also returns every public distribution+ # and application image, which is huge and identical for every account.+ "images": DigitalOceanEndpointConfig(+ name="images",+ path="/v2/images",+ data_selector="images",+ partition_key="created_at",+ extra_params={"private": "true"},+ ),+ "domains": DigitalOceanEndpointConfig(+ name="domains",+ path="/v2/domains",+ data_selector="domains",+ primary_keys=["name"],+ ),+ "ssh_keys": DigitalOceanEndpointConfig(+ name="ssh_keys",+ path="/v2/account/keys",+ data_selector="ssh_keys",+ ),+ "reserved_ips": DigitalOceanEndpointConfig(+ name="reserved_ips",+ path="/v2/reserved_ips",+ data_selector="reserved_ips",+ primary_keys=["ip"],+ ),+ "tags": DigitalOceanEndpointConfig(+ name="tags",+ path="/v2/tags",+ data_selector="tags",+ primary_keys=["name"],+ ),+ "invoices": DigitalOceanEndpointConfig(+ name="invoices",+ path="/v2/customers/my/invoices",+ data_selector="invoices",+ primary_keys=["invoice_uuid"],+ ),+ # Append-only financial ledger with no natural unique key. The composite is a best-effort+ # dedup guard; the endpoint is full-refresh (replace) so it's rewritten wholesale each sync.+ "billing_history": DigitalOceanEndpointConfig(+ name="billing_history",+ path="/v2/customers/my/billing_history",+ data_selector="billing_history",+ primary_keys=["date", "type", "amount", "description"],+ ),+}++ENDPOINTS = tuple(DIGITALOCEAN_ENDPOINTS.keys())++# DigitalOcean exposes no server-side timestamp filter on any list endpoint, so no endpoint+# supports genuine incremental sync. Kept for parity with the schema-building convention.+INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/digitalocean/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/digitalocean/source.pyindex 9ee17dd1a8c3..feb3f4717f95 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/digitalocean/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/digitalocean/source.py@@ -1,31 +1,155 @@-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.digitalocean.digitalocean import (+ digitalocean_source,+ validate_credentials as validate_digitalocean_credentials,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.digitalocean.settings import (+ DIGITALOCEAN_ENDPOINTS,+ ENDPOINTS,+ INCREMENTAL_FIELDS,+)from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs import DigitalOceanSourceConfigfrom products.warehouse_sources.backend.types import ExternalDataSourceType@SourceRegistry.registerclass DigitalOceanSource(SimpleSource[DigitalOceanSourceConfig]):+ lists_tables_without_credentials = True # static endpoint catalog — safe for public docs+@propertydef source_type(self) -> ExternalDataSourceType:return ExternalDataSourceType.DIGITALOCEAN+ def get_canonical_descriptions(self) -> CanonicalDescriptions:+ from products.warehouse_sources.backend.temporal.data_imports.sources.digitalocean.canonical_descriptions import (+ CANONICAL_DESCRIPTIONS,+ )++ return CANONICAL_DESCRIPTIONS++ def get_non_retryable_errors(self) -> dict[str, str | None]:+ return {+ # A bad, revoked, or expired token surfaces as an HTTPError when the RESTClient calls+ # `raise_for_status()`. Retrying can never fix a credential problem, so stop the sync.+ # Match the stable status text + base host, not the per-request path/query.+ "401 Client Error: Unauthorized for url: https://api.digitalocean.com": "Your DigitalOcean API token is invalid or has expired. Generate a new personal access token, then reconnect.",+ "403 Client Error: Forbidden for url: https://api.digitalocean.com": "Your DigitalOcean API token is missing the read scope needed to sync this data. Grant read access to the relevant resources, then reconnect.",+ }++ def get_schemas(+ self,+ config: DigitalOceanSourceConfig,+ team_id: int,+ with_counts: bool = False,+ names: list[str] | None = None,+ force_refresh: bool = False,+ ) -> list[SourceSchema]:+ schemas = [+ SourceSchema(+ name=endpoint,+ # DigitalOcean has no server-side timestamp filter, so no endpoint can be+ # incrementally synced — every table is full refresh.+ supports_incremental=False,+ supports_append=False,+ incremental_fields=INCREMENTAL_FIELDS.get(endpoint, []),+ )+ for endpoint in ENDPOINTS+ ]+ if names is not None:+ names_set = set(names)+ schemas = [s for s in schemas if s.name in names_set]+ return schemas++ def validate_credentials(+ self, config: DigitalOceanSourceConfig, team_id: int, schema_name: Optional[str] = None+ ) -> tuple[bool, str | None]:+ ok, status_code = validate_digitalocean_credentials(config.api_key)+ if ok:+ return True, None++ if status_code in (401, 403):+ return (+ False,+ "DigitalOcean rejected the API token. Check that the personal access token is correct, has read "+ "scope, and has not expired.",+ )++ # A transient response (429, 5xx) or transport error (status_code is None) is not proof the+ # token is bad, so don't tell the user it is — ask them to retry.+ return (+ False,+ "Couldn't reach DigitalOcean to verify the API token. This is usually temporary — wait a moment and "+ "try again.",+ )+@propertydef get_source_config(self) -> SourceConfig:return SourceConfig(name=SchemaExternalDataSourceType.DIGITAL_OCEAN,category=DataWarehouseSourceCategory.ENGINEERING___MONITORING,label="DigitalOcean",- iconPath="/static/services/digitalocean.png",+ releaseStatus=ReleaseStatus.ALPHA,+ caption="""Enter a DigitalOcean personal access token to pull your DigitalOcean infrastructure and billing data into the PostHog Data warehouse.++Create a token under [API → Tokens](https://cloud.digitalocean.com/account/api/tokens) with at least **Read** scope.""",+ iconPath="/static/services/digitalocean.svg",+ docsUrl="https://posthog.com/docs/cdp/sources/digitalocean",keywords=["cloud", "infrastructure", "droplets", "billing"],- fields=cast(list[FieldType], []),- unreleasedSource=True,+ fields=cast(+ list[FieldType],+ [+ SourceFieldInputConfig(+ name="api_key",+ label="Personal access token",+ type=SourceFieldInputConfigType.PASSWORD,+ required=True,+ placeholder="dop_v1_...",+ secret=True,+ ),+ ],+ ),)++ def source_for_pipeline(self, config: DigitalOceanSourceConfig, inputs: SourceInputs) -> SourceResponse:+ endpoint_config = DIGITALOCEAN_ENDPOINTS[inputs.schema_name]+ resource = digitalocean_source(+ api_key=config.api_key,+ endpoint=inputs.schema_name,+ team_id=inputs.team_id,+ job_id=inputs.job_id,+ )+ response = SourceResponse(+ name=resource.name,+ items=lambda: resource,+ primary_keys=endpoint_config.primary_keys,+ column_hints=resource.column_hints,+ )++ if endpoint_config.partition_key:+ response.partition_count = 1+ response.partition_size = 1+ response.partition_mode = "datetime"+ response.partition_format = "month"+ response.partition_keys = [endpoint_config.partition_key]++ return responsediff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/digitalocean/tests/test_digitalocean.py b/products/warehouse_sources/backend/temporal/data_imports/sources/digitalocean/tests/test_digitalocean.pynew file mode 100644index 000000000000..110cd9147d9a--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/digitalocean/tests/test_digitalocean.py@@ -0,0 +1,203 @@+import json+from typing import Any, cast++import pytest+from unittest.mock import MagicMock, patch++from requests import Request, Response++from products.warehouse_sources.backend.temporal.data_imports.sources.digitalocean.digitalocean import (+ _paginator,+ digitalocean_source,+ get_resource,+ validate_credentials,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.digitalocean.settings import (+ DIGITALOCEAN_ENDPOINTS,+ PAGE_SIZE,+)+++def _make_response(json_body: dict[str, Any] | None = None, status_code: int = 200) -> Response:+ resp = Response()+ resp.status_code = status_code+ resp.headers["Content-Type"] = "application/json"+ resp._content = json.dumps(json_body or {}).encode()+ return resp+++def _endpoint(resource: Any) -> dict[str, Any]:+ return cast(dict[str, Any], resource["endpoint"])+++class TestDigitalOceanPaginator:+ def test_advances_on_next_page_url(self) -> None:+ # DigitalOcean nests the next-page URL under links.pages.next; a page that has one must+ # continue pagination. A wrong json path (e.g. "links.next") would silently stop after page 1.+ p = _paginator()+ p.update_state(+ _make_response(+ {+ "droplets": [{"id": 1}],+ "links": {"pages": {"next": "https://api.digitalocean.com/v2/droplets?page=2"}},+ }+ )+ )++ assert p.has_next_page is True++ req = Request(method="GET", url="https://api.digitalocean.com/v2/droplets")+ p.update_request(req)+ assert req.url == "https://api.digitalocean.com/v2/droplets?page=2"++ @pytest.mark.parametrize(+ "body",+ [+ pytest.param(+ {"droplets": [{"id": 1}], "links": {"pages": {"last": "…", "prev": "…"}}}, id="last_page_no_next"+ ),+ pytest.param({"droplets": [{"id": 1}], "links": {}}, id="empty_links"),+ pytest.param({"droplets": []}, id="no_links_key"),+ ],+ )+ def test_stops_when_no_next_page(self, body: dict[str, Any]) -> None:+ p = _paginator()+ p.update_state(_make_response(body))+ assert p.has_next_page is False+++class TestDigitalOceanGetResource:+ @pytest.mark.parametrize("endpoint", list(DIGITALOCEAN_ENDPOINTS.keys()))+ def test_resource_matches_endpoint_config(self, endpoint: str) -> None:+ config = DIGITALOCEAN_ENDPOINTS[endpoint]+ resource = get_resource(config)+ endpoint_def = _endpoint(resource)++ # data_selector must equal the JSON key DigitalOcean wraps the list under; a mismatch+ # yields an empty table without erroring, so this pins the contract per endpoint.+ assert endpoint_def["data_selector"] == config.data_selector+ assert endpoint_def["path"] == config.path+ assert endpoint_def["params"]["per_page"] == PAGE_SIZE+ # No incremental filter exists on any endpoint, so every table is full replace.+ assert resource["write_disposition"] == "replace"++ def test_images_limits_to_private(self) -> None:+ # Without private=true the images list also returns every public distribution/application+ # image — huge and identical for every account.+ resource = get_resource(DIGITALOCEAN_ENDPOINTS["images"])+ assert _endpoint(resource)["params"]["private"] == "true"+++class TestDigitalOceanSensitiveFields:+ _DATABASE_RECORD = {+ "id": "db-1",+ "name": "prod-pg",+ "engine": "pg",+ "region": "nyc1",+ "connection": {"uri": "postgresql://doadmin:secret@host:25060/defaultdb", "password": "secret"},+ "private_connection": {"uri": "postgresql://doadmin:secret@priv-host:25060/defaultdb"},+ "standby_connection": {"password": "secret"},+ "standby_private_connection": {"password": "secret"},+ "users": [{"name": "doadmin", "password": "secret"}],+ }++ def test_databases_strips_credential_bearing_fields(self) -> None:+ # /v2/databases embeds live connection URIs, passwords, and the users list in every+ # record; without stripping they'd land in a queryable warehouse table.+ resource = digitalocean_source("dop_v1_token", "databases", team_id=1, job_id="job-1")+ [transformed] = resource._apply_transforms([dict(self._DATABASE_RECORD)])++ assert transformed == {"id": "db-1", "name": "prod-pg", "engine": "pg", "region": "nyc1"}++ def test_apps_strips_nested_env_and_log_credentials(self) -> None:+ # App specs bury env-var values and log-destination credentials inside spec.services and+ # the deployment spec copy; the strip must recurse to reach them while keeping metadata.+ record = {+ "id": "app-1",+ "spec": {+ "name": "web",+ "services": [+ {+ "name": "api",+ "envs": [{"key": "SECRET_KEY", "value": "leak-me"}],+ "log_destinations": [{"name": "dd", "datadog": {"api_key": "leak-me"}}],+ }+ ],+ },+ "active_deployment": {"spec": {"services": [{"name": "api", "envs": [{"value": "leak-me"}]}]}},+ }+ resource = digitalocean_source("dop_v1_token", "apps", team_id=1, job_id="job-1")+ [transformed] = resource._apply_transforms([record])++ assert transformed == {+ "id": "app-1",+ "spec": {"name": "web", "services": [{"name": "api"}]},+ "active_deployment": {"spec": {"services": [{"name": "api"}]}},+ }++ def test_non_sensitive_endpoint_keeps_every_field(self) -> None:+ # Only endpoints that declare sensitive_fields get filtered; everything else must round-trip+ # untouched or the strip would silently drop real data.+ record = {"id": 1, "name": "web-1", "networks": {"v4": [{"ip_address": "1.2.3.4"}]}}+ resource = digitalocean_source("dop_v1_token", "droplets", team_id=1, job_id="job-1")++ assert resource._apply_transforms([dict(record)]) == [record]++ @patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.digitalocean.digitalocean.make_tracked_session"+ )+ def test_databases_opts_out_of_sample_capture(self, mock_session: MagicMock) -> None:+ # Sample capture records the raw response before resource maps run, so the secrets would be+ # captured even though they're stripped from storage; the endpoint must disable capture.+ digitalocean_source("dop_v1_token", "databases", team_id=1, job_id="job-1")++ mock_session.assert_called_once_with(redact_values=("dop_v1_token",), capture=False)++ @patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.digitalocean.digitalocean.make_tracked_session"+ )+ def test_non_sensitive_endpoint_keeps_capture_on(self, mock_session: MagicMock) -> None:+ # Non-sensitive endpoints must not build their own session here, leaving the tracked client's+ # default (capture on) in place so their traffic stays in HTTP samples.+ digitalocean_source("dop_v1_token", "droplets", team_id=1, job_id="job-1")++ mock_session.assert_not_called()+++class TestDigitalOceanValidateCredentials:+ @pytest.mark.parametrize(+ "status_code,expected",+ [+ pytest.param(200, True, id="ok"),+ pytest.param(401, False, id="unauthorized"),+ pytest.param(403, False, id="forbidden"),+ pytest.param(500, False, id="server_error"),+ ],+ )+ @patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.digitalocean.digitalocean.make_tracked_session"+ )+ def test_maps_status_to_validity(self, mock_session: MagicMock, status_code: int, expected: bool) -> None:+ # The status code is returned alongside validity so the caller can tell an auth rejection+ # (401/403) apart from a transient failure (429/5xx) it must not report as an invalid token.+ mock_session.return_value.get.return_value = _make_response(status_code=status_code)+ assert validate_credentials("dop_v1_token") == (expected, status_code)++ @patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.digitalocean.digitalocean.make_tracked_session"+ )+ def test_transport_error_reports_no_status(self, mock_session: MagicMock) -> None:+ # A network failure must not surface as "token invalid"; it yields (False, None) so the+ # caller can distinguish it from a real auth rejection.+ mock_session.return_value.get.side_effect = ConnectionError("boom")+ assert validate_credentials("dop_v1_token") == (False, None)++ @patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.digitalocean.digitalocean.make_tracked_session"+ )+ def test_sends_bearer_token(self, mock_session: MagicMock) -> None:+ mock_session.return_value.get.return_value = _make_response(status_code=200)+ validate_credentials("dop_v1_token")++ _, kwargs = mock_session.return_value.get.call_args+ assert kwargs["headers"]["Authorization"] == "Bearer dop_v1_token"diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/digitalocean/tests/test_digitalocean_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/digitalocean/tests/test_digitalocean_source.pynew file mode 100644index 000000000000..417815c564f4--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/digitalocean/tests/test_digitalocean_source.py@@ -0,0 +1,182 @@+from typing import Any++import pytest+from unittest.mock import MagicMock, patch++from posthog.schema import ReleaseStatus, SourceFieldInputConfig, SourceFieldInputConfigType++from products.warehouse_sources.backend.temporal.data_imports.sources.digitalocean.settings import ENDPOINTS+from products.warehouse_sources.backend.temporal.data_imports.sources.digitalocean.source import DigitalOceanSource+from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs import DigitalOceanSourceConfig+from products.warehouse_sources.backend.types import ExternalDataSourceType+++def _config() -> DigitalOceanSourceConfig:+ return DigitalOceanSourceConfig(api_key="dop_v1_token")+++class TestDigitalOceanSourceConfig:+ def test_source_type(self) -> None:+ assert DigitalOceanSource().source_type == ExternalDataSourceType.DIGITALOCEAN++ def test_config_exposes_single_password_token_field(self) -> None:+ config = DigitalOceanSource().get_source_config+ assert [f.name for f in config.fields] == ["api_key"]+ field = config.fields[0]+ assert isinstance(field, SourceFieldInputConfig)+ assert field.type == SourceFieldInputConfigType.PASSWORD+ assert field.required is True++ def test_stays_gated_in_alpha(self) -> None:+ # The source ships hidden (unreleasedSource) and labelled alpha until it's validated+ # against a live account; a regression that flips either would expose it prematurely.+ config = DigitalOceanSource().get_source_config+ assert config.releaseStatus == ReleaseStatus.ALPHA++ def test_docs_url_matches_icon_slug(self) -> None:+ config = DigitalOceanSource().get_source_config+ assert config.docsUrl == "https://posthog.com/docs/cdp/sources/digitalocean"+ assert config.iconPath == "/static/services/digitalocean.svg"+++class TestDigitalOceanGetSchemas:+ def test_lists_every_endpoint_as_full_refresh(self) -> None:+ schemas = DigitalOceanSource().get_schemas(_config(), team_id=1)+ assert {s.name for s in schemas} == set(ENDPOINTS)+ # DigitalOcean has no server-side timestamp filter, so nothing may advertise incremental+ # sync — otherwise "incremental" runs re-page the whole endpoint at full API cost.+ assert all(not s.supports_incremental for s in schemas)+ assert all(not s.supports_append for s in schemas)++ def test_filters_by_names(self) -> None:+ schemas = DigitalOceanSource().get_schemas(_config(), team_id=1, names=["droplets"])+ assert [s.name for s in schemas] == ["droplets"]++ def test_documented_tables_render_without_credentials(self) -> None:+ # lists_tables_without_credentials=True powers the public docs Supported tables section;+ # it must produce an entry per endpoint from the static catalog with no network call.+ tables = DigitalOceanSource().get_documented_tables()+ assert {t["name"] for t in tables} == set(ENDPOINTS)+++class TestDigitalOceanValidateCredentials:+ @patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.digitalocean.source.validate_digitalocean_credentials",+ return_value=(True, 200),+ )+ def test_accepts_valid_token(self, _mock: MagicMock) -> None:+ assert DigitalOceanSource().validate_credentials(_config(), team_id=1) == (True, None)++ @pytest.mark.parametrize("status_code", [401, 403])+ @patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.digitalocean.source.validate_digitalocean_credentials"+ )+ def test_auth_rejection_says_token_invalid(self, mock_validate: MagicMock, status_code: int) -> None:+ mock_validate.return_value = (False, status_code)+ valid, error = DigitalOceanSource().validate_credentials(_config(), team_id=1)+ assert not valid+ assert error is not None+ assert "rejected the API token" in error++ @pytest.mark.parametrize("status_code", [429, 500, 503, None])+ @patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.digitalocean.source.validate_digitalocean_credentials"+ )+ def test_transient_failure_does_not_blame_the_token(+ self, mock_validate: MagicMock, status_code: int | None+ ) -> None:+ # A rate limit, server error, or transport failure is not proof the token is bad; the+ # message must ask the user to retry rather than tell them to regenerate a good token.+ mock_validate.return_value = (False, status_code)+ valid, error = DigitalOceanSource().validate_credentials(_config(), team_id=1)+ assert not valid+ assert error is not None+ assert "rejected the API token" not in error+++class TestDigitalOceanSourceForPipeline:+ @pytest.mark.parametrize(+ "endpoint,expected_pk,expects_partition",+ [+ pytest.param("droplets", ["id"], True, id="droplets_id_pk_partitioned"),+ pytest.param("domains", ["name"], False, id="domains_name_pk_no_partition"),+ pytest.param("reserved_ips", ["ip"], False, id="reserved_ips_ip_pk_no_partition"),+ pytest.param(+ "billing_history",+ ["date", "type", "amount", "description"],+ False,+ id="billing_history_composite_pk",+ ),+ ],+ )+ @patch("products.warehouse_sources.backend.temporal.data_imports.sources.digitalocean.source.digitalocean_source")+ def test_plumbs_primary_keys_and_partitioning(+ self, mock_source: MagicMock, endpoint: str, expected_pk: list[str], expects_partition: bool+ ) -> None:+ resource = MagicMock()+ resource.name = endpoint+ resource.column_hints = None+ mock_source.return_value = resource++ inputs = MagicMock()+ inputs.schema_name = endpoint+ inputs.team_id = 1+ inputs.job_id = "job-1"++ response = DigitalOceanSource().source_for_pipeline(_config(), inputs)++ assert response.name == endpoint+ assert response.primary_keys == expected_pk+ if expects_partition:+ # Partition only on the stable created_at timestamp, never on keyless resources.+ assert response.partition_mode == "datetime"+ assert response.partition_keys == ["created_at"]+ else:+ assert response.partition_mode is None++ @patch("products.warehouse_sources.backend.temporal.data_imports.sources.digitalocean.source.digitalocean_source")+ def test_passes_token_and_endpoint_through(self, mock_source: MagicMock) -> None:+ resource = MagicMock()+ resource.name = "droplets"+ resource.column_hints = None+ mock_source.return_value = resource++ inputs = MagicMock()+ inputs.schema_name = "droplets"+ inputs.team_id = 7+ inputs.job_id = "job-42"++ DigitalOceanSource().source_for_pipeline(_config(), inputs)++ _, kwargs = mock_source.call_args+ assert kwargs == {+ "api_key": "dop_v1_token",+ "endpoint": "droplets",+ "team_id": 7,+ "job_id": "job-42",+ }+++class TestDigitalOceanNonRetryableErrors:+ @pytest.mark.parametrize("status", ["401", "403"])+ def test_auth_errors_are_non_retryable(self, status: str) -> None:+ errors = DigitalOceanSource().get_non_retryable_errors()+ assert any(status in key for key in errors)++ def test_error_keys_scope_to_base_host(self) -> None:+ # Matching the base host (not a per-request URL) keeps the match stable across endpoints.+ errors = DigitalOceanSource().get_non_retryable_errors()+ assert all("https://api.digitalocean.com" in key for key in errors)+++class TestDigitalOceanCanonicalDescriptions:+ def test_descriptions_key_on_real_endpoints(self) -> None:+ # Canonical descriptions are keyed by schema name; a typo'd key silently falls back to+ # LLM enrichment instead of the curated text, so keep the keys inside the endpoint set.+ descriptions = DigitalOceanSource().get_canonical_descriptions()+ assert set(descriptions.keys()) <= set(ENDPOINTS)++ def test_covers_headline_infrastructure_endpoints(self) -> None:+ descriptions: dict[str, Any] = dict(DigitalOceanSource().get_canonical_descriptions())+ for endpoint in ("droplets", "databases", "kubernetes_clusters"):+ assert descriptions[endpoint]["columns"]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 e68a20502315..5a8882aab265 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@@ -1055,7 +1055,7 @@ class DevinAISourceConfig(config.Config):@config.configclass DigitalOceanSourceConfig(config.Config):- pass+ api_key: str@config.config