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(warehouse-sources): add linode types, regions, transfer and invoice item tables (#114528)

Tom Owers2c555e2cf988
diff --git a/posthog/test/repo_invariants/dataclass_frozen_baseline.txt b/posthog/test/repo_invariants/dataclass_frozen_baseline.txt
index 85fc4a231986..d4a83c09bca7 100644
--- a/posthog/test/repo_invariants/dataclass_frozen_baseline.txt
+++ b/posthog/test/repo_invariants/dataclass_frozen_baseline.txt
@@ -769,7 +769,6 @@
1 products/warehouse_sources/backend/temporal/data_imports/sources/linkrunner/linkrunner.py
1 products/warehouse_sources/backend/temporal/data_imports/sources/linkrunner/settings.py
1 products/warehouse_sources/backend/temporal/data_imports/sources/linode/linode.py
-1 products/warehouse_sources/backend/temporal/data_imports/sources/linode/settings.py
1 products/warehouse_sources/backend/temporal/data_imports/sources/llama_cloud/llama_cloud.py
1 products/warehouse_sources/backend/temporal/data_imports/sources/llama_cloud/settings.py
1 products/warehouse_sources/backend/temporal/data_imports/sources/lob/lob.py
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.md b/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.md
index 91b139f7d3c0..4fbfe33164ac 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.md
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.md
@@ -5221,10 +5221,10 @@ Today (9): `domains`, `events`, `invoices`, `linodes`, `lke_clusters`, `nodebala
Diffed against: <https://raw.githubusercontent.com/linode/linode-api-openapi/main/openapi.json>
-- [ ] `account/invoices/{invoiceId}/items` — invoice line items - without them the synced invoices are just totals with no cost breakdown by service (high)
-- [ ] `linode/types` — lookup resolving the plan type ID on every Linode instance we sync, plus its hourly/monthly price and specs (high)
-- [ ] `regions (and regions/availability)` — lookup resolving the region ID carried on instances, volumes, nodebalancers and buckets (high)
-- [ ] `account/transfer` — network transfer pool usage vs quota - the headline overage-risk metric (high)
+- [x] `account/invoices/{invoiceId}/items` — invoice line items - without them the synced invoices are just totals with no cost breakdown by service (high)
+- [x] `linode/types` — lookup resolving the plan type ID on every Linode instance we sync, plus its hourly/monthly price and specs (high)
+- [x] `regions (and regions/availability)` — lookup resolving the region ID carried on instances, volumes, nodebalancers and buckets (high)
+- [x] `account/transfer` — network transfer pool usage vs quota - the headline overage-risk metric (high)
- [ ] `linode/instances/{linodeId}/transfer/{year}/{month}` — per-instance monthly bandwidth usage, the breakdown behind account-level transfer (medium)
- [ ] `images` — custom and recovery images with size and expiry; a billed resource with no coverage today (medium)
- [ ] `databases/instances (plus databases/types)` — managed database inventory, a billed service class entirely absent from the current tables (medium)
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
index 8ceb2b8fe413..890a3981be66 100644
--- 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
@@ -117,4 +117,65 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
"read": "Whether the event has been read.",
},
},
+ "invoice_items": {
+ "description": "Line items on each billing invoice, breaking the invoice total down by service.",
+ "docs_url": "https://techdocs.akamai.com/linode-api/reference/get-invoice-items",
+ "columns": {
+ "invoice_id": "The id of the invoice this item belongs to.",
+ "invoice_date": "When the parent invoice was generated.",
+ "label": "The item's display label.",
+ "type": "The type of service, either hourly or misc.",
+ "region": "The id of the region this item applies to, or null if no region applies.",
+ "quantity": "The quantity of this item on the invoice.",
+ "unit_price": "The service fee per unit, in US dollars.",
+ "amount": "The price of the item before tax, in US dollars. Equal to unit_price multiplied by quantity.",
+ "tax": "The amount of tax levied on this item, in US dollars.",
+ "total": "The price of the item after tax, in US dollars.",
+ "from": "The start of the period this item covers.",
+ "to": "The end of the period this item covers.",
+ },
+ },
+ "account_transfer": {
+ "description": "Network transfer pool usage for the current billing cycle. One row, replaced on every sync.",
+ "docs_url": "https://techdocs.akamai.com/linode-api/reference/get-transfer",
+ "columns": {
+ "quota": "The amount of network transfer allowed this billing cycle, in GB.",
+ "used": "The amount of network transfer used this billing cycle, in GB.",
+ "billable": "The amount of network transfer that is billable as overage this billing cycle, in GB.",
+ "region_transfers": "Per-region transfer pools for regions with their own pricing (id, quota, used, billable).",
+ },
+ },
+ "linode_types": {
+ "description": "Linode plan types with their specs and prices. Joins to the type column on linodes.",
+ "docs_url": "https://techdocs.akamai.com/linode-api/reference/get-linode-types",
+ "columns": {
+ "id": "The id of the Linode type (e.g. g6-standard-2).",
+ "label": "The display name of the Linode type.",
+ "class": "The class of the Linode type (e.g. nanode, standard, dedicated, highmem, gpu).",
+ "vcpus": "The number of vCPU cores the type offers.",
+ "memory": "The amount of RAM the type includes, in MB.",
+ "disk": "The disk size of the type, in MB.",
+ "transfer": "The monthly outbound transfer allowance, in MB.",
+ "network_out": "The outbound bandwidth allocation, in Mbits.",
+ "gpus": "The number of GPUs the type offers.",
+ "price": "The default hourly and monthly price of the type, in US dollars.",
+ "region_prices": "Hourly and monthly prices for regions that differ from the default price.",
+ "addons": "Optional add-on services (such as backups) and their prices.",
+ "successor": "The type a Linode of this type upgrades to on mutate, or null if it can't be mutated.",
+ },
+ },
+ "regions": {
+ "description": "Regions (data centers) where resources can be deployed. Joins to the region column on other tables.",
+ "docs_url": "https://techdocs.akamai.com/linode-api/reference/get-regions",
+ "columns": {
+ "id": "The unique id of the region (e.g. us-east).",
+ "label": "Location details for the region, including city and country.",
+ "country": "The country where the region resides.",
+ "capabilities": "The services the region supports.",
+ "status": "The current operational status of the region, either ok or outage.",
+ "site_type": "The site type of the region, such as core or distributed.",
+ "resolvers": "The IPv4 and IPv6 DNS resolvers for the region.",
+ "placement_group_limits": "The placement group limits for the region.",
+ },
+ },
}
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
index ba346a518df8..ed63cb1d5529 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/linode/linode.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/linode/linode.py
@@ -1,27 +1,35 @@
import json
import dataclasses
+from collections.abc import Callable, Iterable
from datetime import date, datetime
-from typing import Any, Optional
+from typing import Any, Optional, cast
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 (
RESTAPIConfig,
rest_api_resource,
)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.fanout import (
+ build_dependent_resource,
+)
from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.paginators import (
PageNumberPaginator,
)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.typing import (
+ ClientConfig,
+ Endpoint,
+)
from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
from products.warehouse_sources.backend.temporal.data_imports.sources.common.source_helpers import validate_via_probe
from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceResponse
-from products.warehouse_sources.backend.temporal.data_imports.sources.linode.settings import LINODE_ENDPOINTS
+from products.warehouse_sources.backend.temporal.data_imports.sources.linode.settings import (
+ LINODE_ENDPOINTS,
+ PAGE_SIZE,
+ 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
-
@dataclasses.dataclass
class LinodeResumeConfig:
@@ -100,25 +108,26 @@ def linode_source(
cursor_field = incremental_field or config.incremental_field
headers["X-Filter"] = json.dumps(_build_x_filter(cursor_field, db_incremental_field_last_value))
+ client_config: ClientConfig = {
+ "base_url": LINODE_BASE_URL,
+ "headers": headers,
+ "auth": {"type": "bearer", "token": api_token},
+ # Linode returns {data, page, pages, results}; `pages` is the total page count, so the
+ # paginator stops after the last page rather than paying an extra empty-page request.
+ "paginator": PageNumberPaginator(base_page=1, page_param="page", total_path="pages"),
+ }
+
+ if config.fanout is not None:
+ return _fanout_source(config, endpoint, client_config, team_id, job_id)
+
+ endpoint_config: Endpoint = (
+ {"path": config.path, "data_selector": "$", "paginator": "single_page"}
+ if config.single_object
+ else {"path": config.path, "params": {"page_size": PAGE_SIZE}, "data_selector": "data"}
+ )
rest_config: RESTAPIConfig = {
- "client": {
- "base_url": LINODE_BASE_URL,
- "headers": headers,
- "auth": {"type": "bearer", "token": api_token},
- # Linode returns {data, page, pages, results}; `pages` is the total page count, so the
- # paginator stops after the last page rather than paying an extra empty-page request.
- "paginator": PageNumberPaginator(base_page=1, page_param="page", total_path="pages"),
- },
- "resources": [
- {
- "name": endpoint,
- "endpoint": {
- "path": config.path,
- "params": {"page_size": PAGE_SIZE},
- "data_selector": "data",
- },
- }
- ],
+ "client": client_config,
+ "resources": [{"name": endpoint, "endpoint": endpoint_config}],
}
initial_paginator_state: Optional[dict[str, Any]] = None
@@ -143,9 +152,44 @@ def linode_source(
initial_paginator_state=initial_paginator_state,
)
+ return _make_source_response(config, endpoint, lambda: resource)
+
+
+def _fanout_source(
+ config: LinodeEndpointConfig,
+ endpoint: str,
+ client_config: ClientConfig,
+ team_id: int,
+ job_id: str,
+) -> SourceResponse:
+ assert config.fanout is not None
+ # No resume state: the parent invoice list is small (one invoice per billing period), so a
+ # restarted run re-walks it cheaply.
+ dependent_resource = cast(
+ Iterable[Any],
+ build_dependent_resource(
+ endpoint_configs=LINODE_ENDPOINTS,
+ child_endpoint=endpoint,
+ fanout=config.fanout,
+ client_config=client_config,
+ path_format_values={},
+ team_id=team_id,
+ job_id=job_id,
+ db_incremental_field_last_value=None,
+ parent_endpoint_extra={"data_selector": "data"},
+ child_endpoint_extra={"data_selector": "data"},
+ page_size_param="page_size",
+ ),
+ )
+ return _make_source_response(config, endpoint, lambda: dependent_resource)
+
+
+def _make_source_response(
+ config: LinodeEndpointConfig, endpoint: str, items: Callable[[], Iterable[Any]]
+) -> SourceResponse:
return SourceResponse(
name=endpoint,
- items=lambda: resource,
+ items=items,
primary_keys=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.
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
index 922a17e193f1..d88de3b39791 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/linode/settings.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/linode/settings.py
@@ -1,17 +1,24 @@
from dataclasses import dataclass, field
from typing import Optional
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.fanout import (
+ DependentEndpointConfig,
+)
from products.warehouse_sources.backend.types import IncrementalField, IncrementalFieldType
+# 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
-@dataclass
+
+@dataclass(frozen=True)
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"])
+ # except users, which key on `username` instead. None for full-refresh tables with no unique key.
+ primary_keys: list[str] | None = 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
@@ -22,6 +29,15 @@ class LinodeEndpointConfig:
# can only ever be appended, never merged/upserted.
append_only: bool = False
should_sync_default: bool = True
+ # The endpoint returns one bare object instead of the paginated {data, page, pages} envelope.
+ single_object: bool = False
+ # Set for child resources that only exist per parent row (e.g. items under an invoice).
+ fanout: Optional[DependentEndpointConfig] = None
+ page_size: int = PAGE_SIZE
+
+ @property
+ def default_incremental_field(self) -> str | None:
+ return self.incremental_field
# Linode API v4 (https://api.linode.com/v4). Every list endpoint shares the same page/page_size query
@@ -107,6 +123,40 @@ LINODE_ENDPOINTS: dict[str, LinodeEndpointConfig] = {
},
],
),
+ "invoice_items": LinodeEndpointConfig(
+ name="invoice_items",
+ path="/account/invoices/{invoice_id}/items",
+ # Items carry no id, and two items on one invoice can share label, type and period, so there
+ # is no unique key. Issued invoices are immutable and the set is small, so full refresh fits.
+ primary_keys=None,
+ partition_key="invoice_date",
+ incremental_fields=[],
+ fanout=DependentEndpointConfig(
+ parent_name="invoices",
+ resolve_param="invoice_id",
+ resolve_field="id",
+ include_from_parent=["id", "date"],
+ parent_field_renames={"id": "invoice_id", "date": "invoice_date"},
+ ),
+ ),
+ "account_transfer": LinodeEndpointConfig(
+ name="account_transfer",
+ path="/account/transfer",
+ # One row: the account's network transfer pool for the current month, replaced on every sync.
+ primary_keys=None,
+ single_object=True,
+ incremental_fields=[],
+ ),
+ "linode_types": LinodeEndpointConfig(
+ name="linode_types",
+ path="/linode/types",
+ incremental_fields=[],
+ ),
+ "regions": LinodeEndpointConfig(
+ name="regions",
+ path="/regions",
+ incremental_fields=[],
+ ),
}
ENDPOINTS = tuple(LINODE_ENDPOINTS.keys())
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 c61007fffa7f..c0f4239e50ef 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
@@ -48,7 +48,7 @@ class LinodeSource(ResumableSource[LinodeSourceConfig, LinodeResumeConfig]):
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)
+- Account (invoices, invoice items, payments, network transfer, events, users)
- Linodes
- Volumes
- NodeBalancers
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
index b5eee2ec87d7..7b63c8ce64e6 100644
--- 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
@@ -217,6 +217,53 @@ class TestPagination:
mock.call(LinodeResumeConfig(next_page=3)),
]
+ @mock.patch(CLIENT_SESSION_PATCH)
+ def test_invoice_items_fan_out_per_invoice_and_carry_invoice_fields(self, MockSession: mock.MagicMock) -> None:
+ session = MockSession.return_value
+ session.headers = {}
+ urls: list[str] = []
+
+ def _prepare(request: Any) -> mock.MagicMock:
+ urls.append(request.url)
+ return mock.MagicMock()
+
+ session.prepare_request.side_effect = _prepare
+ session.send.side_effect = [
+ _response([{"id": 11, "date": "2026-01-01T00:00:00"}, {"id": 12, "date": "2026-02-01T00:00:00"}]),
+ _response([{"label": "Linode 1", "amount": 5.0}]),
+ _response([{"label": "Linode 1", "amount": 5.0}, {"label": "Backups", "amount": 2.0}]),
+ ]
+
+ response = _source(endpoint="invoice_items")
+ rows = _rows(response)
+
+ assert [u.rsplit("/v4", 1)[1] for u in urls] == [
+ "/account/invoices",
+ "/account/invoices/11/items",
+ "/account/invoices/12/items",
+ ]
+ assert [(r["invoice_id"], r["invoice_date"], r["label"]) for r in rows] == [
+ (11, "2026-01-01T00:00:00", "Linode 1"),
+ (12, "2026-02-01T00:00:00", "Linode 1"),
+ (12, "2026-02-01T00:00:00", "Backups"),
+ ]
+ assert response.partition_keys == ["invoice_date"]
+
+ @mock.patch(CLIENT_SESSION_PATCH)
+ def test_account_transfer_yields_the_bare_object_as_one_row(self, MockSession: mock.MagicMock) -> None:
+ session = MockSession.return_value
+ transfer = {"quota": 4000, "used": 120, "billable": 0, "region_transfers": []}
+ resp = Response()
+ resp.status_code = 200
+ resp._content = json.dumps(transfer).encode()
+ params = _wire(session, [resp])
+
+ rows = _rows(_source(endpoint="account_transfer"))
+
+ assert rows == [transfer]
+ assert "page_size" not in params[0]
+ assert session.send.call_count == 1
+
class TestRetries:
@parameterized.expand([("rate_limited", 429), ("server_error", 503)])