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): add 5 missing tables to the Vantage source (#117903)

Tom Owers5192deaad245
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 2db8d35e8879..baa88adf6750 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
@@ -12854,10 +12854,10 @@ Today (20): `access_grants`, `anomaly_alerts`, `billing_rules`, `budgets`, `cost
Diffed against: <https://api.vantage.sh/v2/swagger.json>
-- [ ] `GET /costs` — the actual cost rows for a cost report — we sync report definitions but none of the cost data (high)
-- [ ] `GET /resources` — the resource inventory returned by a resource report; today only the report definition is synced (high)
-- [ ] `GET /financial_commitments` — actual RI/savings-plan commitments; we sync only financial_commitment_reports definitions (high)
-- [ ] `GET /tags and GET /tags/{key}/values` — lookup for the cost-allocation tag keys/values every cost breakdown groups by (high)
+- [x] `GET /costs` — the actual cost rows for a cost report — we sync report definitions but none of the cost data (high)
+- [x] `GET /resources` — the resource inventory returned by a resource report; today only the report definition is synced (high)
+- [x] `GET /financial_commitments` — actual RI/savings-plan commitments; we sync only financial_commitment_reports definitions (high)
+- [x] `GET /tags and GET /tags/{key}/values` — lookup for the cost-allocation tag keys/values every cost breakdown groups by (high)
- [ ] `GET /cost_providers, GET /cost_provider_accounts, GET /cost_services` — lookup tables resolving the provider, account and service ids that appear in cost data (high)
- [ ] `GET /unit_costs` — unit economics per cost report (cost per business unit), a headline FinOps metric (medium)
- [ ] `GET /business_metrics and GET /business_metrics/{token}/values` — the metric series that unit costs divide by; needed to reproduce unit-cost math (medium)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/vantage/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/vantage/canonical_descriptions.py
index 069ef041d09b..33c82f83363a 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/vantage/canonical_descriptions.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/vantage/canonical_descriptions.py
@@ -334,4 +334,85 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
"last_seen_at": "The last time the User logged in.",
},
},
+ "tags": {
+ "description": "A cost-allocation tag key found on provider costs, used to group and filter cost data.",
+ "docs_url": "https://vantage.readme.io/reference/gettags",
+ "columns": {
+ "tag_key": "The Tag key.",
+ "hidden": "Whether the Tag has been hidden from the Vantage UI.",
+ "preferred": "Whether the Tag has been marked as preferred.",
+ "providers": "The unique providers that are covered by the Tag key.",
+ },
+ },
+ "tag_values": {
+ "description": "A value seen for a cost-allocation tag key.",
+ "docs_url": "https://vantage.readme.io/reference/gettagvalues",
+ "columns": {
+ "tag_key": "The Tag key that this value belongs to.",
+ "tag_value": "The TagValue.",
+ "providers": "The unique providers that are covered by the TagValue.",
+ },
+ },
+ "financial_commitments": {
+ "description": "A financial commitment, such as a Reserved Instance or a Savings Plan.",
+ "docs_url": "https://vantage.readme.io/reference/getfinancialcommitments",
+ "columns": {
+ "commitment_type": "The commitment type (eg Savings Plan or Reserved Instance).",
+ "service": "The service this commitment applies towards.",
+ "account": "The account for this financial commitment.",
+ "type": "The type of financial commitment.",
+ "amount": "The number of instances for the financial commitment.",
+ "term": "The duration in years of the financial commitment.",
+ "payment_type": "The type of payment for the financial commitment.",
+ "region": "The region for the financial commitment.",
+ "purchase_date": "The purchase date of the financial commitment. ISO 8601 Formatted.",
+ "expiration_date": "The expiration date of the financial commitment. ISO 8601 Formatted.",
+ "commitment": "The amount of the financial commitment.",
+ "status": "The status of the financial commitment (e.g. active vs expired).",
+ "created_at": "The date and time, in UTC, the Financial Commitment was created. ISO 8601 Formatted.",
+ "workspace_token": "The token for the Workspace the FinancialCommitment is a part of.",
+ },
+ },
+ "costs": {
+ "description": "A cost row of a cost report, for one date bin and one combination of the report's groupings.",
+ "docs_url": "https://vantage.readme.io/reference/getcosts",
+ "columns": {
+ "cost_report_token": "The token of the CostReport that returned this cost row.",
+ "accrued_at": "The date that the cost was accrued. ISO 8601 Formatted.",
+ "amount": "The amount of the cost.",
+ "currency": "The currency of the cost.",
+ "usage": "The usage amount and unit incurred by the cost.",
+ "provider": "The cost provider which incurred the cost.",
+ "billing_account_id": "The cost provider's billing account id that incurred the cost.",
+ "account_id": "The cost provider's account id that incurred the cost.",
+ "service": "The service which incurred the cost.",
+ "region": "The region which incurred the cost.",
+ "resource_id": "The resource id which incurred the cost.",
+ "resource_name": "The human-readable resource name when Vantage can enrich the resource id.",
+ "tags": "The tag pairs attached to the cost that was incurred.",
+ "cost_category": "The category for the cost.",
+ "cost_subcategory": "The subcategory for the cost.",
+ "charge_type": "The charge type for the cost.",
+ "tagged": "Whether the cost has tags.",
+ "usage_unit": "The unit used to measure usage.",
+ "segment": "The segment name for segment report costs.",
+ },
+ },
+ "resources": {
+ "description": "A cloud resource contained in a resource report.",
+ "docs_url": "https://vantage.readme.io/reference/getreportresources",
+ "columns": {
+ "resource_report_token": "The token of the ResourceReport that contains this resource.",
+ "token": "Unique identifier (token) for the resource record.",
+ "uuid": "The unique identifier for the resource.",
+ "type": "The kind of resource.",
+ "metadata": "Type-specific attributes of the resource.",
+ "account_id": "The provider account where the resource is located.",
+ "billing_account_id": "The provider billing account this resource is charged to.",
+ "provider": "The provider of the resource.",
+ "region": "The region where the resource is located. Region values are specific to each provider.",
+ "created_at": "The date and time when Vantage first observed the resource.",
+ "tags": "Key-value pairs of tags associated with the resource.",
+ },
+ },
}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/vantage/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/vantage/settings.py
index 84464c40cf97..f40cf8d9bc64 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/vantage/settings.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/vantage/settings.py
@@ -1,10 +1,22 @@
-from dataclasses import dataclass, field
+from dataclasses import field
from typing import Optional
+from posthog.dataclasses import frozen
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.fanout import (
+ DependentEndpointConfig,
+)
from products.warehouse_sources.backend.types import IncrementalField
+# The Vantage API caps `limit` at 1000 on most list endpoints; use the max to minimise the number of
+# paginated requests (and thus stay well under the ~1,000 requests/hour and ~20 requests/minute
+# per-key rate limits).
+PAGE_SIZE = 1000
+# `/costs` documents a higher cap than the other list endpoints.
+COSTS_PAGE_SIZE = 5000
+
-@dataclass
+@frozen
class VantageEndpointConfig:
name: str
# API path relative to the v2 base URL (e.g. "/cost_reports").
@@ -12,8 +24,9 @@ class VantageEndpointConfig:
# Key under which the response nests the row array (e.g. {"links": ..., "cost_reports": [...]}).
data_key: str
# Columns that uniquely identify a row table-wide, used for merge dedup. Vantage identifies
- # every top-level object with a globally-unique `token`, so that's the default.
- primary_keys: list[str] = field(default_factory=lambda: ["token"])
+ # every top-level object with a globally-unique `token`, so that's the default. None for
+ # full-refresh rows that carry no identifier at all.
+ primary_keys: Optional[list[str]] = field(default_factory=lambda: ["token"])
# Stable datetime field to partition by. Must never change once a row is created, so we use
# `created_at` (never `updated_at`). None for objects the API doesn't stamp with a creation time.
partition_key: Optional[str] = None
@@ -22,13 +35,18 @@ class VantageEndpointConfig:
# Vantage exposes no generic `updated_after` cursor on these config/report resources, so every
# endpoint is full-refresh only. Kept for parity with other sources / future incremental support.
incremental_fields: list[IncrementalField] = field(default_factory=list)
+ default_incremental_field: Optional[str] = None
+ page_size: int = PAGE_SIZE
+ # Set for endpoints that need a parent row (a report token or a tag key) to build each request.
+ fanout: Optional[DependentEndpointConfig] = None
+ # Child-request params that are not page size, e.g. a fixed sort order.
+ params: dict[str, str] = field(default_factory=dict)
-# Every endpoint below is a top-level GET list endpoint that returns
-# `{"links": {...}, "<data_key>": [...]}` and paginates through `links.next`. All are full refresh:
-# Vantage's config/report objects have no server-side timestamp filter to drive incremental sync
-# (only the cost/usage data endpoints accept date-range windows, and those are intentionally left
-# out of this initial version - see the source docstring / PR notes).
+# Every endpoint below is a GET list endpoint that returns `{"links": {...}, "<data_key>": [...]}`
+# and paginates through `links.next`. All are full refresh: Vantage's config/report objects have no
+# server-side timestamp filter to drive incremental sync, and cost rows are restated by the
+# providers after they accrue and carry no key to merge on.
VANTAGE_ENDPOINTS: dict[str, VantageEndpointConfig] = {
"cost_reports": VantageEndpointConfig(
name="cost_reports", path="/cost_reports", data_key="cost_reports", partition_key="created_at"
@@ -92,6 +110,71 @@ VANTAGE_ENDPOINTS: dict[str, VantageEndpointConfig] = {
),
"teams": VantageEndpointConfig(name="teams", path="/teams", data_key="teams"),
"users": VantageEndpointConfig(name="users", path="/users", data_key="users"),
+ "tags": VantageEndpointConfig(name="tags", path="/tags", data_key="tags", primary_keys=["tag_key"]),
+ # Commitment rows carry no token or other identifier, so the table is replaced on every sync.
+ "financial_commitments": VantageEndpointConfig(
+ name="financial_commitments",
+ path="/financial_commitments",
+ data_key="financial_commitments",
+ primary_keys=None,
+ partition_key="created_at",
+ ),
+ # The fan-out tables below make one request series per parent row. They are off by default
+ # because a large account can have many reports or tag keys, and the cost endpoints have
+ # stricter rate limits than the config endpoints.
+ "tag_values": VantageEndpointConfig(
+ name="tag_values",
+ path="/tags/{tag_key}/values",
+ data_key="tag_values",
+ primary_keys=["tag_key", "tag_value"],
+ should_sync_default=False,
+ fanout=DependentEndpointConfig(
+ parent_name="tags",
+ resolve_param="tag_key",
+ # Tag keys can contain `/` (e.g. `kubernetes.io/name`), so the path uses a
+ # percent-encoded copy that the transport adds to each parent row.
+ resolve_field="tag_key_path",
+ include_from_parent=["tag_key"],
+ parent_field_renames={"tag_key": "tag_key"},
+ child_response_actions=[{"status_code": 404, "action": "ignore"}],
+ ),
+ ),
+ # Cost rows have no identifier and their dimensions depend on each report's saved groupings,
+ # so the table is replaced on every sync. Each report's saved date range and settings apply.
+ "costs": VantageEndpointConfig(
+ name="costs",
+ path="/costs?cost_report_token={cost_report_token}",
+ data_key="costs",
+ primary_keys=None,
+ should_sync_default=False,
+ page_size=COSTS_PAGE_SIZE,
+ params={"order": "asc"},
+ fanout=DependentEndpointConfig(
+ parent_name="cost_reports",
+ resolve_param="cost_report_token",
+ resolve_field="token",
+ include_from_parent=["token"],
+ parent_field_renames={"token": "cost_report_token"},
+ child_response_actions=[{"status_code": 404, "action": "ignore"}],
+ ),
+ ),
+ # The same resource can appear in several resource reports, so the report token is in the key.
+ "resources": VantageEndpointConfig(
+ name="resources",
+ path="/resources?resource_report_token={resource_report_token}",
+ data_key="resources",
+ primary_keys=["resource_report_token", "token"],
+ partition_key="created_at",
+ should_sync_default=False,
+ fanout=DependentEndpointConfig(
+ parent_name="resource_reports",
+ resolve_param="resource_report_token",
+ resolve_field="token",
+ include_from_parent=["token"],
+ parent_field_renames={"token": "resource_report_token"},
+ child_response_actions=[{"status_code": 404, "action": "ignore"}],
+ ),
+ ),
}
ENDPOINTS = tuple(VANTAGE_ENDPOINTS.keys())
@@ -99,3 +182,5 @@ ENDPOINTS = tuple(VANTAGE_ENDPOINTS.keys())
INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {
name: config.incremental_fields for name, config in VANTAGE_ENDPOINTS.items()
}
+
+SHOULD_SYNC_DEFAULT: dict[str, bool] = {name: config.should_sync_default for name, config in VANTAGE_ENDPOINTS.items()}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/vantage/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/vantage/source.py
index 52c551791b8d..bb7a2b7aeb3e 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/vantage/source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/vantage/source.py
@@ -25,6 +25,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.generated_
from products.warehouse_sources.backend.temporal.data_imports.sources.vantage.settings import (
ENDPOINTS,
INCREMENTAL_FIELDS,
+ SHOULD_SYNC_DEFAULT,
)
from products.warehouse_sources.backend.temporal.data_imports.sources.vantage.vantage import (
VantageResumeConfig,
@@ -100,7 +101,7 @@ Create a read-scoped access token or a service token from your [Vantage settings
force_refresh: bool = False,
api_version: str | None = None,
) -> list[SourceSchema]:
- return build_endpoint_schemas(ENDPOINTS, INCREMENTAL_FIELDS, names)
+ return build_endpoint_schemas(ENDPOINTS, INCREMENTAL_FIELDS, names, should_sync_default=SHOULD_SYNC_DEFAULT)
def validate_credentials(
self,
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/vantage/tests/test_vantage.py b/products/warehouse_sources/backend/temporal/data_imports/sources/vantage/tests/test_vantage.py
index 6c6c769e632a..df12d50984e0 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/vantage/tests/test_vantage.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/vantage/tests/test_vantage.py
@@ -5,6 +5,7 @@ from parameterized import parameterized
from products.warehouse_sources.backend.temporal.data_imports.sources.common.testing import (
DriveResult,
+ RecordedRequest,
Script,
ScriptedResponse,
SourceDriver,
@@ -133,6 +134,146 @@ class TestRetries:
assert len(result.requests) == 1
+def _by_url(answers: dict[str, ScriptedResponse]) -> Script:
+ # Fan-out runs interleave parent and child requests, so answer each request by its URL.
+ def respond(request: RecordedRequest) -> ScriptedResponse:
+ return answers[request.url]
+
+ return respond
+
+
+_COSTS_CHILD = f"{VANTAGE_BASE_URL}/costs?cost_report_token={{token}}&limit=5000&order=asc"
+_RESOURCES_CHILD = f"{VANTAGE_BASE_URL}/resources?resource_report_token={{token}}&limit=1000"
+_TAG_VALUES_CHILD = f"{VANTAGE_BASE_URL}/tags/{{token}}/values?limit=1000"
+
+
+class TestFanOut:
+ @parameterized.expand(
+ [
+ (
+ "costs",
+ "cost_reports",
+ [{"token": "rprt_a"}, {"token": "rprt_b"}],
+ _COSTS_CHILD,
+ ["rprt_a", "rprt_b"],
+ "cost_report_token",
+ {"accrued_at": "2025-01-01", "amount": "1.50"},
+ ),
+ (
+ "resources",
+ "resource_reports",
+ [{"token": "rsrc_rprt_a"}, {"token": "rsrc_rprt_b"}],
+ _RESOURCES_CHILD,
+ ["rsrc_rprt_a", "rsrc_rprt_b"],
+ "resource_report_token",
+ {"token": "prvdr_rsrc_1", "created_at": "2025-01-01T00:00:00Z"},
+ ),
+ (
+ # A `/` in a tag key would otherwise split the path into a different route.
+ "tag_values",
+ "tags",
+ [{"tag_key": "team"}, {"tag_key": "kubernetes.io/name"}],
+ _TAG_VALUES_CHILD,
+ ["team", "kubernetes.io%2Fname"],
+ "tag_key",
+ {"tag_value": "web"},
+ ),
+ ]
+ )
+ def test_walks_every_parent_and_child_page_and_tags_rows_with_parent(
+ self,
+ endpoint: str,
+ parent_key: str,
+ parents: list[dict[str, Any]],
+ child_url: str,
+ child_path_values: list[str],
+ parent_column: str,
+ child_row: dict[str, Any],
+ ) -> None:
+ first_child = child_url.format(token=child_path_values[0])
+ second_page = f"{first_child}&page=2"
+ second_child = child_url.format(token=child_path_values[1])
+ parent_values = [next(iter(parent.values())) for parent in parents]
+
+ result = _run(
+ _by_url(
+ {
+ f"{VANTAGE_BASE_URL}/{parent_key}?limit=1000": _response(parents, data_key=parent_key),
+ first_child: _response([dict(child_row)], data_key=endpoint, next_url=second_page),
+ second_page: _response([dict(child_row)], data_key=endpoint),
+ second_child: _response([dict(child_row)], data_key=endpoint),
+ }
+ ),
+ endpoint=endpoint,
+ )
+
+ assert result.raised is None
+ assert [row[parent_column] for row in result.rows] == [parent_values[0], parent_values[0], parent_values[1]]
+ assert all(f"_{parent_key}_" not in column for row in result.rows for column in row)
+ assert result.urls[1:] == [first_child, second_page, second_child]
+
+ def test_child_404_for_a_deleted_report_skips_only_that_report(self) -> None:
+ result = _run(
+ _by_url(
+ {
+ f"{VANTAGE_BASE_URL}/cost_reports?limit=1000": _response(
+ [{"token": "rprt_gone"}, {"token": "rprt_b"}]
+ ),
+ _COSTS_CHILD.format(token="rprt_gone"): _response(None, include_links=False, status_code=404),
+ _COSTS_CHILD.format(token="rprt_b"): _response([{"amount": "2.00"}], data_key="costs"),
+ }
+ ),
+ endpoint="costs",
+ )
+
+ assert result.raised is None
+ assert result.rows == [{"amount": "2.00", "cost_report_token": "rprt_b"}]
+
+ def test_resume_skips_completed_parents_and_continues_the_current_child(self) -> None:
+ resume_url = f"{_COSTS_CHILD.format(token='rprt_b')}&page=3"
+ result = _run(
+ _by_url(
+ {
+ f"{VANTAGE_BASE_URL}/cost_reports?limit=1000": _response(
+ [{"token": "rprt_a"}, {"token": "rprt_b"}, {"token": "rprt_c"}]
+ ),
+ resume_url: _response([{"amount": "3.00"}], data_key="costs"),
+ _COSTS_CHILD.format(token="rprt_c"): _response([{"amount": "4.00"}], data_key="costs"),
+ }
+ ),
+ endpoint="costs",
+ resume_state=VantageResumeConfig(
+ fanout_state={
+ "completed": ["/costs?cost_report_token=rprt_a"],
+ "current": "/costs?cost_report_token=rprt_b",
+ "child_state": {"next_url": resume_url},
+ }
+ ),
+ )
+
+ assert result.raised is None
+ assert [row["cost_report_token"] for row in result.rows] == ["rprt_b", "rprt_c"]
+ assert result.urls[1:] == [resume_url, _COSTS_CHILD.format(token="rprt_c")]
+ assert all(isinstance(state, VantageResumeConfig) and state.fanout_state for state in result.saved_states)
+
+ def test_untrusted_child_next_url_is_refused(self) -> None:
+ first_child = _TAG_VALUES_CHILD.format(token="team")
+ result = _run(
+ _by_url(
+ {
+ f"{VANTAGE_BASE_URL}/tags?limit=1000": _response([{"tag_key": "team"}], data_key="tags"),
+ first_child: _response(
+ [{"tag_value": "web"}], data_key="tag_values", next_url="https://evil.example.com/v2/tags"
+ ),
+ }
+ ),
+ endpoint="tag_values",
+ )
+
+ assert isinstance(result.raised, VantageUntrustedURLError)
+ assert result.urls[1:] == [first_child]
+
+
class TestValidateCredentials:
@parameterized.expand([("ok", 200, True), ("unauthorized", 401, False), ("forbidden", 403, False)])
def test_status_maps_to_validity(self, _name: str, status: int, expected: bool) -> None:
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/vantage/tests/test_vantage_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/vantage/tests/test_vantage_source.py
index b19b7def2c77..5c95e9c1e524 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/vantage/tests/test_vantage_source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/vantage/tests/test_vantage_source.py
@@ -74,3 +74,10 @@ class TestPublicDocsCatalog:
def test_canonical_description_keys_are_real_endpoints(self) -> None:
# A key that doesn't match an endpoint name would silently never apply to any synced table.
assert set(CANONICAL_DESCRIPTIONS).issubset(set(ENDPOINTS))
+
+
+class TestSchemaDefaults:
+ def test_fan_out_tables_are_off_by_default(self) -> None:
+ schemas = {schema.name: schema for schema in VantageSource().get_schemas(MagicMock(), team_id=1)}
+ off_by_default = {"costs", "resources", "tag_values"}
+ assert {name for name, schema in schemas.items() if not schema.should_sync_default} == off_by_default
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/vantage/vantage.py b/products/warehouse_sources/backend/temporal/data_imports/sources/vantage/vantage.py
index 83a325355295..0b435b8e4cde 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/vantage/vantage.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/vantage/vantage.py
@@ -1,29 +1,34 @@
-import dataclasses
-from typing import Any, Optional
-from urllib.parse import urlparse
+from typing import Any, Optional, cast
+from urllib.parse import quote, urlparse
from requests import Response
+from posthog.dataclasses import frozen
+
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 (
JSONResponsePaginator,
)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.resource import Resource
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.typing import ClientConfig
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.vantage.settings import VANTAGE_ENDPOINTS
+from products.warehouse_sources.backend.temporal.data_imports.sources.vantage.settings import (
+ VANTAGE_ENDPOINTS,
+ VantageEndpointConfig,
+)
VANTAGE_HOST = "api.vantage.sh"
VANTAGE_BASE_URL = f"https://{VANTAGE_HOST}/v2"
-# The Vantage API caps `limit` at 1000; use the max to minimise the number of paginated requests
-# (and thus stay well under the ~1,000 requests/hour and ~20 requests/minute per-key rate limits).
-PAGE_SIZE = 1000
-
class VantageUntrustedURLError(Exception):
pass
@@ -66,11 +71,14 @@ class VantageTrustedJSONPaginator(JSONResponsePaginator):
)
+@frozen
class VantageResumeConfig:
# Full URL of the next page to fetch, taken verbatim from the response `links.next`. Vantage
# encodes `page`/`limit` into it, so following it is enough to resume where we left off.
- next_url: str
+ next_url: str = ""
+ # Fan-out endpoints: the framework's dependent-resource resume state
+ # (`{"completed": [...], "current": ..., "child_state": ...}`).
+ fanout_state: Optional[dict[str, Any]] = None
def _get_headers(api_key: str) -> dict[str, str]:
@@ -92,36 +100,47 @@ def validate_credentials(api_key: str) -> bool:
return ok
-def vantage_source(
+def _add_tag_key_path(row: dict[str, Any]) -> dict[str, Any]:
+ # The fan-out binds the path with `str.format`, which applies no escaping.
+ row["tag_key_path"] = quote(row["tag_key"], safe="")
+ return row
+
+
+_PARENT_DATA_MAPS = {"tag_values": _add_tag_key_path}
+
+
+def _client_config(api_key: str) -> ClientConfig:
+ return {
+ "base_url": VANTAGE_BASE_URL,
+ # Auth (Bearer) goes through the framework auth config so the token is redacted from
+ # logs and raised errors; only the non-secret Accept header is set here.
+ "headers": {"Accept": "application/json"},
+ "auth": {"type": "bearer", "token": api_key},
+ "paginator": VantageTrustedJSONPaginator(),
+ # `links.next` is server-controlled: pin every request to Vantage's own host and never
+ # follow a redirect that could forward the bearer token off-host.
+ "allowed_hosts": [],
+ "allow_redirects": False,
+ }
+
+
+def _top_level_resource(
+ config: VantageEndpointConfig,
api_key: str,
- endpoint: str,
team_id: int,
job_id: str,
resumable_source_manager: ResumableSourceManager[VantageResumeConfig],
-) -> SourceResponse:
- config = VANTAGE_ENDPOINTS[endpoint]
-
+) -> Resource:
rest_config: RESTAPIConfig = {
- "client": {
- "base_url": VANTAGE_BASE_URL,
- # Auth (Bearer) goes through the framework auth config so the token is redacted from
- # logs and raised errors; only the non-secret Accept header is set here.
- "headers": {"Accept": "application/json"},
- "auth": {"type": "bearer", "token": api_key},
- "paginator": VantageTrustedJSONPaginator(),
- # `links.next` is server-controlled: pin every request to Vantage's own host and never
- # follow a redirect that could forward the bearer token off-host.
- "allowed_hosts": [],
- "allow_redirects": False,
- },
+ "client": _client_config(api_key),
"resource_defaults": {},
"resources": [
{
- "name": endpoint,
+ "name": config.name,
"endpoint": {
"path": config.path,
# Cap page size on the first request; `links.next` carries limit/page thereafter.
- "params": {"limit": PAGE_SIZE},
+ "params": {"limit": config.page_size, **config.params},
# Rows nest under the endpoint's own key (e.g. "cost_reports"). A missing key on a
# 200 yields zero rows (matching the prior `data.get(key, [])`), not a hard error.
"data_selector": config.data_key,
@@ -142,7 +161,7 @@ def vantage_source(
if state and state.get("next_url"):
resumable_source_manager.save_state(VantageResumeConfig(next_url=state["next_url"]))
- resource = rest_api_resource(
+ return rest_api_resource(
rest_config,
team_id,
job_id,
@@ -151,6 +170,64 @@ def vantage_source(
initial_paginator_state=initial_paginator_state,
)
+
+def _fanout_resource(
+ config: VantageEndpointConfig,
+ api_key: str,
+ team_id: int,
+ job_id: str,
+ resumable_source_manager: ResumableSourceManager[VantageResumeConfig],
+) -> Resource:
+ assert config.fanout is not None
+ parent_config = VANTAGE_ENDPOINTS[config.fanout.parent_name]
+
+ initial_paginator_state: Optional[dict[str, Any]] = None
+ if resumable_source_manager.can_resume():
+ resume = resumable_source_manager.load_state()
+ if resume is not None and resume.fanout_state:
+ initial_paginator_state = resume.fanout_state
+
+ def save_checkpoint(state: Optional[dict[str, Any]]) -> None:
+ if state is not None:
+ resumable_source_manager.save_state(VantageResumeConfig(fanout_state=state))
+
+ return cast(
+ Resource,
+ build_dependent_resource(
+ endpoint_configs=VANTAGE_ENDPOINTS,
+ child_endpoint=config.name,
+ fanout=config.fanout,
+ client_config=_client_config(api_key),
+ path_format_values={},
+ team_id=team_id,
+ job_id=job_id,
+ db_incremental_field_last_value=None,
+ child_params_extra=config.params or None,
+ parent_endpoint_extra={"data_selector": parent_config.data_key},
+ child_endpoint_extra={
+ "data_selector": config.data_key,
+ # A path that ends in a placeholder (`/costs?cost_report_token={...}`) reads as a
+ # single-entity path to the framework, which then fetches only one page.
+ "paginator": VantageTrustedJSONPaginator(),
+ },
+ parent_data_map=_PARENT_DATA_MAPS.get(config.name),
+ resume_hook=save_checkpoint,
+ initial_paginator_state=initial_paginator_state,
+ ),
+ )
+
+
+def vantage_source(
+ api_key: str,
+ endpoint: str,
+ team_id: int,
+ job_id: str,
+ resumable_source_manager: ResumableSourceManager[VantageResumeConfig],
+) -> SourceResponse:
+ config = VANTAGE_ENDPOINTS[endpoint]
+ build_resource = _fanout_resource if config.fanout else _top_level_resource
+ resource = build_resource(config, api_key, team_id, job_id, resumable_source_manager)
+
return SourceResponse(
name=endpoint,
items=lambda: resource,