:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(data-warehouse): implement vantage import source (#70016)
Tom Owers14c26ac8e7b4
diff --git a/frontend/public/services/vantage.png b/frontend/public/services/vantage.pngindex e35e4c250256..bab8937d5575 100644Binary files a/frontend/public/services/vantage.png and b/frontend/public/services/vantage.png differdiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.mdindex c57245114ae9..644eccf9a4a4 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md@@ -402,6 +402,7 @@ the row lists both.| typeform | HTTP | requests + `rest_source.RESTClient` | ✅ || ubidots | HTTP | requests | ✅ || unleash | HTTP | requests | ✅ |+| vantage | HTTP | requests | ✅ || vellum | HTTP | requests | ✅ || vercel | HTTP | requests | ✅ || vitally | HTTP | requests + `rest_source.RESTClient` | ✅ |@@ -838,7 +839,6 @@ doesn't conflict with concurrent PRs.- uptick- us_census- uservoice-- vantage- vapi- veeqo- vespadiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.py b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.pyindex 1e0ca4c63324..aa342e7f5d17 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@@ -3939,7 +3939,7 @@ class VWOSourceConfig(config.Config):@config.configclass VantageSourceConfig(config.Config):- pass+ api_key: str@config.configdiff --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.pynew file mode 100644index 000000000000..069ef041d09b--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/vantage/canonical_descriptions.py@@ -0,0 +1,337 @@+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (+ CanonicalDescriptions,+)++# Curated table/column descriptions sourced from the Vantage API reference (https://vantage.readme.io).+# Keyed by endpoint/schema name (matching ENDPOINTS). Columns not covered here fall back to LLM+# enrichment using the table's docs_url and column types.+CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {+ "cost_reports": {+ "description": "A saved report that visualizes and filters cloud cost data across providers over a date range.",+ "docs_url": "https://vantage.readme.io/reference/getcostreports",+ "columns": {+ "token": "Unique identifier (token) for the cost_report record.",+ "title": "The title of the CostReport.",+ "folder_token": "The token for the Folder the CostReport is a part of.",+ "saved_filter_tokens": "The tokens for the SavedFilters assigned to the CostReport.",+ "business_metric_tokens_with_metadata": "The tokens for the BusinessMetrics assigned to the CostReport, the unit scale, and label filter.",+ "default_forecast": "The default forecast selection for the CostReport.",+ "filter": "The filter applied to the CostReport. Additional documentation available at https://docs.vantage.sh/vql.",+ "groupings": "The grouping aggregations applied to the filtered data.",+ "settings": "Report settings.",+ "created_at": "The date and time, in UTC, the report was created. ISO 8601 Formatted.",+ "workspace_token": "The token for the Workspace the CostReport is a part of.",+ "previous_period_start_date": "The previous period start date of the CostReport. ISO 8601 Formatted.",+ "previous_period_end_date": "The previous period end date of the CostReport. ISO 8601 Formatted.",+ "start_date": "The start date of the CostReports. ISO 8601 Formatted. Overwrites 'date_interval' if set.",+ "end_date": "The end date of the CostReports. ISO 8601 Formatted. Overwrites 'date_interval' if set.",+ "date_interval": "The date interval of the CostReport.",+ "chart_type": "The chart type of the CostReport.",+ "date_bin": "The date bin of the CostReport.",+ },+ },+ "budgets": {+ "description": "A spending budget defined against a cost report, with periods and alert thresholds.",+ "docs_url": "https://vantage.readme.io/reference/getbudgets",+ "columns": {+ "token": "Unique identifier (token) for the budget record.",+ "name": "The name of the Budget.",+ "workspace_token": "The token for the Workspace the Budget is a part of.",+ "user_token": "The token for the User who created this Budget.",+ "created_by_token": "The token of the Creator of the Budget.",+ "cost_report_token": "The token of the Report associated with the Budget.",+ "created_at": "The date and time, in UTC, the Budget was created. ISO 8601 Formatted.",+ "budget_alert_tokens": "The tokens of the BudgetAlerts associated with the Budget.",+ "child_budget_tokens": "The tokens of the child Budgets associated with the hierarchical Budget.",+ "periods": "The budget periods associated with the Budget.",+ "performance": "The historical performance of the Budget.",+ },+ },+ "folders": {+ "description": "A folder used to organize cost reports and other resources in a workspace.",+ "docs_url": "https://vantage.readme.io/reference/getfolders",+ "columns": {+ "token": "Unique identifier (token) for the folder record.",+ "title": "The title of the Folder.",+ "type": "The type of the Folder.",+ "parent_folder_token": "The token for the parent Folder, if any.",+ "saved_filter_tokens": "The tokens for the SavedFilters assigned to the Folder.",+ "created_at": "The date and time, in UTC, the Folder was created. ISO 8601 Formatted.",+ "updated_at": "The date and time, in UTC, the Folder was last updated at. ISO 8601 Formatted.",+ "workspace_token": "The token for the Workspace the Folder is a part of.",+ },+ },+ "dashboards": {+ "description": "A dashboard composed of widgets that visualize cost and usage data.",+ "docs_url": "https://vantage.readme.io/reference/getdashboards",+ "columns": {+ "token": "Unique identifier (token) for the dashboard record.",+ "title": "The title of the Dashboard.",+ "saved_filter_tokens": "The tokens of the Saved Filters used in the Dashboard.",+ "date_bin": "Determines how to group costs in the Dashboard.",+ "date_interval": "Determines the date range for Reports in the Dashboard. Guaranteed to be set to 'custom' if 'start_date' and 'end_date' are set.",+ "start_date": "The start date for the date range for Reports in the Dashboard. ISO 8601 Formatted. Overwrites 'date_interval' if set.",+ "end_date": "The end date for the date range for Reports in the Dashboard. ISO 8601 Formatted. Overwrites 'date_interval' if set.",+ "created_at": "The date and time, in UTC, the Dashboard was created. ISO 8601 Formatted.",+ "updated_at": "The date and time, in UTC, the Dashboard was created. ISO 8601 Formatted.",+ "workspace_token": "The token for the Workspace the Dashboard is a part of.",+ },+ },+ "cost_alerts": {+ "description": "A cost alert that notifies recipients when spend crosses a configured threshold.",+ "docs_url": "https://vantage.readme.io/reference/getcostalerts",+ "columns": {+ "token": "Unique identifier (token) for the cost_alert record.",+ "email_recipients": "The email addresses that will receive the alert.",+ "slack_channels": "The Slack channels that will receive the alert. Make sure your slack integration is connected at https://console.vantage.sh/settings/slack.",+ "teams_channels": "The Microsoft Teams channels that will receive the alert. Make sure your teams integration is connected at https://console.vantage.sh/settings/microsoft_teams.",+ "created_at": "The date and time, in UTC, for when the alert was created. ISO 8601 Formatted.",+ "updated_at": "The date and time, in UTC, for when the alert was last updated. ISO 8601 Formatted.",+ "workspace_token": "The ID of the organization that owns the CostAlert.",+ "interval": "The period of time used to compare costs. Options are 'day', 'week', 'month', 'quarter'.",+ "threshold": "The cost change threshold to alert on.",+ "unit_type": "The unit type used to compare costs. Options are 'currency' or 'percentage'.",+ "minimum_threshold": "The minimum monetary amount threshold for percentage-based alerts. When set, alerts will only trigger if the cost change meets this minimum, even if the percentage threshold is exceeded.",+ "report_tokens": "The tokens of the reports to alert on.",+ },+ },+ "anomaly_alerts": {+ "description": "An anomaly alert flagging an unexpected change in spend for a provider/service.",+ "docs_url": "https://vantage.readme.io/reference/getanomalyalerts",+ "columns": {+ "token": "Unique identifier (token) for the anomaly_alert record.",+ "created_at": "The date and time, in UTC, the AnomalyAlert was created. ISO 8601 Formatted.",+ "alerted_at": "The date and time, in UTC, the AnomalyAlert is sent. ISO 8601 Formatted.",+ "category": "The category of the AnomalyAlert.",+ "service": "The provider service causing the AnomalyAlert.",+ "provider": "The provider of the service causing the AnomalyAlert.",+ "amount": "The amount observed.",+ "previous_amount": "The previous amount observed.",+ "seven_day_average": "The seven day average of the amount observed.",+ "status": "The status of the AnomalyAlert.",+ "feedback": "The user-provided feedback of why alert was ignored/archived.",+ "resources": "The names of the resources the AnomalyAlert was attributed to.",+ "resource_tokens": "The tokens of the Resources the AnomalyAlert was attributed to.",+ "cost_report_token": "The token of the Report associated with the AnomalyAlert.",+ },+ },+ "resource_reports": {+ "description": "A report listing cloud resources matching a filter, with optional cost data.",+ "docs_url": "https://vantage.readme.io/reference/getresourcereports",+ "columns": {+ "token": "Unique identifier (token) for the resource_report record.",+ "title": "The title of the ResourceReport.",+ "filter": "The filter applied to the ResourceReport. Additional documentation available at https://docs.vantage.sh/vql.",+ "created_at": "The date and time, in UTC, the report was created. ISO 8601 Formatted.",+ "workspace_token": "The token for the Workspace the ResourceReport is a part of.",+ "user_token": "The token for the User who created this ResourceReport.",+ "created_by_token": "The token for the User or Team who created this ResourceReport.",+ "folder_token": "The token for the Folder the ResourceReport is a part of.",+ "columns": "Array of column names configured for the ResourceReport table display.",+ },+ },+ "financial_commitment_reports": {+ "description": "A report analyzing commitment-based discounts (reservations, savings plans).",+ "docs_url": "https://vantage.readme.io/reference/getfinancialcommitmentreports",+ "columns": {+ "token": "Unique identifier (token) for the financial_commitment_report record.",+ "title": "The title of the FinancialCommitmentReport.",+ "default": "Indicates whether the FinancialCommitmentReport is the default report.",+ "created_at": "The date and time, in UTC, the report was created. ISO 8601 Formatted.",+ "workspace_token": "The token for the Workspace the FinancialCommitmentReport is a part of.",+ "user_token": "The token for the User who created this FinancialCommitmentReport.",+ "start_date": "The start date for the FinancialCommitmentReport. Only set for custom date ranges. ISO 8601 Formatted.",+ "end_date": "The end date for the FinancialCommitmentReport. Only set for custom date ranges. ISO 8601 Formatted.",+ "date_interval": "The date range for the FinancialCommitmentReport. Only present if a custom date range is not specified.",+ "date_bucket": "How costs are grouped and displayed in the FinancialCommitmentReport. Possible values: day, week, month.",+ "groupings": "The grouping aggregations applied to the filtered data.",+ "on_demand_costs_scope": "The scope for the costs. Possible values: discountable, all.",+ "filter": "The filter applied to the FinancialCommitmentReport. Additional documentation available at https://docs.vantage.sh/vql.",+ },+ },+ "network_flow_reports": {+ "description": "A report analyzing network flow costs and data transfer.",+ "docs_url": "https://vantage.readme.io/reference/getnetworkflowreports",+ "columns": {+ "token": "Unique identifier (token) for the network_flow_report record.",+ "title": "The title of the NetworkFlowReport.",+ "default": "Indicates whether the NetworkFlowReport is the default report.",+ "created_at": "The date and time, in UTC, the report was created. ISO 8601 Formatted.",+ "workspace_token": "The token for the Workspace the NetworkFlowReport is a part of.",+ "created_by_token": "The token for the User or Team that created this NetworkFlowReport.",+ "start_date": "The start date for the NetworkFlowReport. Only set for custom date ranges. ISO 8601 Formatted.",+ "end_date": "The end date for the NetworkFlowReport. Only set for custom date ranges. ISO 8601 Formatted.",+ "date_interval": "The date range for the NetworkFlowReport. Only present if a custom date range is not specified.",+ "groupings": "The grouping aggregations applied to the filtered data.",+ "flow_direction": "The flow weight of the NetworkFlowReport. Possible values: costs, bytes.",+ "flow_weight": "The flow weight of the NetworkFlowReport. Possible values: costs, bytes.",+ "filter": "The filter applied to the NetworkFlowReport. Additional documentation available at https://docs.vantage.sh/vql.",+ },+ },+ "kubernetes_efficiency_reports": {+ "description": "A report analyzing Kubernetes cluster cost efficiency.",+ "docs_url": "https://vantage.readme.io/reference/getkubernetesefficiencyreports",+ "columns": {+ "token": "Unique identifier (token) for the kubernetes_efficiency_report record.",+ "title": "The title of the KubernetesEfficiencyReport.",+ "default": "Indicates whether the KubernetesEfficiencyReport is the default report.",+ "created_at": "The date and time, in UTC, the report was created. ISO 8601 Formatted.",+ "workspace_token": "The token for the Workspace the KubernetesEfficiencyReport is a part of.",+ "user_token": "The token for the User who created this KubernetesEfficiencyReport.",+ "start_date": "The start date for the KubernetesEfficiencyReport. Only set for custom date ranges. ISO 8601 Formatted.",+ "end_date": "The end date for the KubernetesEfficiencyReport. Only set for custom date ranges. ISO 8601 Formatted.",+ "date_interval": "The date range for the KubernetesEfficiencyReport. Only present if a custom date range is not specified.",+ "date_bucket": "How costs are grouped and displayed in the KubernetesEfficiencyReport. Possible values: day, week, month.",+ "aggregated_by": "How costs are aggregated by. Possible values: idle_cost, amount, cost_efficiency.",+ "groupings": "Grouping values for aggregating costs on the KubernetesEfficiencyReport. Valid groupings: cluster_id, namespace, region, labeled, category, pod, label, label:<label_name>.",+ "filter": "The filter applied to the KubernetesEfficiencyReport. Additional documentation available at https://docs.vantage.sh/vql.",+ },+ },+ "segments": {+ "description": "A segment that allocates a slice of costs by a filter, used for showback/chargeback.",+ "docs_url": "https://vantage.readme.io/reference/getsegments",+ "columns": {+ "token": "Unique identifier (token) for the segment record.",+ "title": "The title of the Segment.",+ "parent_segment_token": "The token of the parent Segment of this Segment.",+ "description": "The description of the Segment.",+ "track_unallocated": "Track Unallocated Costs which are not assigned to any of the created Segments.",+ "report_settings": "Report settings configurable on top-level Segments.",+ "priority": "Costs are assigned in priority order across all Segments with assigned filters.",+ "filter": "The filter applied to the Segment. Additional documentation available at https://docs.vantage.sh/vql.",+ "created_at": "The date and time, in UTC, the Segment was created. ISO 8601 Formatted.",+ "workspace_token": "The token for the Workspace the Segment is a part of.",+ "report_token": "The token for the Report the Segment has generated.",+ },+ },+ "saved_filters": {+ "description": "A reusable, saved VQL cost filter that can be applied across reports.",+ "docs_url": "https://vantage.readme.io/reference/getsavedfilters",+ "columns": {+ "token": "Unique identifier (token) for the saved_filter record.",+ "title": "The title of the SavedFilter.",+ "cost_report_tokens": "The tokens for any CostReports the SavedFilter is applied to.",+ "filter": "The SavedFilter's filter, applied to any relevant CostReports. Additional documentation available at https://docs.vantage.sh/vql.",+ "created_at": "The date and time, in UTC, the report was created. ISO 8601 Formatted.",+ "created_by": "The token for the Creator of this SavedFilter.",+ "workspace_token": "The token for the Workspace the SavedFilter is a part of.",+ },+ },+ "recommendations": {+ "description": "A cost-saving recommendation identified by Vantage for a provider/service.",+ "docs_url": "https://vantage.readme.io/reference/getrecommendations",+ "columns": {+ "token": "Unique identifier (token) for the recommendation record.",+ "type": "The type of the Recommendation. This is analogous to category, but with a uniform format.",+ "category": "The category of the Recommendation.",+ "workspace_token": "The token for the Workspace the Recommendation is a part of.",+ "provider": "The provider the Recommendation is for.",+ "provider_account_id": "The account ID of the provider. For Azure, this is the subscription ID.",+ "documentation_url": "A URL to related documentation if available.",+ "potential_savings": "The monthly potential savings of the Recommendation, converted to the organization's selected currency.",+ "service": "The service the Recommendation is for.",+ "created_at": "The date and time, in UTC, the Recommendation was created. ISO 8601 Formatted.",+ "resources_affected_count": "The number of ProviderResources related to the Recommendation. Use the `recommendations/:token/resources` endpoint to get the full list of resources.",+ "currency_code": "The currency code used by the Workspace to which this Recommendation belongs.",+ "currency_symbol": "The currency symbol used by the Workspace to which this Recommendation belongs.",+ },+ },+ "billing_rules": {+ "description": "A billing rule that adjusts costs (e.g. credits, charges, adjustments) for MSP billing.",+ "docs_url": "https://vantage.readme.io/reference/getbillingrules",+ "columns": {+ "token": "Unique identifier (token) for the billing_rule record.",+ "title": "The title of the BillingRule.",+ "type": "The type of the BillingRule.",+ "start_date": "The start date of the BillingRule.",+ "end_date": "The end date of the BillingRule.",+ "apply_to_all": "Whether the BillingRule applies to all future managed accounts.",+ "created_by_token": "The token of the Creator of the BillingRule.",+ "created_at": "The date and time, in UTC, the BillingRule was created. ISO 8601 Formatted.",+ "service": "The service for the BillingRule (Charge).",+ "category": "The category for the BillingRule (Charge).",+ "percentage": "The percentage of the cost shown for the BillingRule (Adjustment).",+ "charge_type": "The charge type for the BillingRule.",+ "sub_category": "The subcategory for the BillingRule (Charge).",+ "start_period": "The start period for the BillingRule (Charge).",+ "amount": "The amount for the BillingRule (Charge).",+ "sql_query": "The SQL query for the BillingRule (Custom).",+ },+ },+ "access_grants": {+ "description": "An access grant defining a team's access to a resource.",+ "docs_url": "https://vantage.readme.io/reference/getaccessgrants",+ "columns": {+ "token": "Unique identifier (token) for the access_grant record.",+ "resource_token": "The token for any resource the AccessGrant is applied to.",+ "access": "The access status of the AccessGrant.",+ "team_token": "The Team token for which an AccessGrant is applied to.",+ "created_at": "The date and time, in UTC, the AccessGrant was created. ISO 8601 Formatted.",+ "created_by": "The token for the User who created the AccessGrant.",+ },+ },+ "integrations": {+ "description": "A connected cloud provider integration (AWS, Azure, GCP, etc.) feeding cost data.",+ "docs_url": "https://vantage.readme.io/reference/getintegrations",+ "columns": {+ "token": "Unique identifier (token) for the integration record.",+ "provider": "The name of the Integration.",+ "account_identifier": "The account identifier. For GCP this is the billing Account ID, for Azure this is the account ID",+ "status": "The status of the Integration. Can be 'connected', 'error', 'pending', 'importing', 'imported', or 'disconnected'.",+ "last_updated": "The date and time, in UTC, when the Integration was last updated. ISO 8601 Formatted.",+ "workspace_tokens": "The tokens for any Workspaces that the account belongs to.",+ "created_at": "The date and time, in UTC, the Integration was created. ISO 8601 Formatted.",+ "managed_account_tokens": "The tokens for any Managed Accounts that are associated with the Integration.",+ },+ },+ "workspaces": {+ "description": "A workspace grouping related resources, integrations, and reports.",+ "docs_url": "https://vantage.readme.io/reference/getworkspaces",+ "columns": {+ "token": "Unique identifier (token) for the workspace record.",+ "name": "The name of the Workspace.",+ "created_at": "The date and time, in UTC, the Workspace was created. ISO 8601 Formatted.",+ "enable_currency_conversion": "Whether or not currency conversion is enabled for the Workspace.",+ "currency": "The currency code for the Workspace that will be used for currency conversion.",+ "exchange_rate_date": "The exchange rate date that will be used to convert currency for your cost data.",+ },+ },+ "report_notifications": {+ "description": "A scheduled notification that delivers a cost report to recipients.",+ "docs_url": "https://vantage.readme.io/reference/getreportnotifications",+ "columns": {+ "token": "Unique identifier (token) for the report_notification record.",+ "title": "The title of the ReportNotification.",+ "cost_report_token": "The token for a CostReport the ReportNotification is applied to.",+ "user_tokens": "The Users that receive the notification.",+ "recipient_channels": "The Slack or Microsoft Teams channels that receive the notification.",+ "frequency": "The frequency the ReportNotification is sent.",+ "change": "The type of change the ReportNotification is tracking.",+ },+ },+ "teams": {+ "description": "A team of users, used to manage access and notifications.",+ "docs_url": "https://vantage.readme.io/reference/getteams",+ "columns": {+ "token": "Unique identifier (token) for the team record.",+ "name": "The name of the Team.",+ "description": "The description of the Team.",+ "workspace_tokens": "The tokens for any Workspaces that the Team belongs to",+ "user_emails": "The email addresses for Users that belong to the Team",+ "user_tokens": "The tokens for Users that belong to the Team",+ "default_dashboard_token": "The token of the default Dashboard for the Team.",+ },+ },+ "users": {+ "description": "A user belonging to the Vantage account.",+ "docs_url": "https://vantage.readme.io/reference/getusers",+ "columns": {+ "token": "Unique identifier (token) for the user record.",+ "name": "The name of the User.",+ "email": "The email of the User.",+ "role": "The role of the User.",+ "default_dashboard_token": "The token of the default Dashboard for the User.",+ "last_seen_at": "The last time the User logged in.",+ },+ },+}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.pynew file mode 100644index 000000000000..84464c40cf97--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/vantage/settings.py@@ -0,0 +1,101 @@+from dataclasses import dataclass, field+from typing import Optional++from products.warehouse_sources.backend.types import IncrementalField+++@dataclass+class VantageEndpointConfig:+ name: str+ # API path relative to the v2 base URL (e.g. "/cost_reports").+ path: str+ # 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"])+ # 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+ # Whether the table is selected for sync by default in the UI.+ should_sync_default: bool = True+ # 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)+++# 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).+VANTAGE_ENDPOINTS: dict[str, VantageEndpointConfig] = {+ "cost_reports": VantageEndpointConfig(+ name="cost_reports", path="/cost_reports", data_key="cost_reports", partition_key="created_at"+ ),+ "budgets": VantageEndpointConfig(name="budgets", path="/budgets", data_key="budgets", partition_key="created_at"),+ "folders": VantageEndpointConfig(name="folders", path="/folders", data_key="folders", partition_key="created_at"),+ "dashboards": VantageEndpointConfig(+ name="dashboards", path="/dashboards", data_key="dashboards", partition_key="created_at"+ ),+ "cost_alerts": VantageEndpointConfig(+ name="cost_alerts", path="/cost_alerts", data_key="cost_alerts", partition_key="created_at"+ ),+ "anomaly_alerts": VantageEndpointConfig(+ name="anomaly_alerts", path="/anomaly_alerts", data_key="anomaly_alerts", partition_key="created_at"+ ),+ "resource_reports": VantageEndpointConfig(+ name="resource_reports", path="/resource_reports", data_key="resource_reports", partition_key="created_at"+ ),+ "financial_commitment_reports": VantageEndpointConfig(+ name="financial_commitment_reports",+ path="/financial_commitment_reports",+ data_key="financial_commitment_reports",+ partition_key="created_at",+ ),+ "network_flow_reports": VantageEndpointConfig(+ name="network_flow_reports",+ path="/network_flow_reports",+ data_key="network_flow_reports",+ partition_key="created_at",+ ),+ "kubernetes_efficiency_reports": VantageEndpointConfig(+ name="kubernetes_efficiency_reports",+ path="/kubernetes_efficiency_reports",+ data_key="kubernetes_efficiency_reports",+ partition_key="created_at",+ ),+ "segments": VantageEndpointConfig(+ name="segments", path="/segments", data_key="segments", partition_key="created_at"+ ),+ "saved_filters": VantageEndpointConfig(+ name="saved_filters", path="/saved_filters", data_key="saved_filters", partition_key="created_at"+ ),+ "recommendations": VantageEndpointConfig(+ name="recommendations", path="/recommendations", data_key="recommendations", partition_key="created_at"+ ),+ "billing_rules": VantageEndpointConfig(+ name="billing_rules", path="/billing_rules", data_key="billing_rules", partition_key="created_at"+ ),+ "access_grants": VantageEndpointConfig(+ name="access_grants", path="/access_grants", data_key="access_grants", partition_key="created_at"+ ),+ "integrations": VantageEndpointConfig(+ name="integrations", path="/integrations", data_key="integrations", partition_key="created_at"+ ),+ "workspaces": VantageEndpointConfig(+ name="workspaces", path="/workspaces", data_key="workspaces", partition_key="created_at"+ ),+ # No `created_at` on these objects, so they're synced without partitioning.+ "report_notifications": VantageEndpointConfig(+ name="report_notifications", path="/report_notifications", data_key="report_notifications"+ ),+ "teams": VantageEndpointConfig(name="teams", path="/teams", data_key="teams"),+ "users": VantageEndpointConfig(name="users", path="/users", data_key="users"),+}++ENDPOINTS = tuple(VANTAGE_ENDPOINTS.keys())++INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {+ name: config.incremental_fields 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.pyindex 58041feee6de..633c6ad9ac69 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@@ -1,19 +1,43 @@-from typing import cast+from typing import Optional, castfrom posthog.schema import (DataWarehouseSourceCategory,ExternalDataSourceType as SchemaExternalDataSourceType,+ ReleaseStatus,SourceConfig,+ SourceFieldInputConfig,+ SourceFieldInputConfigType,)-from products.warehouse_sources.backend.temporal.data_imports.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 SourceSchemafrom products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs import VantageSourceConfig+from products.warehouse_sources.backend.temporal.data_imports.sources.vantage.settings import (+ ENDPOINTS,+ INCREMENTAL_FIELDS,+ VANTAGE_ENDPOINTS,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.vantage.vantage import (+ VantageResumeConfig,+ validate_credentials as validate_vantage_credentials,+ vantage_source,+)from products.warehouse_sources.backend.types import ExternalDataSourceType@SourceRegistry.register-class VantageSource(SimpleSource[VantageSourceConfig]):+class VantageSource(ResumableSource[VantageSourceConfig, VantageResumeConfig]):+ lists_tables_without_credentials = True # static endpoint catalog - safe for public docs+@propertydef source_type(self) -> ExternalDataSourceType:return ExternalDataSourceType.VANTAGE@@ -22,9 +46,90 @@ class VantageSource(SimpleSource[VantageSourceConfig]):def get_source_config(self) -> SourceConfig:return SourceConfig(name=SchemaExternalDataSourceType.VANTAGE,- category=DataWarehouseSourceCategory.ENGINEERING___MONITORING,+ category=DataWarehouseSourceCategory.FINANCE___ACCOUNTING,label="Vantage",- iconPath="/static/services/vantage.png",- fields=cast(list[FieldType], []),+ releaseStatus=ReleaseStatus.ALPHA,unreleasedSource=True,+ caption="""Enter your Vantage API access token to pull your Vantage FinOps data into the PostHog Data warehouse.++Create a read-scoped access token or a service token from your [Vantage settings](https://console.vantage.sh/settings/access_tokens). Only the `read` scope is required for imports.""",+ iconPath="/static/services/vantage.png",+ docsUrl="https://posthog.com/docs/cdp/sources/vantage",+ fields=cast(+ list[FieldType],+ [+ SourceFieldInputConfig(+ name="api_key",+ label="API access token",+ type=SourceFieldInputConfigType.PASSWORD,+ required=True,+ placeholder="vntg_tkn_...",+ secret=True,+ ),+ ],+ ),+ )++ def get_canonical_descriptions(self) -> CanonicalDescriptions:+ from products.warehouse_sources.backend.temporal.data_imports.sources.vantage.canonical_descriptions import (+ CANONICAL_DESCRIPTIONS,+ )++ return CANONICAL_DESCRIPTIONS++ def get_non_retryable_errors(self) -> dict[str, str | None]:+ return {+ # A bad, revoked, or expired token surfaces as an HTTPError when `_fetch_page` calls+ # `raise_for_status()`. Retrying can never fix a credential problem, so stop the sync.+ "401 Client Error: Unauthorized for url: https://api.vantage.sh": "Your Vantage API access token is invalid or has been revoked. Create a new read-scoped token in your Vantage settings, then reconnect.",+ "403 Client Error: Forbidden for url: https://api.vantage.sh": "Your Vantage API access token is missing the read scope needed to sync this data. Grant the read scope in your Vantage settings, then reconnect.",+ }++ def get_schemas(+ self,+ config: VantageSourceConfig,+ 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 = VANTAGE_ENDPOINTS[endpoint]+ has_incremental = len(INCREMENTAL_FIELDS.get(endpoint, [])) > 0+ return SourceSchema(+ name=endpoint,+ supports_incremental=has_incremental,+ supports_append=has_incremental,+ incremental_fields=INCREMENTAL_FIELDS.get(endpoint, []),+ 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: VantageSourceConfig, team_id: int, schema_name: Optional[str] = None+ ) -> tuple[bool, str | None]:+ if validate_vantage_credentials(config.api_key):+ return True, None++ return False, "Invalid Vantage API access token"++ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[VantageResumeConfig]:+ return ResumableSourceManager[VantageResumeConfig](inputs, VantageResumeConfig)++ def source_for_pipeline(+ self,+ config: VantageSourceConfig,+ resumable_source_manager: ResumableSourceManager[VantageResumeConfig],+ inputs: SourceInputs,+ ) -> SourceResponse:+ return vantage_source(+ api_key=config.api_key,+ endpoint=inputs.schema_name,+ logger=inputs.logger,+ resumable_source_manager=resumable_source_manager,)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.pynew file mode 100644index 000000000000..978ba822c652--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/vantage/tests/test_vantage.py@@ -0,0 +1,246 @@+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.pipelines.pipeline.batcher import Batcher+from products.warehouse_sources.backend.temporal.data_imports.sources.vantage import vantage+from products.warehouse_sources.backend.temporal.data_imports.sources.vantage.vantage import (+ VANTAGE_BASE_URL,+ VantageResumeConfig,+ _build_initial_url,+ get_rows,+ validate_credentials,+ vantage_source,+)+++class _FakeResumableManager:+ def __init__(self, state: VantageResumeConfig | None = None) -> None:+ self._state = state+ self.saved: list[VantageResumeConfig] = []++ def can_resume(self) -> bool:+ return self._state is not None++ def load_state(self) -> VantageResumeConfig | None:+ return self._state++ def save_state(self, data: VantageResumeConfig) -> None:+ self.saved.append(data)+++def _collect(+ manager: _FakeResumableManager, monkeypatch: Any, pages: dict[str, Any], endpoint: str = "cost_reports"+) -> tuple[list[dict], list[str]]:+ fetched: list[str] = []++ def fake_fetch(session: Any, url: str, headers: dict[str, str], logger: Any) -> dict:+ fetched.append(url)+ result = pages[url]+ if isinstance(result, Exception):+ raise result+ return result++ monkeypatch.setattr(vantage, "_fetch_page", fake_fetch)++ rows: list[dict] = []+ for table in get_rows(+ api_key="tok",+ endpoint=endpoint,+ logger=MagicMock(),+ resumable_source_manager=manager, # type: ignore[arg-type]+ ):+ rows.extend(table.to_pylist())+ return rows, fetched+++class TestPagination:+ def test_follows_links_next_and_terminates(self, monkeypatch: Any) -> None:+ # Regression guard: not advancing the URL loops forever; not terminating on a null `next`+ # over-fetches. Rows must come back across every page, in order.+ p1 = _build_initial_url(vantage.VANTAGE_ENDPOINTS["cost_reports"])+ p2 = f"{VANTAGE_BASE_URL}/cost_reports?page=2&limit=1000"+ pages = {+ p1: {"cost_reports": [{"token": "a"}, {"token": "b"}], "links": {"next": p2}},+ p2: {"cost_reports": [{"token": "c"}], "links": {"next": None}},+ }+ rows, fetched = _collect(_FakeResumableManager(), monkeypatch, pages)+ assert rows == [{"token": "a"}, {"token": "b"}, {"token": "c"}]+ assert fetched == [p1, p2]++ def test_reads_endpoint_specific_data_key(self, monkeypatch: Any) -> None:+ # The row array is nested under the endpoint's own key (e.g. "budgets"), never a hardcoded+ # "data" - reading the wrong key silently yields zero rows.+ p1 = _build_initial_url(vantage.VANTAGE_ENDPOINTS["budgets"])+ pages = {p1: {"budgets": [{"token": "b1"}], "links": {"next": None}}}+ rows, _ = _collect(_FakeResumableManager(), monkeypatch, pages, endpoint="budgets")+ assert rows == [{"token": "b1"}]++ def test_missing_links_object_terminates(self, monkeypatch: Any) -> None:+ # A last page may omit `links` entirely; the paginator must stop, not KeyError.+ p1 = _build_initial_url(vantage.VANTAGE_ENDPOINTS["cost_reports"])+ pages = {p1: {"cost_reports": [{"token": "a"}]}}+ rows, fetched = _collect(_FakeResumableManager(), monkeypatch, pages)+ assert rows == [{"token": "a"}]+ assert fetched == [p1]+++class TestResume:+ def test_starts_from_initial_url_without_state(self, monkeypatch: Any) -> None:+ p1 = _build_initial_url(vantage.VANTAGE_ENDPOINTS["cost_reports"])+ pages = {p1: {"cost_reports": [], "links": {"next": None}}}+ _, fetched = _collect(_FakeResumableManager(), monkeypatch, pages)+ assert fetched == [p1]+ assert "limit=1000" in p1++ def test_resumes_from_saved_url(self, monkeypatch: Any) -> None:+ # Ignoring saved state restarts from page 1 and re-fetches everything already synced.+ resume_url = f"{VANTAGE_BASE_URL}/cost_reports?page=5&limit=1000"+ pages = {resume_url: {"cost_reports": [{"token": "z"}], "links": {"next": None}}}+ manager = _FakeResumableManager(VantageResumeConfig(next_url=resume_url))+ rows, fetched = _collect(manager, monkeypatch, pages)+ assert fetched == [resume_url]+ assert rows == [{"token": "z"}]++ def test_saves_state_after_yield_only_while_pages_remain(self, monkeypatch: Any) -> None:+ # With a tiny chunk size every page emits a batch, so we can observe that resume state is+ # persisted with the *next* page's URL (so a crash re-yields the last page, not skips it)+ # and is never saved on the final page (no `next` to resume from).+ monkeypatch.setattr(+ vantage, "Batcher", lambda **kwargs: Batcher(logger=kwargs["logger"], chunk_size=1, chunk_size_bytes=10**9)+ )+ p1 = _build_initial_url(vantage.VANTAGE_ENDPOINTS["cost_reports"])+ p2 = f"{VANTAGE_BASE_URL}/cost_reports?page=2&limit=1000"+ pages = {+ p1: {"cost_reports": [{"token": "a"}, {"token": "b"}], "links": {"next": p2}},+ p2: {"cost_reports": [{"token": "c"}, {"token": "d"}], "links": {"next": None}},+ }+ manager = _FakeResumableManager()+ _collect(manager, monkeypatch, pages)+ saved_urls = [s.next_url for s in manager.saved]+ assert saved_urls # state was persisted at least once+ assert all(u == p2 for u in saved_urls) # only ever the pending page, never the final one+++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:+ response = MagicMock()+ response.status_code = status+ session = MagicMock()+ session.get.return_value = response+ with patch.object(vantage, "make_tracked_session", return_value=session):+ assert validate_credentials("tok") is expected++ def test_network_error_is_invalid(self) -> None:+ session = MagicMock()+ session.get.side_effect = requests.ConnectionError("boom")+ with patch.object(vantage, "make_tracked_session", return_value=session):+ assert validate_credentials("tok") is False++ def test_probes_cheap_ping_endpoint(self) -> None:+ # Validation must not hit a Cost Report endpoint (5 req/5s cap) - `/ping` is the cheap probe.+ response = MagicMock()+ response.status_code = 200+ session = MagicMock()+ session.get.return_value = response+ with patch.object(vantage, "make_tracked_session", return_value=session):+ validate_credentials("tok")+ assert session.get.call_args[0][0] == f"{VANTAGE_BASE_URL}/ping"+++class TestFetchPageRetries:+ @parameterized.expand([("rate_limited", 429), ("server_error", 500), ("bad_gateway", 502)])+ def test_retryable_status_is_retried(self, _name: str, status: int) -> None:+ retryable = MagicMock()+ retryable.status_code = status+ good = MagicMock()+ good.status_code = 200+ good.ok = True+ good.json.return_value = {"cost_reports": [], "links": {"next": None}}+ session = MagicMock()+ session.get.side_effect = [retryable, good]++ with patch.object(vantage._fetch_page.retry, "sleep", lambda *_: None): # type: ignore[attr-defined]+ result = vantage._fetch_page(session, f"{VANTAGE_BASE_URL}/cost_reports", {}, MagicMock())++ assert result == {"cost_reports": [], "links": {"next": None}}+ assert session.get.call_count == 2++ @parameterized.expand(+ [+ ("read_timeout", requests.ReadTimeout("Read timed out.")),+ ("connection_error", requests.ConnectionError("Connection reset by peer")),+ ("chunked", requests.exceptions.ChunkedEncodingError("Connection broken")),+ ]+ )+ def test_transient_network_error_is_retried(self, _name: str, err: Exception) -> None:+ good = MagicMock()+ good.status_code = 200+ good.ok = True+ good.json.return_value = {"cost_reports": []}+ session = MagicMock()+ session.get.side_effect = [err, good]++ with patch.object(vantage._fetch_page.retry, "sleep", lambda *_: None): # type: ignore[attr-defined]+ result = vantage._fetch_page(session, f"{VANTAGE_BASE_URL}/cost_reports", {}, MagicMock())++ assert result == {"cost_reports": []}+ assert session.get.call_count == 2++ def test_client_error_is_raised_not_retried(self) -> None:+ # A 4xx (other than 429) is a permanent client error - raise immediately so+ # get_non_retryable_errors can classify it, rather than burning retries.+ response = MagicMock()+ response.status_code = 404+ response.ok = False+ response.raise_for_status.side_effect = requests.HTTPError("404 Client Error", response=response)+ session = MagicMock()+ session.get.return_value = response++ with pytest.raises(requests.HTTPError):+ vantage._fetch_page(session, f"{VANTAGE_BASE_URL}/cost_reports", {}, MagicMock())+ assert session.get.call_count == 1++ @parameterized.expand(+ [+ ("off_host", "https://evil.example.com/v2/cost_reports"),+ ("subdomain_lookalike", "https://api.vantage.sh.evil.example.com/v2/cost_reports"),+ ("plain_http", "http://api.vantage.sh/v2/cost_reports"),+ ("wrong_path_prefix", "https://api.vantage.sh/internal/cost_reports"),+ ]+ )+ def test_untrusted_url_is_refused_without_sending_token(self, _name: str, url: str) -> None:+ # `links.next` is server-controlled; the bearer token must never leave Vantage's own host,+ # so an off-host/non-HTTPS URL is refused before any request (and thus any auth header) goes out.+ session = MagicMock()+ with pytest.raises(vantage.VantageUntrustedURLError):+ vantage._fetch_page(session, url, {"Authorization": "Bearer tok"}, MagicMock())+ session.get.assert_not_called()+++class TestSourceResponse:+ @parameterized.expand(+ [+ ("cost_reports", "created_at"),+ ("workspaces", "created_at"),+ ]+ )+ def test_datetime_partitioning_on_created_at(self, endpoint: str, partition_key: str) -> None:+ response = vantage_source("tok", endpoint, MagicMock(), MagicMock())+ assert response.primary_keys == ["token"]+ assert response.sort_mode == "asc"+ assert response.partition_mode == "datetime"+ assert response.partition_keys == [partition_key]++ @parameterized.expand([("teams",), ("users",), ("report_notifications",)])+ def test_no_partitioning_when_no_stable_created_at(self, endpoint: str) -> None:+ # These objects carry no creation timestamp; partitioning on a missing field would break sync.+ response = vantage_source("tok", endpoint, MagicMock(), MagicMock())+ assert response.partition_mode is None+ assert response.partition_keys is None+ assert response.primary_keys == ["token"]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.pynew file mode 100644index 000000000000..f8c8cde45f6d--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/vantage/tests/test_vantage_source.py@@ -0,0 +1,115 @@+from unittest.mock import MagicMock, patch++from parameterized import parameterized++from posthog.schema import ReleaseStatus, SourceFieldInputConfig, SourceFieldInputConfigType++from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from products.warehouse_sources.backend.temporal.data_imports.sources.vantage.canonical_descriptions import (+ CANONICAL_DESCRIPTIONS,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.vantage.settings import ENDPOINTS+from products.warehouse_sources.backend.temporal.data_imports.sources.vantage.source import VantageSource+from products.warehouse_sources.backend.temporal.data_imports.sources.vantage.vantage import VantageResumeConfig+from products.warehouse_sources.backend.types import ExternalDataSourceType+++class TestVantageSourceConfig:+ def test_source_type(self) -> None:+ assert VantageSource().source_type == ExternalDataSourceType.VANTAGE++ def test_config_has_single_secret_api_key_field(self) -> None:+ # The token is a credential; a non-secret/non-password field would leak it in the UI and API.+ config = VantageSource().get_source_config+ fields = config.fields+ assert len(fields) == 1+ field = fields[0]+ assert isinstance(field, SourceFieldInputConfig)+ assert field.name == "api_key"+ assert field.type == SourceFieldInputConfigType.PASSWORD+ assert field.required is True+ assert field.secret is True++ def test_config_is_alpha_and_unreleased(self) -> None:+ config = VantageSource().get_source_config+ assert config.releaseStatus == ReleaseStatus.ALPHA+ assert config.unreleasedSource is True+ assert config.docsUrl == "https://posthog.com/docs/cdp/sources/vantage"+++class TestGetSchemas:+ def test_lists_every_endpoint_as_full_refresh(self) -> None:+ # Vantage exposes no server-side updated_after cursor, so every table is full refresh only;+ # advertising incremental/append here would let the pipeline skip rows on later syncs.+ schemas = VantageSource().get_schemas(MagicMock(), team_id=1)+ assert {s.name for s in schemas} == set(ENDPOINTS)+ assert all(not s.supports_incremental for s in schemas)+ assert all(not s.supports_append for s in schemas)++ def test_names_filter_restricts_output(self) -> None:+ schemas = VantageSource().get_schemas(MagicMock(), team_id=1, names=["budgets", "folders"])+ assert {s.name for s in schemas} == {"budgets", "folders"}+++class TestValidateCredentials:+ @parameterized.expand([("valid", True, True), ("invalid", False, False)])+ def test_delegates_to_transport(self, _name: str, transport_result: bool, expected_ok: bool) -> None:+ with patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.vantage.source.validate_vantage_credentials",+ return_value=transport_result,+ ):+ ok, error = VantageSource().validate_credentials(MagicMock(), team_id=1)+ assert ok is expected_ok+ assert (error is None) is expected_ok+++class TestResumableWiring:+ def test_manager_bound_to_resume_config(self) -> None:+ manager = VantageSource().get_resumable_source_manager(MagicMock())+ assert isinstance(manager, ResumableSourceManager)+ assert manager._data_class is VantageResumeConfig++ def test_source_for_pipeline_plumbs_schema_name(self) -> None:+ inputs = MagicMock()+ inputs.schema_name = "cost_reports"+ config = MagicMock()+ config.api_key = "tok"+ response = VantageSource().source_for_pipeline(config, MagicMock(), inputs)+ assert response.name == "cost_reports"+ assert response.primary_keys == ["token"]+++class TestNonRetryableErrors:+ @parameterized.expand(+ [+ ("unauthorized", "401 Client Error: Unauthorized for url: https://api.vantage.sh/v2/cost_reports?page=2"),+ ("forbidden", "403 Client Error: Forbidden for url: https://api.vantage.sh/v2/budgets"),+ ]+ )+ def test_credential_errors_are_non_retryable(self, _name: str, observed: str) -> None:+ non_retryable = VantageSource().get_non_retryable_errors()+ assert any(key in observed for key in non_retryable)++ @parameterized.expand(+ [+ ("rate_limited", "429 Client Error: Too Many Requests for url: https://api.vantage.sh/v2/cost_reports"),+ ("server_error", "500 Server Error: Internal Server Error for url: https://api.vantage.sh/v2/budgets"),+ ("timeout", "HTTPSConnectionPool(host='api.vantage.sh', port=443): Read timed out."),+ ]+ )+ def test_transient_errors_remain_retryable(self, _name: str, observed: str) -> None:+ non_retryable = VantageSource().get_non_retryable_errors()+ assert not any(key in observed for key in non_retryable)+++class TestPublicDocsCatalog:+ def test_lists_tables_without_credentials(self) -> None:+ # Static endpoint catalog with no I/O - the public docs Supported tables section depends on this.+ assert VantageSource.lists_tables_without_credentials is True+ tables = VantageSource().get_documented_tables()+ assert {t["name"] for t in tables} == set(ENDPOINTS)+ assert all("Full refresh" in t["sync_methods"] for t in tables)++ 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))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.pynew file mode 100644index 000000000000..160e6654ce9c--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/vantage/vantage.py@@ -0,0 +1,180 @@+import dataclasses+from collections.abc import Iterator+from typing import Any+from urllib.parse import urlencode, urlparse++import requests+from structlog.types import FilteringBoundLogger+from tenacity import 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.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 VantageRetryableError(Exception):+ pass+++class VantageUntrustedURLError(Exception):+ pass+++def _is_trusted_vantage_url(url: str) -> bool:+ # `links.next` (and any resumed cursor derived from it) is server-controlled data. Before we+ # attach the bearer token and fetch it, pin the URL to Vantage's own HTTPS host and `/v2/` API+ # path so a spoofed or compromised response can't redirect the credential to an+ # attacker-controlled origin.+ try:+ parsed = urlparse(url)+ except ValueError:+ return False+ return parsed.scheme == "https" and parsed.hostname == VANTAGE_HOST and parsed.path.startswith("/v2/")+++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+++def _get_headers(api_key: str) -> dict[str, str]:+ return {+ "Authorization": f"Bearer {api_key}",+ "Accept": "application/json",+ }+++def validate_credentials(api_key: str) -> bool:+ # `/ping` is the cheapest authenticated endpoint - it requires a valid read token and returns+ # 401 for a bad/expired one, without touching any cost data (so it can't trip the stricter+ # Cost Report rate limits).+ url = f"{VANTAGE_BASE_URL}/ping"+ try:+ response = make_tracked_session(redact_values=(api_key,)).get(url, headers=_get_headers(api_key), timeout=10)+ return response.status_code == 200+ except Exception:+ return False+++@retry(+ retry=retry_if_exception_type(+ (+ VantageRetryableError,+ requests.ReadTimeout,+ requests.ConnectionError,+ requests.exceptions.ChunkedEncodingError,+ )+ ),+ stop=stop_after_attempt(5),+ wait=wait_exponential_jitter(initial=1, max=30),+ reraise=True,+)+def _fetch_page(+ session: requests.Session, page_url: str, headers: dict[str, str], logger: FilteringBoundLogger+) -> dict:+ if not _is_trusted_vantage_url(page_url):+ raise VantageUntrustedURLError(+ f"Refusing to fetch untrusted Vantage URL: host must be {VANTAGE_HOST} over HTTPS"+ )++ response = session.get(page_url, headers=headers, timeout=60)++ # 429 (rate limited) and 5xx are transient - retry with backoff. Vantage returns rate-limit+ # status in headers and 429 on exceed; the exponential jitter keeps us within the per-key window.+ if response.status_code == 429 or response.status_code >= 500:+ raise VantageRetryableError(f"Vantage API error (retryable): status={response.status_code}, url={page_url}")++ if not response.ok:+ logger.error(f"Vantage API error: status={response.status_code}, body={response.text}, url={page_url}")+ response.raise_for_status()++ return response.json()+++def _build_initial_url(config: VantageEndpointConfig) -> str:+ return f"{VANTAGE_BASE_URL}{config.path}?{urlencode({'limit': PAGE_SIZE})}"+++def get_rows(+ api_key: str,+ endpoint: str,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[VantageResumeConfig],+) -> Iterator[Any]:+ config = VANTAGE_ENDPOINTS[endpoint]+ headers = _get_headers(api_key)+ batcher = Batcher(logger=logger, chunk_size=2000, chunk_size_bytes=100 * 1024 * 1024)+ # Reuse one session across every page so urllib3 keeps the connection alive. Redact the token+ # from logged URLs/samples, and never follow redirects - a valid `links.next` that 3xx-redirects+ # off-host would otherwise forward the bearer token to the redirect target.+ session = make_tracked_session(redact_values=(api_key,), allow_redirects=False)++ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None+ if resume is not None and resume.next_url:+ url = resume.next_url+ logger.debug(f"Vantage: resuming {endpoint} from URL: {url}")+ else:+ url = _build_initial_url(config)++ while True:+ data = _fetch_page(session, url, headers, logger)++ items = data.get(config.data_key, [])+ next_url = data.get("links", {}).get("next")++ for item in items:+ batcher.batch(item)++ if batcher.should_yield():+ yield batcher.get_table()+ # Save state AFTER yielding (and only when more pages remain) so a crash re-yields+ # the last page rather than skipping it - merge dedupes on the primary key.+ if next_url:+ resumable_source_manager.save_state(VantageResumeConfig(next_url=next_url))++ if not next_url:+ break+ url = next_url++ if batcher.should_yield(include_incomplete_chunk=True):+ yield batcher.get_table()+++def vantage_source(+ api_key: str,+ endpoint: str,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[VantageResumeConfig],+) -> SourceResponse:+ endpoint_config = VANTAGE_ENDPOINTS[endpoint]++ return SourceResponse(+ name=endpoint,+ items=lambda: get_rows(+ api_key=api_key,+ endpoint=endpoint,+ logger=logger,+ resumable_source_manager=resumable_source_manager,+ ),+ primary_keys=endpoint_config.primary_keys,+ 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,+ )