Skip to content

: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.

feat(data-warehouse): implement linode import source (#70037)

Tom Owers73bdebbb0574
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
index 9025eece777c..41cbf86f0634 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
@@ -237,6 +237,7 @@ the row lists both.
| lingo_dev | HTTP | requests + `rest_source.RESTClient` | ✅ |
| linkedin_ads | HTTP (vendor SDK, RESTli) | linkedin-api (RestliClient) | ⚠️ |
| linkrunner | HTTP | requests | ✅ |
+| linode | HTTP | requests | ✅ |
| lob | HTTP | requests | ✅ |
| luma | HTTP | requests | ✅ |
| mailchimp | HTTP | requests + `rest_source.RESTClient` | ✅ |
@@ -633,7 +634,6 @@ doesn't conflict with concurrent PRs.
- lingo_dev
- linkedin_pages
- linnworks
-- linode
- llama_cloud
- lokalise
- looker
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.py
index acd877b1f0ee..45b8a5d85f49 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
@@ -2136,7 +2136,7 @@ class LinnworksSourceConfig(config.Config):
@config.config
class LinodeSourceConfig(config.Config):
- pass
+ api_token: str
@config.config
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/linode/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/linode/canonical_descriptions.py
new file mode 100644
index 000000000000..8ceb2b8fe413
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/linode/canonical_descriptions.py
@@ -0,0 +1,120 @@
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (
+ CanonicalDescriptions,
+)
+
+# Descriptions sourced from the Linode (Akamai Connected Cloud) API v4 docs at
+# https://techdocs.akamai.com/linode-api/reference. Partial coverage is fine; anything not listed
+# falls back to LLM enrichment.
+CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
+ "linodes": {
+ "description": "Linode instances (virtual machines) on the account.",
+ "docs_url": "https://techdocs.akamai.com/linode-api/reference/get-linode-instances",
+ "columns": {
+ "id": "Unique identifier for the Linode instance.",
+ "label": "The user-supplied label for this Linode.",
+ "region": "The region (data center) where the Linode is deployed.",
+ "type": "The Linode plan type (e.g. g6-standard-2) that determines its resources.",
+ "status": "Current run status of the Linode (e.g. running, offline, provisioning).",
+ "ipv4": "The public and private IPv4 addresses assigned to this Linode.",
+ "ipv6": "The IPv6 range assigned to this Linode.",
+ "created": "When this Linode was created.",
+ "updated": "When this Linode was last updated.",
+ },
+ },
+ "volumes": {
+ "description": "Block storage volumes on the account.",
+ "docs_url": "https://techdocs.akamai.com/linode-api/reference/get-volumes",
+ "columns": {
+ "id": "Unique identifier for the volume.",
+ "label": "The user-supplied label for this volume.",
+ "status": "Current status of the volume (e.g. active, creating, resizing).",
+ "size": "Size of the volume in GB.",
+ "region": "The region where the volume resides.",
+ "linode_id": "The id of the Linode the volume is attached to, or null if detached.",
+ "created": "When this volume was created.",
+ "updated": "When this volume was last updated.",
+ },
+ },
+ "nodebalancers": {
+ "description": "NodeBalancers (managed load balancers) on the account.",
+ "docs_url": "https://techdocs.akamai.com/linode-api/reference/get-node-balancers",
+ "columns": {
+ "id": "Unique identifier for the NodeBalancer.",
+ "label": "The user-supplied label for this NodeBalancer.",
+ "region": "The region where the NodeBalancer is deployed.",
+ "hostname": "The public hostname of the NodeBalancer.",
+ "ipv4": "The public IPv4 address of the NodeBalancer.",
+ "created": "When this NodeBalancer was created.",
+ "updated": "When this NodeBalancer was last updated.",
+ },
+ },
+ "lke_clusters": {
+ "description": "Linode Kubernetes Engine (LKE) clusters on the account.",
+ "docs_url": "https://techdocs.akamai.com/linode-api/reference/get-lke-clusters",
+ "columns": {
+ "id": "Unique identifier for the LKE cluster.",
+ "label": "The user-supplied label for this cluster.",
+ "region": "The region where the cluster is deployed.",
+ "k8s_version": "The Kubernetes version running on the cluster's control plane.",
+ "status": "Current status of the cluster (e.g. ready, not_ready).",
+ "created": "When this cluster was created.",
+ "updated": "When this cluster was last updated.",
+ },
+ },
+ "domains": {
+ "description": "DNS domains (zones) managed by the account's DNS Manager.",
+ "docs_url": "https://techdocs.akamai.com/linode-api/reference/get-domains",
+ "columns": {
+ "id": "Unique identifier for the domain.",
+ "domain": "The domain name (e.g. example.com).",
+ "type": "Whether this is a master or slave zone.",
+ "status": "Whether the domain is active, disabled, or has an edit_mode set.",
+ "soa_email": "The start-of-authority email address for the zone.",
+ },
+ },
+ "users": {
+ "description": "Users with access to the Linode account.",
+ "docs_url": "https://techdocs.akamai.com/linode-api/reference/get-users",
+ "columns": {
+ "username": "The unique username, used as the primary key.",
+ "email": "The user's email address.",
+ "restricted": "Whether the user only has access to a subset of resources (true) or full access (false).",
+ "tfa_enabled": "Whether the user has two-factor authentication enabled.",
+ },
+ },
+ "invoices": {
+ "description": "Billing invoices issued to the account.",
+ "docs_url": "https://techdocs.akamai.com/linode-api/reference/get-invoices",
+ "columns": {
+ "id": "Unique identifier for the invoice.",
+ "date": "When the invoice was generated. Used as the incremental cursor.",
+ "label": "The name/description of the invoice.",
+ "total": "The total amount due on the invoice, in US dollars.",
+ "subtotal": "The amount of the invoice before taxes, in US dollars.",
+ "tax": "The amount of tax levied on the invoice, in US dollars.",
+ },
+ },
+ "payments": {
+ "description": "Payments made against the account.",
+ "docs_url": "https://techdocs.akamai.com/linode-api/reference/get-payments",
+ "columns": {
+ "id": "Unique identifier for the payment.",
+ "date": "When the payment was made.",
+ "usd": "The amount of the payment, in US dollars.",
+ },
+ },
+ "events": {
+ "description": "Account audit events (the last 90 days of activity). Immutable and append-only.",
+ "docs_url": "https://techdocs.akamai.com/linode-api/reference/get-events",
+ "columns": {
+ "id": "Unique, monotonically increasing identifier for the event. Used as the incremental cursor.",
+ "action": "The type of action that triggered the event (e.g. linode_boot, volume_create).",
+ "created": "When the event occurred.",
+ "entity": "The resource the event is associated with (type, id, label, url).",
+ "username": "The username of the user who triggered the event.",
+ "status": "Current status of the event (e.g. finished, failed, notification).",
+ "seen": "Whether the event has been seen.",
+ "read": "Whether the event has been read.",
+ },
+ },
+}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/linode/linode.py b/products/warehouse_sources/backend/temporal/data_imports/sources/linode/linode.py
new file mode 100644
index 000000000000..a334ced819e4
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/linode/linode.py
@@ -0,0 +1,237 @@
+import json
+import random
+import dataclasses
+from collections.abc import Iterator
+from datetime import date, datetime
+from typing import Any, Optional
+from urllib.parse import urlencode
+
+import requests
+from structlog.types import FilteringBoundLogger
+from tenacity import RetryCallState, retry, retry_if_exception_type, stop_after_attempt, wait_exponential_jitter
+
+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.batcher import Batcher
+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.linode.settings import (
+ LINODE_ENDPOINTS,
+ LinodeEndpointConfig,
+)
+
+LINODE_BASE_URL = "https://api.linode.com/v4"
+
+# Max allowed page_size is 500 (min 25). Using the max minimizes request count against the 200 req/min
+# paginated-GET rate limit.
+PAGE_SIZE = 500
+
+# Cap on how long we honor a rate-limit Retry-After before retrying, so a misreported header can't
+# stall a worker indefinitely. The source iterator runs in a thread pool while the activity heartbeat
+# fires from the event loop, so a 60s wait here does not trip the heartbeat timeout.
+MAX_RETRY_AFTER_SECONDS = 60.0
+
+
+class LinodeRetryableError(Exception):
+ """Raised for 429/5xx responses so the tenacity layer retries. Carries the server's Retry-After
+ (seconds) when present so we can wait exactly as long as Linode asks."""
+
+ def __init__(self, message: str, retry_after: float | None = None) -> None:
+ super().__init__(message)
+ self.retry_after = retry_after
+
+
+def _get_headers(api_token: str) -> dict[str, str]:
+ return {
+ "Authorization": f"Bearer {api_token}",
+ "Accept": "application/json",
+ }
+
+
+def _format_filter_value(value: Any) -> Any:
+ """Format an incremental cursor value for a Linode X-Filter comparison.
+
+ Integer cursors (event id) pass through unchanged. Datetime/date cursors are rendered as the
+ `YYYY-MM-DDTHH:MM:SS` form Linode uses for its own timestamp fields (no timezone offset)."""
+ if isinstance(value, datetime):
+ return value.strftime("%Y-%m-%dT%H:%M:%S")
+ if isinstance(value, date):
+ return value.strftime("%Y-%m-%dT%H:%M:%S")
+ return value
+
+
+def _build_x_filter(field: str, value: Any) -> dict[str, Any]:
+ """Build the JSON X-Filter body. Always orders ascending on the cursor field so pages arrive in
+ the order SourceResponse.sort_mode ("asc") promises; adds a `+gte` bound when a watermark exists.
+
+ The header is sent identically on every page request, so the server applies the filter and order
+ to the full result set — pagination naturally terminates at the watermark, no client-side stop
+ needed (unlike APIs that only window the first page)."""
+ x_filter: dict[str, Any] = {"+order_by": field, "+order": "asc"}
+ if value is not None:
+ x_filter[field] = {"+gte": _format_filter_value(value)}
+ return x_filter
+
+
+class LinodeResumeConfig:
+ # Next page (1-indexed) to fetch. The X-Filter header (built from the run's fixed watermark) and
+ # page_size are constant across a run, so the page number alone is enough to resume.
+ next_page: int
+
+
+def _page_url(path: str, page: int) -> str:
+ return f"{LINODE_BASE_URL}{path}?{urlencode({'page': page, 'page_size': PAGE_SIZE})}"
+
+
+def validate_credentials(api_token: str) -> tuple[bool, str | None]:
+ """Confirm the token is genuine by hitting /profile, which any valid token can read regardless of
+ its granted scopes — so a token that only has scopes for some endpoints still validates."""
+ try:
+ response = make_tracked_session(redact_values=(api_token,)).get(
+ f"{LINODE_BASE_URL}/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 == 401:
+ return False, "Invalid Linode API token"
+ # Don't surface the raw response body: Linode error bodies can echo account/resource details, and
+ # this message is persisted on the source. The status code alone is enough to diagnose.
+ return False, f"Linode API returned {response.status_code}"
+
+
+_backoff_wait = wait_exponential_jitter(initial=1, max=30)
+
+
+def _retry_wait(state: RetryCallState) -> float:
+ """Honor Linode's Retry-After on a rate limit (capped, plus jitter), else exponential backoff."""
+ if state.outcome is not None and state.outcome.failed:
+ exc = state.outcome.exception()
+ if isinstance(exc, LinodeRetryableError) and exc.retry_after is not None:
+ return min(float(exc.retry_after), MAX_RETRY_AFTER_SECONDS) + random.uniform(0, 1)
+ return _backoff_wait(state)
+
+
+@retry(
+ retry=retry_if_exception_type(
+ (
+ LinodeRetryableError,
+ requests.ReadTimeout,
+ requests.ConnectionError,
+ # A mid-stream connection break on a chunked body; transient like ConnectionError but not a
+ # subclass of it, so it needs its own entry.
+ requests.exceptions.ChunkedEncodingError,
+ )
+ ),
+ stop=stop_after_attempt(5),
+ wait=_retry_wait,
+ reraise=True,
+)
+def _fetch_page(session: requests.Session, url: str, headers: dict[str, str], logger: FilteringBoundLogger) -> dict:
+ response = session.get(url, headers=headers, timeout=60)
+
+ if response.status_code == 429 or response.status_code >= 500:
+ retry_after = response.headers.get("Retry-After")
+ raise LinodeRetryableError(
+ f"Linode API error (retryable): status={response.status_code}, url={url}",
+ retry_after=float(retry_after) if retry_after and retry_after.isdigit() else None,
+ )
+
+ if not response.ok:
+ # Log only status and URL, never response.text: Linode error bodies can echo account, billing,
+ # user, and audit data, and logs sit outside the warehouse table's access controls.
+ logger.error(f"Linode API error: status={response.status_code}, url={url}")
+ response.raise_for_status()
+
+ return response.json()
+
+
+def get_rows(
+ api_token: str,
+ endpoint: str,
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[LinodeResumeConfig],
+ should_use_incremental_field: bool = False,
+ db_incremental_field_last_value: Any = None,
+ incremental_field: str | None = None,
+) -> Iterator[Any]:
+ config = LINODE_ENDPOINTS[endpoint]
+ headers = _get_headers(api_token)
+
+ # Attach the X-Filter header for incremental/append endpoints. Honor the user's chosen cursor
+ # field, falling back to the endpoint's declared filterable field. On the first sync the watermark
+ # is None, so we send only the ordering (no +gte bound) and pull the full available window.
+ if config.incremental_field is not None and should_use_incremental_field:
+ cursor_field = incremental_field or config.incremental_field
+ headers["X-Filter"] = json.dumps(_build_x_filter(cursor_field, db_incremental_field_last_value))
+
+ batcher = Batcher(logger=logger, chunk_size=2000, chunk_size_bytes=100 * 1024 * 1024)
+ session = make_tracked_session(redact_values=(api_token,))
+
+ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None
+ page = resume.next_page if resume is not None else 1
+ if resume is not None:
+ logger.debug(f"Linode: resuming {endpoint} from page {page}")
+
+ while True:
+ data = _fetch_page(session, _page_url(config.path, page), headers, logger)
+ items = data.get("data") or []
+ total_pages = data.get("pages") or 1
+
+ for item in items:
+ batcher.batch(item)
+ if batcher.should_yield():
+ yield batcher.get_table()
+
+ if page >= total_pages:
+ break
+
+ # Advance the resume checkpoint only once the batcher has fully drained at this page boundary.
+ # The batcher aggregates rows across pages, so anything still buffered belongs to pages at or
+ # before this one and has not been yielded yet (and so not committed downstream). Persisting
+ # next_page while rows are buffered would skip them on resume — permanent loss for append-only
+ # endpoints. Holding the checkpoint until a drained boundary keeps resume at-least-once: a crash
+ # re-fetches from the last fully-committed page rather than dropping rows.
+ if not batcher.should_yield(include_incomplete_chunk=True):
+ resumable_source_manager.save_state(LinodeResumeConfig(next_page=page + 1))
+
+ page += 1
+
+ if batcher.should_yield(include_incomplete_chunk=True):
+ yield batcher.get_table()
+
+
+def linode_source(
+ api_token: str,
+ endpoint: str,
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[LinodeResumeConfig],
+ should_use_incremental_field: bool = False,
+ db_incremental_field_last_value: Optional[Any] = None,
+ incremental_field: str | None = None,
+) -> SourceResponse:
+ endpoint_config: LinodeEndpointConfig = LINODE_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,
+ incremental_field=incremental_field,
+ ),
+ primary_keys=endpoint_config.primary_keys,
+ # The X-Filter header orders results ascending on the cursor field, so rows arrive oldest-first
+ # and the watermark advances safely after each batch.
+ sort_mode="asc",
+ partition_count=1,
+ partition_size=1,
+ partition_mode="datetime" if endpoint_config.partition_key else None,
+ partition_format="month" if endpoint_config.partition_key else None,
+ partition_keys=[endpoint_config.partition_key] if endpoint_config.partition_key else None,
+ )
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/linode/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/linode/settings.py
new file mode 100644
index 000000000000..922a17e193f1
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/linode/settings.py
@@ -0,0 +1,116 @@
+from dataclasses import dataclass, field
+from typing import Optional
+
+from products.warehouse_sources.backend.types import IncrementalField, IncrementalFieldType
+
+
+@dataclass
+class LinodeEndpointConfig:
+ name: str
+ path: str
+ incremental_fields: list[IncrementalField]
+ # Primary key columns for dedup on merge. All Linode collections expose a globally unique `id`
+ # except users, which key on `username` instead.
+ primary_keys: list[str] = field(default_factory=lambda: ["id"])
+ # Stable datetime field to partition by. Must never change once set (e.g. `created`, `date`),
+ # so a row never migrates partitions. None leaves the table unpartitioned (no stable timestamp).
+ partition_key: Optional[str] = None
+ # The field passed to the Linode `X-Filter` header for server-side incremental sync. It must be
+ # documented as filterable AND orderable on this endpoint. None means full refresh only.
+ incremental_field: Optional[str] = None
+ # Events are an immutable, append-only audit log capped to the last 90 days by the API, so they
+ # can only ever be appended, never merged/upserted.
+ append_only: bool = False
+ should_sync_default: bool = True
+
+
+# Linode API v4 (https://api.linode.com/v4). Every list endpoint shares the same page/page_size query
+# params and the {data, page, pages, results} response envelope, so a single paginated client fits all.
+#
+# Incremental sync uses the JSON `X-Filter` header with the `+gte`/`+order_by`/`+order` operators on
+# fields the API documents as filterable. Only `events` (by monotonic integer id) and `invoices` (by
+# date) expose a genuine server-side filter; the infrastructure inventories are small and their
+# created/updated timestamps are not consistently filterable, so they ship full refresh.
+LINODE_ENDPOINTS: dict[str, LinodeEndpointConfig] = {
+ "linodes": LinodeEndpointConfig(
+ name="linodes",
+ path="/linode/instances",
+ partition_key="created",
+ incremental_fields=[],
+ ),
+ "volumes": LinodeEndpointConfig(
+ name="volumes",
+ path="/volumes",
+ partition_key="created",
+ incremental_fields=[],
+ ),
+ "nodebalancers": LinodeEndpointConfig(
+ name="nodebalancers",
+ path="/nodebalancers",
+ partition_key="created",
+ incremental_fields=[],
+ ),
+ "lke_clusters": LinodeEndpointConfig(
+ name="lke_clusters",
+ path="/lke/clusters",
+ partition_key="created",
+ incremental_fields=[],
+ ),
+ "domains": LinodeEndpointConfig(
+ name="domains",
+ path="/domains",
+ # Domain objects carry no creation/update timestamp, so there is nothing stable to partition on.
+ incremental_fields=[],
+ ),
+ "users": LinodeEndpointConfig(
+ name="users",
+ path="/account/users",
+ primary_keys=["username"],
+ incremental_fields=[],
+ ),
+ "invoices": LinodeEndpointConfig(
+ name="invoices",
+ path="/account/invoices",
+ partition_key="date",
+ incremental_field="date",
+ incremental_fields=[
+ {
+ "label": "date",
+ "type": IncrementalFieldType.DateTime,
+ "field": "date",
+ "field_type": IncrementalFieldType.DateTime,
+ },
+ ],
+ ),
+ "payments": LinodeEndpointConfig(
+ name="payments",
+ path="/account/payments",
+ partition_key="date",
+ # Payments carry a `date`, but the API docs don't clearly mark it filterable and we couldn't
+ # confirm it against the live API, so ship full refresh (the billing history is small).
+ incremental_fields=[],
+ ),
+ "events": LinodeEndpointConfig(
+ name="events",
+ path="/account/events",
+ partition_key="created",
+ # Event ids increase monotonically, so the id `+gte` filter is the cheapest reliable cursor and
+ # avoids any datetime formatting ambiguity. Events only retain 90 days upstream regardless.
+ incremental_field="id",
+ append_only=True,
+ incremental_fields=[
+ {
+ "label": "id",
+ "type": IncrementalFieldType.Integer,
+ "field": "id",
+ "field_type": IncrementalFieldType.Integer,
+ },
+ ],
+ ),
+}
+
+ENDPOINTS = tuple(LINODE_ENDPOINTS.keys())
+
+INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {
+ name: config.incremental_fields for name, config in LINODE_ENDPOINTS.items()
+}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/linode/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/linode/source.py
index c5a499aa265a..8150961478dc 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/linode/source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/linode/source.py
@@ -1,19 +1,41 @@
-from typing import cast
+from typing import Optional, cast
from posthog.schema import (
DataWarehouseSourceCategory,
ExternalDataSourceType as SchemaExternalDataSourceType,
+ ReleaseStatus,
SourceConfig,
+ SourceFieldInputConfig,
+ SourceFieldInputConfigType,
)
-from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, SimpleSource
+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import (
+ SourceInputs,
+ SourceResponse,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, ResumableSource
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (
+ CanonicalDescriptions,
+)
from products.warehouse_sources.backend.temporal.data_imports.sources.common.registry import SourceRegistry
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.schema import SourceSchema
from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs import LinodeSourceConfig
+from products.warehouse_sources.backend.temporal.data_imports.sources.linode.linode import (
+ LinodeResumeConfig,
+ linode_source,
+ validate_credentials as validate_linode_credentials,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.linode.settings import ENDPOINTS, LINODE_ENDPOINTS
from products.warehouse_sources.backend.types import ExternalDataSourceType
@SourceRegistry.register
-class LinodeSource(SimpleSource[LinodeSourceConfig]):
+class LinodeSource(ResumableSource[LinodeSourceConfig, LinodeResumeConfig]):
+ # get_schemas iterates the static ENDPOINTS catalog with no I/O, so the table list is safe to
+ # render in public docs without credentials.
+ lists_tables_without_credentials = True
+
@property
def source_type(self) -> ExternalDataSourceType:
return ExternalDataSourceType.LINODE
@@ -24,8 +46,103 @@ class LinodeSource(SimpleSource[LinodeSourceConfig]):
name=SchemaExternalDataSourceType.LINODE,
category=DataWarehouseSourceCategory.ENGINEERING___MONITORING,
label="Linode",
- iconPath="/static/services/linode.png",
+ releaseStatus=ReleaseStatus.ALPHA,
+ caption="""Enter your Linode (Akamai Connected Cloud) personal access token to pull your account data into the PostHog Data warehouse.
+
+Create a personal access token in the [Linode Cloud Manager](https://cloud.linode.com/profile/tokens). Grant **read-only** access to the resources you want to sync:
+- Account (invoices, payments, events, users)
+- Linodes
+- Volumes
+- NodeBalancers
+- Kubernetes
+- Domains
+""",
+ iconPath="/static/services/linode.svg",
+ docsUrl="https://posthog.com/docs/cdp/sources/linode",
keywords=["cloud", "infrastructure", "hosting", "akamai"],
- fields=cast(list[FieldType], []),
+ fields=cast(
+ list[FieldType],
+ [
+ SourceFieldInputConfig(
+ name="api_token",
+ label="Personal access token",
+ type=SourceFieldInputConfigType.PASSWORD,
+ required=True,
+ placeholder="",
+ secret=True,
+ ),
+ ],
+ ),
+ # Kept hidden until the sync logic has been exercised against a live account (we could not
+ # curl-verify the incremental X-Filter behavior without credentials).
unreleasedSource=True,
)
+
+ def get_canonical_descriptions(self) -> CanonicalDescriptions:
+ from products.warehouse_sources.backend.temporal.data_imports.sources.linode.canonical_descriptions import (
+ CANONICAL_DESCRIPTIONS,
+ )
+
+ return CANONICAL_DESCRIPTIONS
+
+ def get_non_retryable_errors(self) -> dict[str, str | None]:
+ return {
+ # A revoked/invalid token surfaces as a requests HTTPError when `_fetch_page` calls
+ # `raise_for_status()`. Retrying can never satisfy a credential problem. Match the stable
+ # status text and base host, not the per-request path/query.
+ "401 Client Error: Unauthorized for url: https://api.linode.com": "Your Linode API token is invalid or has been revoked. Create a new personal access token in the Linode Cloud Manager, then reconnect.",
+ "403 Client Error: Forbidden for url: https://api.linode.com": "Your Linode API token is missing the read scopes needed to sync this data. Grant the required read-only access in the Linode Cloud Manager, then reconnect.",
+ }
+
+ def get_schemas(
+ self,
+ config: LinodeSourceConfig,
+ team_id: int,
+ with_counts: bool = False,
+ names: list[str] | None = None,
+ force_refresh: bool = False,
+ ) -> list[SourceSchema]:
+ def _build_schema(endpoint: str) -> SourceSchema:
+ endpoint_config = LINODE_ENDPOINTS[endpoint]
+ has_incremental = bool(endpoint_config.incremental_fields)
+ return SourceSchema(
+ name=endpoint,
+ # Events are an immutable, append-only audit log — offer append (server-side cursor via
+ # X-Filter) but never merge/upsert. Endpoints with no server-side filter are full refresh.
+ supports_incremental=has_incremental and not endpoint_config.append_only,
+ supports_append=has_incremental,
+ incremental_fields=endpoint_config.incremental_fields,
+ should_sync_default=endpoint_config.should_sync_default,
+ )
+
+ schemas = [_build_schema(endpoint) for endpoint in ENDPOINTS]
+ if names is not None:
+ names_set = set(names)
+ schemas = [s for s in schemas if s.name in names_set]
+ return schemas
+
+ def validate_credentials(
+ self, config: LinodeSourceConfig, team_id: int, schema_name: Optional[str] = None
+ ) -> tuple[bool, str | None]:
+ return validate_linode_credentials(config.api_token)
+
+ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[LinodeResumeConfig]:
+ return ResumableSourceManager[LinodeResumeConfig](inputs, LinodeResumeConfig)
+
+ def source_for_pipeline(
+ self,
+ config: LinodeSourceConfig,
+ resumable_source_manager: ResumableSourceManager[LinodeResumeConfig],
+ inputs: SourceInputs,
+ ) -> SourceResponse:
+ return linode_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,
+ incremental_field=inputs.incremental_field,
+ )
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/linode/tests/test_linode.py b/products/warehouse_sources/backend/temporal/data_imports/sources/linode/tests/test_linode.py
new file mode 100644
index 000000000000..47fe52540a20
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/linode/tests/test_linode.py
@@ -0,0 +1,293 @@
+import json
+from datetime import UTC, date, datetime
+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.linode import linode
+from products.warehouse_sources.backend.temporal.data_imports.sources.linode.linode import (
+ PAGE_SIZE,
+ LinodeResumeConfig,
+ LinodeRetryableError,
+ _build_x_filter,
+ _format_filter_value,
+ _page_url,
+ get_rows,
+ linode_source,
+ validate_credentials,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.linode.settings import LINODE_ENDPOINTS
+
+
+class TestFormatFilterValue:
+ @parameterized.expand(
+ [
+ ("integer_passthrough", 12345, 12345),
+ ("string_passthrough", "abc", "abc"),
+ ("aware_datetime", datetime(2026, 3, 4, 2, 58, 14, tzinfo=UTC), "2026-03-04T02:58:14"),
+ ("naive_datetime", datetime(2026, 3, 4, 2, 58, 14), "2026-03-04T02:58:14"),
+ ("date_value", date(2026, 3, 4), "2026-03-04T00:00:00"),
+ ]
+ )
+ def test_format_filter_value(self, _name: str, value: Any, expected: Any) -> None:
+ # A "+00:00" offset in the filter value would make Linode reject the X-Filter, so datetimes
+ # must render without one.
+ assert _format_filter_value(value) == expected
+
+
+class TestBuildXFilter:
+ def test_first_sync_has_no_gte_bound(self) -> None:
+ # A missing watermark must produce an order-only filter, never `{"+gte": None}`, which the API
+ # would reject and wedge every first sync.
+ assert _build_x_filter("id", None) == {"+order_by": "id", "+order": "asc"}
+
+ def test_watermark_adds_ascending_gte_bound(self) -> None:
+ # Ordering must always be ascending so rows arrive oldest-first, matching sort_mode="asc";
+ # otherwise the watermark would checkpoint to ~now after the first batch.
+ assert _build_x_filter("date", datetime(2026, 3, 4, 2, 58, 14)) == {
+ "+order_by": "date",
+ "+order": "asc",
+ "date": {"+gte": "2026-03-04T02:58:14"},
+ }
+
+
+class TestValidateCredentials:
+ @parameterized.expand(
+ [
+ ("valid", 200, True),
+ ("invalid_token", 401, False),
+ ("forbidden", 403, False),
+ ("server_error", 500, False),
+ ]
+ )
+ def test_status_mapping(self, _name: str, status_code: int, expected_valid: bool) -> None:
+ response = MagicMock()
+ response.status_code = status_code
+ response.text = "body"
+ with patch.object(linode, "make_tracked_session") as mock_session:
+ mock_session.return_value.get.return_value = response
+ valid, _message = validate_credentials("tok")
+ assert valid is expected_valid
+
+ def test_network_error_is_not_valid(self) -> None:
+ with patch.object(linode, "make_tracked_session") as mock_session:
+ mock_session.return_value.get.side_effect = requests.ConnectionError("boom")
+ valid, message = validate_credentials("tok")
+ assert valid is False
+ assert message is not None
+
+ def test_token_is_registered_for_redaction(self) -> None:
+ # The PAT rides in an Authorization header the value-based scrubber can only mask if the token
+ # is registered via redact_values; dropping it would leak the credential into HTTP telemetry.
+ response = MagicMock()
+ response.status_code = 200
+ with patch.object(linode, "make_tracked_session") as mock_session:
+ mock_session.return_value.get.return_value = response
+ validate_credentials("tok")
+ assert mock_session.call_args.kwargs["redact_values"] == ("tok",)
+
+ def test_error_status_does_not_leak_response_body(self) -> None:
+ # Linode error bodies can echo account data; the persisted validation message must not carry it.
+ response = MagicMock()
+ response.status_code = 500
+ response.text = "secret account details"
+ with patch.object(linode, "make_tracked_session") as mock_session:
+ mock_session.return_value.get.return_value = response
+ _valid, message = validate_credentials("tok")
+ assert message is not None
+ assert "secret account details" not in message
+
+
+class TestFetchPageRetries:
+ @parameterized.expand([("rate_limited", 429), ("server_error", 503)])
+ def test_retryable_statuses_raise_retryable_error(self, _name: str, status_code: int) -> None:
+ response = MagicMock()
+ response.status_code = status_code
+ response.headers = {"Retry-After": "1"}
+ session = MagicMock()
+ session.get.return_value = response
+
+ with patch.object(linode._fetch_page.retry, "sleep", lambda *_: None): # type: ignore[attr-defined]
+ with pytest.raises(LinodeRetryableError):
+ linode._fetch_page(session, "https://api.linode.com/v4/volumes", {}, MagicMock())
+
+ # 5 attempts before giving up (reraise=True).
+ assert session.get.call_count == 5
+
+ def test_non_2xx_does_not_log_response_body(self) -> None:
+ # Error bodies can carry account/billing/audit data; logs live outside warehouse access
+ # controls, so a failing sync must not copy the raw body into them.
+ response = MagicMock()
+ response.status_code = 404
+ response.ok = False
+ response.text = "secret account details"
+ response.raise_for_status.side_effect = requests.RequestException("404")
+ session = MagicMock()
+ session.get.return_value = response
+ logger = MagicMock()
+
+ with pytest.raises(requests.RequestException):
+ linode._fetch_page(session, "https://api.linode.com/v4/volumes", {}, logger)
+
+ logged = " ".join(str(call) for call in logger.error.call_args_list)
+ assert "secret account details" not in logged
+
+ def test_transient_error_retried_then_succeeds(self) -> None:
+ good = MagicMock()
+ good.status_code = 200
+ good.ok = True
+ good.json.return_value = {"data": [], "pages": 1}
+ session = MagicMock()
+ session.get.side_effect = [requests.ReadTimeout("slow"), good]
+
+ with patch.object(linode._fetch_page.retry, "sleep", lambda *_: None): # type: ignore[attr-defined]
+ result = linode._fetch_page(session, "https://api.linode.com/v4/volumes", {}, MagicMock())
+
+ assert result == {"data": [], "pages": 1}
+ assert session.get.call_count == 2
+
+
+class _FakeResumableManager:
+ def __init__(self, state: LinodeResumeConfig | None = None) -> None:
+ self._state = state
+ self.saved: list[LinodeResumeConfig] = []
+
+ def can_resume(self) -> bool:
+ return self._state is not None
+
+ def load_state(self) -> LinodeResumeConfig | None:
+ return self._state
+
+ def save_state(self, data: LinodeResumeConfig) -> None:
+ self.saved.append(data)
+
+
+class TestGetRows:
+ @staticmethod
+ def _collect(
+ manager: _FakeResumableManager, pages_by_url: dict[str, Any], endpoint: str = "volumes", **incremental: Any
+ ) -> tuple[list[dict], list[dict[str, str]]]:
+ captured_headers: list[dict[str, str]] = []
+
+ def fake_fetch(session: Any, url: str, headers: dict[str, str], logger: Any) -> dict:
+ captured_headers.append(dict(headers))
+ return pages_by_url[url]
+
+ rows: list[dict] = []
+ with patch.object(linode, "_fetch_page", fake_fetch):
+ for table in get_rows(
+ api_token="tok",
+ endpoint=endpoint,
+ logger=MagicMock(),
+ resumable_source_manager=manager, # type: ignore[arg-type]
+ **incremental,
+ ):
+ rows.extend(table.to_pylist())
+ return rows, captured_headers
+
+ def test_paginates_across_all_pages(self) -> None:
+ pages = {
+ _page_url("/volumes", 1): {"data": [{"id": 1}, {"id": 2}], "page": 1, "pages": 2},
+ _page_url("/volumes", 2): {"data": [{"id": 3}], "page": 2, "pages": 2},
+ }
+ rows, _headers = self._collect(_FakeResumableManager(), pages)
+ assert [r["id"] for r in rows] == [1, 2, 3]
+
+ def test_resumes_from_saved_page(self) -> None:
+ # Fixtures omit page 1, so resuming anywhere other than page 2 fails loudly with a KeyError.
+ pages = {_page_url("/volumes", 2): {"data": [{"id": 3}], "page": 2, "pages": 2}}
+ rows, _headers = self._collect(_FakeResumableManager(LinodeResumeConfig(next_page=2)), pages)
+ assert [r["id"] for r in rows] == [3]
+
+ def test_full_refresh_sends_no_x_filter(self) -> None:
+ pages = {_page_url("/volumes", 1): {"data": [{"id": 1}], "page": 1, "pages": 1}}
+ _rows, headers = self._collect(
+ _FakeResumableManager(),
+ pages,
+ should_use_incremental_field=False,
+ db_incremental_field_last_value=datetime(2026, 3, 4, tzinfo=UTC),
+ )
+ assert all("X-Filter" not in h for h in headers)
+
+ def test_incremental_endpoint_attaches_x_filter_with_watermark(self) -> None:
+ # A regression that stops threading the watermark into the X-Filter would silently revert
+ # incremental events to a full refresh; assert the id `+gte` bound is present on the request.
+ pages = {_page_url("/account/events", 1): {"data": [{"id": 5}], "page": 1, "pages": 1}}
+ _rows, headers = self._collect(
+ _FakeResumableManager(),
+ pages,
+ endpoint="events",
+ should_use_incremental_field=True,
+ db_incremental_field_last_value=4,
+ incremental_field="id",
+ )
+ assert json.loads(headers[0]["X-Filter"]) == {"+order_by": "id", "+order": "asc", "id": {"+gte": 4}}
+
+ def test_page_size_is_maxed(self) -> None:
+ assert f"page_size={PAGE_SIZE}" in _page_url("/volumes", 1)
+ assert PAGE_SIZE == 500
+
+ def test_sync_session_registers_token_for_redaction(self) -> None:
+ # Same leak surface as validation: the sync session sends the PAT on every paginated request,
+ # so it must register the token for value-based masking.
+ pages = {_page_url("/volumes", 1): {"data": [{"id": 1}], "page": 1, "pages": 1}}
+ with patch.object(linode, "make_tracked_session") as mock_session:
+ self._collect(_FakeResumableManager(), pages)
+ assert mock_session.call_args.kwargs["redact_values"] == ("tok",)
+
+ def test_checkpoint_only_advances_past_fully_drained_pages(self) -> None:
+ # The resume checkpoint must never advance past a page while rows from it are still buffered
+ # (unyielded, so uncommitted downstream) — doing so would skip them on resume, permanent loss
+ # for append-only endpoints. chunk_size is 2000, so:
+ # page 1 (2000 rows) yields one chunk and drains the batcher -> checkpoint page 2.
+ # page 2 (2001 rows) yields a chunk but leaves a 1-row tail buffered -> must NOT checkpoint.
+ pages = {
+ _page_url("/volumes", 1): {"data": [{"id": i} for i in range(2000)], "page": 1, "pages": 3},
+ _page_url("/volumes", 2): {"data": [{"id": 2000 + i} for i in range(2001)], "page": 2, "pages": 3},
+ _page_url("/volumes", 3): {"data": [{"id": 9001}], "page": 3, "pages": 3},
+ }
+ manager = _FakeResumableManager()
+ rows, _headers = self._collect(manager, pages)
+ assert len(rows) == 4002
+ # Only the drained page-1 boundary checkpoints; the straddling page-2 boundary is held back.
+ assert manager.saved == [LinodeResumeConfig(next_page=2)]
+
+
+class TestLinodeSource:
+ def test_sort_mode_is_ascending(self) -> None:
+ response = linode_source(
+ api_token="tok", endpoint="events", logger=MagicMock(), resumable_source_manager=MagicMock()
+ )
+ assert response.sort_mode == "asc"
+
+ @parameterized.expand(
+ [
+ ("invoices", "date", True),
+ ("events", "created", True),
+ ("domains", None, False),
+ ("users", None, False),
+ ]
+ )
+ def test_partitioning_matches_stable_field(
+ self, endpoint: str, partition_key: str | None, partitioned: bool
+ ) -> None:
+ response = linode_source(
+ api_token="tok", endpoint=endpoint, logger=MagicMock(), resumable_source_manager=MagicMock()
+ )
+ if partitioned:
+ assert response.partition_keys == [partition_key]
+ assert response.partition_mode == "datetime"
+ else:
+ assert response.partition_keys is None
+ assert response.partition_mode is None
+
+ def test_primary_keys_come_from_endpoint_config(self) -> None:
+ response = linode_source(
+ api_token="tok", endpoint="users", logger=MagicMock(), resumable_source_manager=MagicMock()
+ )
+ assert response.primary_keys == ["username"]
+ assert LINODE_ENDPOINTS["events"].primary_keys == ["id"]
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/linode/tests/test_linode_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/linode/tests/test_linode_source.py
new file mode 100644
index 000000000000..feb152330760
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/linode/tests/test_linode_source.py
@@ -0,0 +1,127 @@
+from typing import Any
+
+from unittest.mock import MagicMock, patch
+
+from parameterized import parameterized
+
+from posthog.schema import SourceFieldInputConfig, SourceFieldInputConfigType
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.linode.linode import LinodeResumeConfig
+from products.warehouse_sources.backend.temporal.data_imports.sources.linode.source import LinodeSource
+from products.warehouse_sources.backend.types import ExternalDataSourceType
+
+
+def _make_config() -> Any:
+ config = MagicMock()
+ config.api_token = "tok"
+ return config
+
+
+class TestLinodeSourceClass:
+ def setup_method(self) -> None:
+ self.source = LinodeSource()
+ self.team_id = 123
+
+ def test_source_type(self) -> None:
+ assert self.source.source_type == ExternalDataSourceType.LINODE
+
+ def test_config_exposes_api_token_as_secret_password(self) -> None:
+ fields = self.source.get_source_config.fields
+ assert len(fields) == 1
+ field = fields[0]
+ assert isinstance(field, SourceFieldInputConfig)
+ assert field.name == "api_token"
+ assert field.type == SourceFieldInputConfigType.PASSWORD
+ assert field.required is True
+ assert field.secret is True
+
+ @parameterized.expand(
+ [
+ # (endpoint, supports_incremental, supports_append)
+ # Events are immutable/append-only: offer append but never merge.
+ ("events", False, True),
+ # Invoices have a genuine server-side date filter: merge-incremental.
+ ("invoices", True, True),
+ # No server-side filter -> full refresh only.
+ ("linodes", False, False),
+ ("volumes", False, False),
+ ("domains", False, False),
+ ("users", False, False),
+ ("payments", False, False),
+ ]
+ )
+ def test_schema_sync_modes(self, endpoint: str, supports_incremental: bool, supports_append: bool) -> None:
+ schemas = {s.name: s for s in self.source.get_schemas(_make_config(), self.team_id)}
+ assert endpoint in schemas
+ schema = schemas[endpoint]
+ assert schema.supports_incremental is supports_incremental
+ assert schema.supports_append is supports_append
+
+ def test_get_schemas_filters_by_names(self) -> None:
+ schemas = self.source.get_schemas(_make_config(), self.team_id, names=["events", "volumes"])
+ assert {s.name for s in schemas} == {"events", "volumes"}
+
+ def test_documented_tables_render_for_public_docs(self) -> None:
+ # lists_tables_without_credentials + a static get_schemas power the posthog.com Supported
+ # tables section; if either regresses the docs silently render nothing.
+ assert self.source.lists_tables_without_credentials is True
+ docs = {d["name"]: d for d in self.source.get_documented_tables()}
+ assert set(docs) == {s.name for s in self.source.get_schemas(_make_config(), self.team_id)}
+ assert docs["events"]["sync_methods"] == ["Append only", "Full refresh"]
+ assert docs["invoices"]["sync_methods"] == ["Incremental", "Full refresh"]
+ assert docs["linodes"]["sync_methods"] == ["Full refresh"]
+ # Canonical descriptions should flow through so the docs aren't blank.
+ assert docs["events"]["description"]
+
+ @parameterized.expand(
+ [
+ ("401 Client Error: Unauthorized for url: https://api.linode.com/v4/volumes?page=1",),
+ ("403 Client Error: Forbidden for url: https://api.linode.com/v4/account/events",),
+ ]
+ )
+ def test_credential_errors_are_non_retryable(self, observed_error: str) -> None:
+ non_retryable = self.source.get_non_retryable_errors()
+ assert any(key in observed_error for key in non_retryable)
+
+ def test_transient_error_stays_retryable(self) -> None:
+ non_retryable = self.source.get_non_retryable_errors()
+ observed = "500 Server Error: Internal Server Error for url: https://api.linode.com/v4/volumes"
+ assert not any(key in observed for key in non_retryable)
+
+ def test_validate_credentials_delegates(self) -> None:
+ with patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.linode.source.validate_linode_credentials",
+ return_value=(True, None),
+ ) as mock_validate:
+ valid, message = self.source.validate_credentials(_make_config(), self.team_id)
+ assert valid is True
+ assert message is None
+ mock_validate.assert_called_once_with("tok")
+
+ def test_get_resumable_source_manager_is_bound_to_resume_config(self) -> None:
+ manager = self.source.get_resumable_source_manager(MagicMock())
+ assert manager._data_class is LinodeResumeConfig
+
+ def test_source_for_pipeline_omits_watermark_when_not_incremental(self) -> None:
+ # A full-refresh run must not forward a stale last-value, or the transport would build an
+ # X-Filter and silently window the results.
+ inputs = MagicMock()
+ inputs.schema_name = "volumes"
+ inputs.should_use_incremental_field = False
+ inputs.db_incremental_field_last_value = "2026-01-01T00:00:00"
+ inputs.incremental_field = None
+
+ captured: dict[str, Any] = {}
+
+ def fake_source(**kwargs: Any) -> Any:
+ captured.update(kwargs)
+ return MagicMock()
+
+ with patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.linode.source.linode_source",
+ side_effect=fake_source,
+ ):
+ self.source.source_for_pipeline(_make_config(), MagicMock(), inputs)
+
+ assert captured["should_use_incremental_field"] is False
+ assert captured["db_incremental_field_last_value"] is None