: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(digitalocean): add action, size, region and invoice tables (#105183)
Tom Owers9fa9c7314682
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.mdindex d4a576310e87..37a2cad8cb25 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@@ -2466,11 +2466,11 @@ Today (16): `apps`, `billing_history`, `databases`, `domains`, `droplets`, `imagDiffed against: <https://api-engineering.nyc3.cdn.digitaloceanspaces.com/spec-ci/DigitalOcean-public.v2.yaml>-- [ ] `/v2/customers/my/invoices/{invoice_uuid} (invoice items) and /invoices/{invoice_uuid}/summary` — per-resource invoice line items; invoices are synced as headers only, so spend cannot be attributed to droplets or databases (high)-- [ ] `/v2/sizes` — lookup resolving the droplet size slug on every droplet into vCPU, memory, disk and hourly/monthly price (high)-- [ ] `/v2/regions` — lookup resolving the region slug carried by droplets, databases, load balancers and volumes (high)+- [x] `/v2/customers/my/invoices/{invoice_uuid} (invoice items) and /invoices/{invoice_uuid}/summary` — per-resource invoice line items; invoices are synced as headers only, so spend cannot be attributed to droplets or databases (high)+- [x] `/v2/sizes` — lookup resolving the droplet size slug on every droplet into vCPU, memory, disk and hourly/monthly price (high)+- [x] `/v2/regions` — lookup resolving the region slug carried by droplets, databases, load balancers and volumes (high)- [ ] `/v2/projects/{project_id}/resources (and /v2/projects/default/resources)` — the join table mapping every synced resource URN to a project — projects are synced but the membership is not (high)-- [ ] `/v2/actions (and /v2/droplets/{droplet_id}/actions)` — account-wide action history: creates, resizes, power cycles with status and timing — the state-transition log for infrastructure (high)+- [x] `/v2/actions (and /v2/droplets/{droplet_id}/actions)` — account-wide action history: creates, resizes, power cycles with status and timing — the state-transition log for infrastructure (high)- [ ] `/v2/apps/{app_id}/deployments (+ /v2/apps/{app_id}/events)` — App Platform deployment history and phase transitions; apps are synced but not their deploy activity (medium)- [ ] `/v2/kubernetes/clusters/{cluster_id}/node_pools` — node pool sizing per cluster, needed to explain Kubernetes cost and capacity (medium)- [ ] `/v2/tags/{tag_id}/resources` — resolves tags (already synced as names) to the resources they are applied to (medium)diff --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.pyindex 3a7ceb58e673..42646aa40216 100644--- 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.py@@ -196,4 +196,84 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {"type": "Type of billing event (e.g. Invoice, Payment).",},},+ "actions": {+ "description": "Account-wide log of actions taken on resources (creates, resizes, power cycles, transfers).",+ "docs_url": "https://docs.digitalocean.com/reference/api/api-reference/#tag/Actions",+ "columns": {+ "id": "Unique numeric identifier for the action.",+ "status": "Current status of the action (in-progress, completed, or errored).",+ "type": "Type of action the record represents (e.g. create, resize, transfer).",+ "started_at": "Time the action was initiated (ISO 8601).",+ "completed_at": "Time the action completed (ISO 8601), null while it is in progress.",+ "resource_id": "Identifier of the resource the action was taken on.",+ "resource_type": "Type of resource the action was taken on (e.g. droplet, image).",+ "region": "Region object the action took place in.",+ "region_slug": "Slug of the region the action took place in.",+ },+ },+ "sizes": {+ "description": "Catalog of Droplet size plans, with the resources and price each slug maps to.",+ "docs_url": "https://docs.digitalocean.com/reference/api/api-reference/#tag/Sizes",+ "columns": {+ "slug": "Slug uniquely identifying the size (used as the primary key, and as `size_slug` on droplets).",+ "memory": "RAM available to Droplets of this size, in megabytes.",+ "vcpus": "Number of virtual CPUs allocated to Droplets of this size.",+ "disk": "Disk space set aside for Droplets of this size, in gigabytes.",+ "transfer": "Public-interface transfer bandwidth included with this size, in terabytes.",+ "price_monthly": "Cost of this size for a full month, in US dollars.",+ "price_hourly": "Cost of this size per hour, in US dollars.",+ "regions": "Region slugs where this size is available for new Droplets.",+ "available": "Whether new Droplets can be created with this size.",+ "description": "Class of Droplet this size belongs to (e.g. Basic, General Purpose, CPU-Optimized).",+ "disk_info": "Details of the disks available to Droplets of this size.",+ "gpu_info": "Details of the GPU attached to Droplets of this size, when the size has one.",+ },+ },+ "regions": {+ "description": "Catalog of data center regions, resolving the region slugs carried by other resources.",+ "docs_url": "https://docs.digitalocean.com/reference/api/api-reference/#tag/Regions",+ "columns": {+ "slug": "Slug uniquely identifying the region (used as the primary key).",+ "name": "Display name of the region, as shown in the control panel.",+ "features": "Features available in this region (e.g. private_networking, backups, ipv6).",+ "available": "Whether new Droplets can be created in this region.",+ "sizes": "Size slugs available in this region.",+ },+ },+ "invoice_items": {+ "description": "Line items behind each invoice, attributing spend to the resource that incurred it.",+ "docs_url": "https://docs.digitalocean.com/reference/api/api-reference/#tag/Billing",+ "columns": {+ "invoice_uuid": "UUID of the invoice the line item belongs to, taken from the parent invoice.",+ "product": "Name of the product being billed.",+ "resource_uuid": "UUID of the billed resource, when the product has one.",+ "resource_id": "Identifier of the billed resource, when the product has one.",+ "group_description": "Name of the grouped usage the item belongs to, such as a cluster.",+ "description": "Description of the line item.",+ "amount": "Billed amount for the line item, in US dollars.",+ "duration": "Amount of time billed.",+ "duration_unit": "Unit the duration is measured in (e.g. Hours).",+ "start_time": "Time the line item began being billed.",+ "end_time": "Time the line item stopped being billed.",+ "project_name": "Name of the project the billed resource belongs to.",+ },+ },+ "invoice_summaries": {+ "description": "Per-invoice totals, split into product charges, overages, taxes, and credits.",+ "docs_url": "https://docs.digitalocean.com/reference/api/api-reference/#tag/Billing",+ "columns": {+ "invoice_uuid": "UUID of the invoice (used as the primary key).",+ "invoice_id": "Identifier of the invoice.",+ "billing_period": "Billing period the invoice covers (YYYY-MM).",+ "amount": "Total amount of the invoice, in US dollars.",+ "user_name": "Name of the customer being invoiced.",+ "user_company": "Company of the customer being invoiced, when set.",+ "user_email": "Email address of the customer being invoiced.",+ "user_billing_address": "Billing address of the customer being invoiced.",+ "product_charges": "Product usage charges, with per-resource-type aggregates under `items`.",+ "overages": "Overage charges contributing to the invoice.",+ "taxes": "Taxes contributing to the invoice.",+ "credits_and_adjustments": "Credits and adjustments contributing to the invoice.",+ },+ },}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.pyindex 481f81ada29e..ee159a2db2c2 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/digitalocean/digitalocean.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/digitalocean/digitalocean.py@@ -1,5 +1,5 @@from collections.abc import Callable-from typing import Any+from typing import Any, castfrom products.warehouse_sources.backend.temporal.data_imports.sources.common.http import make_tracked_sessionfrom products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source import (@@ -7,8 +7,12 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common.resRESTAPIConfig,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 (JSONLinkPaginator,+ SinglePagePaginator,)from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.resource import Resourcefrom products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.typing import EndpointResource@@ -64,9 +68,7 @@ def _strip_sensitive_fields(sensitive_fields: frozenset[str]) -> Callable[[dict[return _strip-def digitalocean_source(api_key: str, endpoint: str, team_id: int, job_id: str) -> Resource:- endpoint_config = DIGITALOCEAN_ENDPOINTS[endpoint]-+def _client_config(api_key: str, endpoint_config: DigitalOceanEndpointConfig) -> ClientConfig:client_config: ClientConfig = {"base_url": DIGITALOCEAN_BASE_URL,"auth": {@@ -75,22 +77,65 @@ def digitalocean_source(api_key: str, endpoint: str, team_id: int, job_id: str)},"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:+ # Sample capture records the raw response before resource maps run, so an endpoint whose+ # response holds secrets (e.g. `databases`) or billing identity (e.g. `invoice_summaries`)+ # must opt out. The request stays metered, logged, and token-redacted.+ if endpoint_config.sensitive_fields or not endpoint_config.captures_http_samples:client_config["session"] = make_tracked_session(redact_values=(api_key,), capture=False)+ return client_config+++def _fanout_resource(+ endpoint_config: DigitalOceanEndpointConfig, client_config: ClientConfig, endpoint: str, team_id: int, job_id: str+) -> Resource:+ fanout = endpoint_config.fanout+ assert fanout is not None+ parent_config = DIGITALOCEAN_ENDPOINTS[fanout.parent_name]++ return cast(+ Resource,+ build_dependent_resource(+ endpoint_configs=DIGITALOCEAN_ENDPOINTS,+ child_endpoint=endpoint,+ fanout=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": parent_config.data_selector},+ # The child paginator is always explicit: the REST framework defaults a path that+ # ends in its resolved id to a single unpaginated entity, which would sync only the+ # first page of a large invoice's line items.+ child_endpoint_extra={+ "data_selector": endpoint_config.data_selector,+ "paginator": _paginator() if endpoint_config.paginated else SinglePagePaginator(),+ },+ # `per_page` is declared per resource on the fan-out config instead, because the+ # summary endpoint returns a single object and takes no page-size param.+ page_size_param=None,+ ),+ )- 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)+def digitalocean_source(api_key: str, endpoint: str, team_id: int, job_id: str) -> Resource:+ endpoint_config = DIGITALOCEAN_ENDPOINTS[endpoint]+ client_config = _client_config(api_key, endpoint_config)++ if endpoint_config.fanout is not None:+ resource = _fanout_resource(endpoint_config, client_config, endpoint, team_id, job_id)+ else:+ 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 resourcediff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/digitalocean/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/digitalocean/settings.pyindex d27b78263db9..d94858a37626 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/digitalocean/settings.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/digitalocean/settings.py@@ -1,6 +1,9 @@from dataclasses import dataclass, fieldfrom 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# DigitalOcean caps `per_page` at 200; use the max to minimize round trips against the@@ -8,13 +11,18 @@ from products.warehouse_sources.backend.types import IncrementalFieldPAGE_SIZE = 200-@dataclass+# Mutable by choice, not oversight: instances flow into `build_dependent_resource`'s+# `endpoint_configs: Mapping[str, FanoutEndpointLike]`, and mypy treats a frozen dataclass's+# fields as read-only, which is incompatible with that Protocol's plain (read-write) attributes.+@dataclass(frozen=False)class DigitalOceanEndpointConfig:name: str- # Path relative to the API root (https://api.digitalocean.com).+ # Path relative to the API root (https://api.digitalocean.com). A fan-out child's path+ # carries the `{...}` placeholder its `fanout.resolve_param` binds.path: str# Key the list of records is nested under in the JSON response body- # (e.g. `{"droplets": [...]}` → "droplets").+ # (e.g. `{"droplets": [...]}` → "droplets"). `"$"` for an endpoint that returns the record+ # as the response body itself rather than wrapped in a list.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.@@ -29,6 +37,24 @@ class DigitalOceanEndpointConfig:# 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()+ # `False` keeps the endpoint's raw response out of HTTP sample capture, which records the+ # response before the resource maps run. Set it for a response that carries data belonging in+ # the warehouse table but not in a diagnostic sample bucket, such as billing identity. A+ # `sensitive_fields` entry implies it, because a secret must never reach a sample either.+ captures_http_samples: bool = True+ # Set for endpoints that hang off a parent list endpoint (invoice line items and summaries+ # are only reachable per invoice uuid). `None` for top-level endpoints.+ fanout: Optional[DependentEndpointConfig] = None+ # `False` for an endpoint that returns a single record as the response body instead of a+ # paginated list. Declared rather than inferred because the REST framework assumes a path+ # ending in its resolved id is a single entity, and `/v2/customers/my/invoices/{invoice_uuid}`+ # returns a page of invoice line items instead.+ paginated: bool = True+ # Read by the fan-out helper's `FanoutEndpointLike` protocol. No DigitalOcean endpoint takes+ # a server-side time filter, so the incremental members stay empty for every endpoint.+ page_size: int = PAGE_SIZE+ incremental_fields: list[IncrementalField] = field(default_factory=list)+ default_incremental_field: Optional[str] = None# DigitalOcean's list endpoints all share the same page-based pagination@@ -52,6 +78,16 @@ DIGITALOCEAN_ENDPOINTS: dict[str, DigitalOceanEndpointConfig] = {partition_key="created_at",sensitive_fields=frozenset({"envs", "log_destinations"}),),+ # Account-wide state-transition log (creates, resizes, power cycles). `/v2/droplets/{id}/actions`+ # returns the same action objects filtered to one droplet, so it adds no columns, because these+ # rows already carry `resource_id` and `resource_type`. Fanning out per droplet would also+ # multiply requests against the account rate limit.+ "actions": DigitalOceanEndpointConfig(+ name="actions",+ path="/v2/actions",+ data_selector="actions",+ partition_key="started_at",+ ),"kubernetes_clusters": DigitalOceanEndpointConfig(name="kubernetes_clusters",path="/v2/kubernetes/clusters",@@ -138,6 +174,20 @@ DIGITALOCEAN_ENDPOINTS: dict[str, DigitalOceanEndpointConfig] = {data_selector="tags",primary_keys=["name"],),+ # Lookups that resolve the `size_slug` and `region` slugs carried by droplets, databases,+ # load balancers and volumes. Both are account-independent catalogs keyed by slug.+ "sizes": DigitalOceanEndpointConfig(+ name="sizes",+ path="/v2/sizes",+ data_selector="sizes",+ primary_keys=["slug"],+ ),+ "regions": DigitalOceanEndpointConfig(+ name="regions",+ path="/v2/regions",+ data_selector="regions",+ primary_keys=["slug"],+ ),"invoices": DigitalOceanEndpointConfig(name="invoices",path="/v2/customers/my/invoices",@@ -152,6 +202,57 @@ DIGITALOCEAN_ENDPOINTS: dict[str, DigitalOceanEndpointConfig] = {data_selector="billing_history",primary_keys=["date", "type", "amount", "description"],),+ # Per-resource line items behind each invoice, so spend can be attributed to the droplet,+ # database or cluster that incurred it. Line items carry no invoice reference of their own,+ # so the parent's `invoice_uuid` is projected onto every row.+ "invoice_items": DigitalOceanEndpointConfig(+ name="invoice_items",+ path="/v2/customers/my/invoices/{invoice_uuid}",+ data_selector="invoice_items",+ captures_http_samples=False,+ # Line items have no id. Like `billing_history`, this composite is a best-effort dedup+ # guard rather than a true key, because the endpoint is full-refresh and each sync+ # rewrites the whole table.+ primary_keys=[+ "invoice_uuid",+ "product",+ "resource_uuid",+ "group_description",+ "description",+ "start_time",+ "end_time",+ ],+ partition_key="start_time",+ fanout=DependentEndpointConfig(+ parent_name="invoices",+ resolve_param="invoice_uuid",+ resolve_field="invoice_uuid",+ include_from_parent=["invoice_uuid"],+ parent_field_renames={"invoice_uuid": "invoice_uuid"},+ parent_params={"per_page": PAGE_SIZE},+ child_params={"per_page": PAGE_SIZE},+ ),+ ),+ # Invoice totals split into product charges, overages, taxes and credits, one row per+ # invoice. The endpoint returns a single object rather than a paginated list. The parent's+ # `invoice_uuid` is projected over the body's own, because the spec does not require the+ # summary body to carry it and it is this table's primary key.+ "invoice_summaries": DigitalOceanEndpointConfig(+ name="invoice_summaries",+ path="/v2/customers/my/invoices/{invoice_uuid}/summary",+ data_selector="$",+ primary_keys=["invoice_uuid"],+ paginated=False,+ captures_http_samples=False,+ fanout=DependentEndpointConfig(+ parent_name="invoices",+ resolve_param="invoice_uuid",+ resolve_field="invoice_uuid",+ include_from_parent=["invoice_uuid"],+ parent_field_renames={"invoice_uuid": "invoice_uuid"},+ parent_params={"per_page": PAGE_SIZE},+ ),+ ),}ENDPOINTS = tuple(DIGITALOCEAN_ENDPOINTS.keys())diff --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.pyindex 110cd9147d9a..8e7dee1ac7b3 100644--- 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.py@@ -7,6 +7,7 @@ from unittest.mock import MagicMock, patchfrom requests import Request, Responsefrom products.warehouse_sources.backend.temporal.data_imports.sources.digitalocean.digitalocean import (+ DIGITALOCEAN_BASE_URL,_paginator,digitalocean_source,get_resource,@@ -17,6 +18,9 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.digitalocePAGE_SIZE,)+TOP_LEVEL_ENDPOINTS = [name for name, config in DIGITALOCEAN_ENDPOINTS.items() if config.fanout is None]+INVOICE_UUID = "22737513-0ea7-4206-8ceb-98a575af7681"+def _make_response(json_body: dict[str, Any] | None = None, status_code: int = 200) -> Response:resp = Response()@@ -67,7 +71,7 @@ class TestDigitalOceanPaginator:class TestDigitalOceanGetResource:- @pytest.mark.parametrize("endpoint", list(DIGITALOCEAN_ENDPOINTS.keys()))+ @pytest.mark.parametrize("endpoint", TOP_LEVEL_ENDPOINTS)def test_resource_matches_endpoint_config(self, endpoint: str) -> None:config = DIGITALOCEAN_ENDPOINTS[endpoint]resource = get_resource(config)@@ -143,25 +147,31 @@ class TestDigitalOceanSensitiveFields:assert resource._apply_transforms([dict(record)]) == [record]- @patch(- "products.warehouse_sources.backend.temporal.data_imports.sources.digitalocean.digitalocean.make_tracked_session"+ @pytest.mark.parametrize(+ "endpoint,capture_disabled",+ [+ pytest.param("databases", True, id="secrets_in_the_response"),+ pytest.param("invoice_summaries", True, id="billing_identity_in_the_response"),+ pytest.param("invoice_items", True, id="resource_level_spend_in_the_response"),+ pytest.param("droplets", False, id="nothing_to_withhold"),+ ],)- 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")+ def test_capture_is_disabled_only_where_the_response_must_not_be_sampled(+ self, mock_session: MagicMock, endpoint: str, capture_disabled: bool+ ) -> None:+ # Sample capture records the raw response before resource maps run, so stripping a field+ # from storage does not keep it out of a sample. An endpoint holding secrets or billing+ # identity must build its own capture-off session; every other endpoint must not, leaving+ # the tracked client's default (capture on) in place.+ digitalocean_source("dop_v1_token", endpoint, team_id=1, job_id="job-1")- mock_session.assert_not_called()+ if capture_disabled:+ mock_session.assert_called_once_with(redact_values=("dop_v1_token",), capture=False)+ else:+ mock_session.assert_not_called()class TestDigitalOceanValidateCredentials:@@ -201,3 +211,74 @@ class TestDigitalOceanValidateCredentials:_, kwargs = mock_session.return_value.get.call_argsassert kwargs["headers"]["Authorization"] == "Bearer dop_v1_token"+++class TestDigitalOceanInvoiceFanout:+ def _rows(self, endpoint: str) -> list[dict[str, Any]]:+ resource = digitalocean_source("dop_v1_token", endpoint, team_id=1, job_id="job-1")+ return [row for page in resource for row in page]++ def _mock_invoice_list(self, requests_mock: Any) -> None:+ requests_mock.get(+ f"{DIGITALOCEAN_BASE_URL}/v2/customers/my/invoices",+ json={"invoices": [{"invoice_uuid": INVOICE_UUID, "amount": "27.13"}]},+ )++ def test_invoice_items_carry_their_parent_invoice_uuid(self, requests_mock: Any) -> None:+ # Line items carry no invoice reference of their own, so without the parent projection+ # (and its rename off the `_invoices_` prefix) spend can't be joined back to an invoice.+ self._mock_invoice_list(requests_mock)+ requests_mock.get(+ f"{DIGITALOCEAN_BASE_URL}/v2/customers/my/invoices/{INVOICE_UUID}",+ json={"invoice_items": [{"product": "Droplets", "amount": "12.34"}]},+ )++ assert self._rows("invoice_items") == [{"product": "Droplets", "amount": "12.34", "invoice_uuid": INVOICE_UUID}]++ def test_invoice_items_paginate_within_one_invoice(self, requests_mock: Any) -> None:+ # An invoice with hundreds of resources spans pages; the child must follow+ # links.pages.next per parent rather than syncing only the first page of line items.+ self._mock_invoice_list(requests_mock)+ page_two = f"{DIGITALOCEAN_BASE_URL}/v2/customers/my/invoices/{INVOICE_UUID}?page=2"+ requests_mock.get(+ f"{DIGITALOCEAN_BASE_URL}/v2/customers/my/invoices/{INVOICE_UUID}",+ [+ {"json": {"invoice_items": [{"product": "Droplets"}], "links": {"pages": {"next": page_two}}}},+ {"json": {"invoice_items": [{"product": "Spaces"}], "links": {}}},+ ],+ )++ assert [row["product"] for row in self._rows("invoice_items")] == ["Droplets", "Spaces"]++ @pytest.mark.parametrize(+ "summary",+ [+ pytest.param({"invoice_uuid": INVOICE_UUID, "amount": "27.13"}, id="body_carries_its_own_uuid"),+ pytest.param({"amount": "27.13"}, id="body_omits_the_uuid"),+ ],+ )+ def test_invoice_summary_yields_one_keyed_row_from_the_bare_object(+ self, requests_mock: Any, summary: dict[str, Any]+ ) -> None:+ # The summary endpoint returns the record as the response body rather than wrapped in a+ # list, so a list-shaped data_selector would sync nothing for it. The spec does not require+ # the body to carry `invoice_uuid`, so the parent's value is projected on; without that the+ # row can arrive with no primary key column at all.+ self._mock_invoice_list(requests_mock)+ requests_mock.get(f"{DIGITALOCEAN_BASE_URL}/v2/customers/my/invoices/{INVOICE_UUID}/summary", json=summary)++ assert self._rows("invoice_summaries") == [{**summary, "invoice_uuid": INVOICE_UUID}]++ def test_both_sides_of_the_fanout_ask_for_the_max_page(self, requests_mock: Any) -> None:+ # The fan-out helper is wired with no page-size param of its own, so `per_page` rides on+ # the fan-out config. Dropping it from either side falls back to DigitalOcean's default+ # of 20 rows a page, which is 10x the requests against a 250-per-minute limit.+ invoices = requests_mock.get(+ f"{DIGITALOCEAN_BASE_URL}/v2/customers/my/invoices",+ json={"invoices": [{"invoice_uuid": INVOICE_UUID}]},+ )+ items = requests_mock.get(f"{DIGITALOCEAN_BASE_URL}/v2/customers/my/invoices/{INVOICE_UUID}", json={})+ self._rows("invoice_items")++ assert invoices.last_request.qs["per_page"] == [str(PAGE_SIZE)]+ assert items.last_request.qs["per_page"] == [str(PAGE_SIZE)]