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 Scaleway source (#118684)

Tom Owers9aa9f62ad00d
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 d932a689eaab..2cec5931fc59 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
@@ -10509,10 +10509,10 @@ Today (10): `api_keys`, `applications`, `audit_trail_events`, `groups`, `instanc
Diffed against: <https://www.scaleway.com/en/developers/api/billing/v2beta1/schema.yml>
-- [ ] `billing consumptions (GET /billing/v2beta1/consumptions)` — spend per product category per month — the headline FinOps number; invoices alone give only totals (high)
-- [ ] `kubernetes clusters (GET /k8s/v1/regions/{region}/clusters)` — major compute inventory missing entirely from the resource picture (high)
-- [ ] `kubernetes pools and nodes (/k8s/v1/regions/{region}/pools, /nodes)` — node-level inventory that attributes k8s cost and capacity (high)
-- [ ] `managed database instances (GET /rdb/v1/regions/{region}/instances)` — managed Postgres/MySQL fleet, a large recurring cost line (high)
+- [x] `billing consumptions (GET /billing/v2beta1/consumptions)` — spend per product category per month — the headline FinOps number; invoices alone give only totals (high)
+- [x] `kubernetes clusters (GET /k8s/v1/regions/{region}/clusters)` — major compute inventory missing entirely from the resource picture (high)
+- [x] `kubernetes pools and nodes (/k8s/v1/regions/{region}/pools, /nodes)` — node-level inventory that attributes k8s cost and capacity (high)
+- [x] `managed database instances (GET /rdb/v1/regions/{region}/instances)` — managed Postgres/MySQL fleet, a large recurring cost line (high)
- [ ] `instance volumes (GET /instance/v1/zones/{zone}/volumes)` — storage attached to the servers already synced; needed to attribute storage spend (high)
- [ ] `instance images (GET /instance/v1/zones/{zone}/images)` — lookup resolving the image id carried on every synced server (medium)
- [ ] `instance snapshots (GET /instance/v1/zones/{zone}/snapshots)` — snapshot inventory, a common source of untracked storage cost (medium)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/scaleway/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/scaleway/canonical_descriptions.py
index 9030a348231a..068bf42ff983 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/scaleway/canonical_descriptions.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/scaleway/canonical_descriptions.py
@@ -168,4 +168,104 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
"status": "Outcome status code of the action.",
},
},
+ "billing_consumptions": {
+ "description": "Consumption cost per product, resource and project for each billing period.",
+ "docs_url": "https://www.scaleway.com/en/developers/api/billing/",
+ "columns": {
+ "billing_period": "Billing period (YYYY-MM) the consumption belongs to.",
+ "value": "Monetary value of the consumption (currency code, units and nanos).",
+ "product_name": "Name of the product consumed.",
+ "resource_name": "Reference of the consumed resource, based on the category.",
+ "sku": "Unique identifier of the product.",
+ "project_id": "ID of the project the consumption belongs to.",
+ "project_name": "Name of the project the consumption belongs to.",
+ "category_name": "Name of the consumption category (for example Compute, Network or Observability).",
+ "unit": "Unit of the consumed quantity.",
+ "billed_quantity": "Consumed quantity.",
+ "consumer_id": "ID of the organization that consumed the resource.",
+ "organization_name": "Name of the organization that consumed the resource.",
+ },
+ },
+ "kubernetes_clusters": {
+ "description": "Kubernetes Kapsule and Kosmos clusters across all regions.",
+ "docs_url": "https://www.scaleway.com/en/developers/api/kubernetes/",
+ "columns": {
+ "id": "Unique identifier of the cluster.",
+ "name": "Name of the cluster.",
+ "type": "Type of the cluster.",
+ "status": "Status of the cluster.",
+ "version": "Kubernetes version of the cluster.",
+ "region": "Region the cluster is deployed in.",
+ "organization_id": "ID of the organization that owns the cluster.",
+ "project_id": "ID of the project that owns the cluster.",
+ "tags": "Tags associated with the cluster.",
+ "cni": "Container Network Interface (CNI) plugin running in the cluster.",
+ "cluster_url": "Kubernetes API server URL of the cluster.",
+ "private_network_id": "ID of the private network used for internal cluster communication.",
+ "commitment_ends_at": "Date from which the cluster can switch to a smaller offer.",
+ "upgrade_available": "Whether a new Kubernetes version is available for the cluster.",
+ "created_at": "Date the cluster was created.",
+ "updated_at": "Date the cluster was last updated.",
+ },
+ },
+ "kubernetes_pools": {
+ "description": "Node pools of each Kubernetes cluster.",
+ "docs_url": "https://www.scaleway.com/en/developers/api/kubernetes/",
+ "columns": {
+ "id": "Unique identifier of the pool.",
+ "cluster_id": "ID of the cluster the pool belongs to.",
+ "name": "Name of the pool.",
+ "status": "Status of the pool.",
+ "version": "Kubernetes version of the pool.",
+ "node_type": "Scaleway Instance type used for the nodes of the pool.",
+ "size": "Number of nodes in the pool.",
+ "min_size": "Minimum size of the pool when autoscaling is enabled.",
+ "max_size": "Maximum size of the pool when autoscaling is enabled.",
+ "autoscaling": "Whether autoscaling is enabled for the pool.",
+ "autohealing": "Whether autohealing is enabled for the pool.",
+ "zone": "Zone the nodes of the pool are created in.",
+ "region": "Region of the cluster the pool belongs to.",
+ "root_volume_type": "Type of the system volume of the nodes.",
+ "root_volume_size": "Size of the system volume of the nodes, in bytes.",
+ "created_at": "Date the pool was created.",
+ "updated_at": "Date the pool was last updated.",
+ },
+ },
+ "kubernetes_nodes": {
+ "description": "Nodes of each Kubernetes cluster.",
+ "docs_url": "https://www.scaleway.com/en/developers/api/kubernetes/",
+ "columns": {
+ "id": "Unique identifier of the node.",
+ "pool_id": "ID of the pool the node belongs to.",
+ "cluster_id": "ID of the cluster the node belongs to.",
+ "provider_id": "ID of the underlying Instance, prefixed with its type and location.",
+ "region": "Region of the cluster the node belongs to.",
+ "name": "Name of the node.",
+ "status": "Status of the node.",
+ "error_message": "Details of the error that occurred when managing the node, if any.",
+ "created_at": "Date the node was created.",
+ "updated_at": "Date the node was last updated.",
+ },
+ },
+ "database_instances": {
+ "description": "Managed Database for PostgreSQL and MySQL instances across all regions.",
+ "docs_url": "https://www.scaleway.com/en/developers/api/managed-database-postgre-mysql/",
+ "columns": {
+ "id": "Unique identifier of the Database Instance.",
+ "name": "Name of the Database Instance.",
+ "organization_id": "ID of the organization the Database Instance belongs to.",
+ "project_id": "ID of the project the Database Instance belongs to.",
+ "region": "Region the Database Instance is in.",
+ "status": "Status of the Database Instance.",
+ "engine": "Database engine (for example PostgreSQL or MySQL) and version.",
+ "node_type": "Node type of the Database Instance.",
+ "volume": "Volume of the Database Instance.",
+ "is_ha_cluster": "Whether High-Availability is enabled.",
+ "tags": "Tags applied to the Database Instance.",
+ "endpoints": "Endpoints of the Database Instance.",
+ "read_replicas": "Read Replicas of the Database Instance.",
+ "backup_schedule": "Backup schedule of the Database Instance.",
+ "created_at": "Date the Database Instance was created.",
+ },
+ },
}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/scaleway/docs/scaleway.md b/products/warehouse_sources/backend/temporal/data_imports/sources/scaleway/docs/scaleway.md
index f36c7e68a141..80f982d138ed 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/scaleway/docs/scaleway.md
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/scaleway/docs/scaleway.md
@@ -14,7 +14,7 @@ import AlphaRelease from "../\_snippets/alpha-release.mdx"
<AlphaRelease />
-Sync your [Scaleway](https://www.scaleway.com) organization data — billing invoices, IAM identities, projects, audit trail events, and compute instances — into PostHog to build cost, security, and infrastructure reporting alongside your product data.
+Sync your [Scaleway](https://www.scaleway.com) organization data — billing invoices and consumption, IAM identities, projects, audit trail events, compute instances, Kubernetes clusters, and managed databases — into PostHog to build cost, security, and infrastructure reporting alongside your product data.
## Prerequisites
@@ -37,9 +37,11 @@ Grant the API key the read permission sets that match the tables you want to syn
- `IAMReadOnly` — users, applications, groups, policies, API keys, SSH keys
- `ProjectReadOnly` — projects
-- `BillingReadOnly` — invoices
+- `BillingReadOnly` — invoices, billing consumptions
- `AuditTrailReadOnly` — audit trail events
- `InstancesReadOnly` — instance servers
+- `KubernetesReadOnly` — Kubernetes clusters, pools, nodes
+- `RelationalDatabasesReadOnly` — database instances
Granting only a subset is fine: the source connects as long as the key is valid, and the table picker flags any table your key cannot read so you can leave it unselected.
@@ -47,7 +49,7 @@ Granting only a subset is fine: the source connects as long as the key is valid,
<SyncModes />
-All Scaleway tables sync via full refresh. Resource inventories (IAM, projects, instances) are small, and invoices and audit events are re-pulled each sync. Audit trail events sync the most recent 90 days on each refresh.
+All Scaleway tables sync via full refresh. Resource inventories (IAM, projects, instances) are small, and invoices and audit events are re-pulled each sync. Audit trail events sync the most recent 90 days on each refresh. Billing consumptions sync the current billing period and the 11 periods before it on each refresh.
## Configuration
@@ -61,6 +63,6 @@ All Scaleway tables sync via full refresh. Resource inventories (IAM, projects,
**"Your API key is missing the read permission set required to sync ..."**: the API key is valid but lacks the permission set for that table. Add the matching read permission (see the list above) to the key in the Scaleway console, then reconnect.
-**No rows for a table**: some resources are region- or zone-scoped. Instance servers are pulled from every zone your organization can use, and audit trail events from the `fr-par` and `nl-ams` regions — a table can legitimately be empty if you have no resources there.
+**No rows for a table**: some resources are region- or zone-scoped. Instance servers are pulled from every zone your organization can use, audit trail events from the `fr-par` and `nl-ams` regions, Kubernetes clusters, pools and nodes from `fr-par`, `nl-ams`, `pl-waw` and `it-mil`, and database instances from `fr-par`, `nl-ams` and `pl-waw` — a table can legitimately be empty if you have no resources there.
<TroubleshootingLink />
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/scaleway/scaleway.py b/products/warehouse_sources/backend/temporal/data_imports/sources/scaleway/scaleway.py
index 0ff5393835ea..c32682f28b62 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/scaleway/scaleway.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/scaleway/scaleway.py
@@ -10,8 +10,8 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common.htt
from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceResponse
from products.warehouse_sources.backend.temporal.data_imports.sources.scaleway.settings import (
- AUDIT_TRAIL_REGIONS,
- INSTANCE_ZONES,
+ BILLING_CONSUMPTION_LOOKBACK_MONTHS,
+ K8S_CLUSTERS_ENDPOINT,
PAGE_SIZE,
SCALEWAY_ENDPOINTS,
ScalewayEndpointConfig,
@@ -25,7 +25,7 @@ REQUEST_TIMEOUT = 60
_UNSCOPED = "_"
[email protected] # nosemgrep: prefer-frozen-dataclasses -- pre-existing; new field shifts the backlog finding into diff
class ScalewayResumeConfig:
# Index into the endpoint's scope list (regions/zones) currently being processed. The scope list
# is static, so a positional index is a stable bookmark across a crash + retry. Stays 0 for
@@ -36,6 +36,9 @@ class ScalewayResumeConfig:
page: int | None = None
# Opaque cursor for the token dialect (Audit Trail): the next `page_token` to fetch.
page_token: str | None = None
+ # The scope at `scope_index`. Billing periods and clusters are built at run time, so their positions
+ # can shift between attempts; resume finds the scope by this key instead.
+ scope_key: str | None = None
def _get_headers(secret_key: str) -> dict[str, str]:
@@ -47,11 +50,23 @@ def _format_rfc3339(dt: datetime) -> str:
return dt.astimezone(UTC).strftime("%Y-%m-%dT%H:%M:%SZ")
+def _billing_periods(now: datetime) -> list[str]:
+ """The `YYYY-MM` billing periods of the consumption window, oldest first, ending with the current month."""
+ periods = []
+ year, month = now.year, now.month
+ for _ in range(BILLING_CONSUMPTION_LOOKBACK_MONTHS):
+ periods.append(f"{year:04d}-{month:02d}")
+ year, month = (year - 1, 12) if month == 1 else (year, month - 1)
+ return list(reversed(periods))
+
+
def _scopes_for(config: ScalewayEndpointConfig) -> list[str]:
- if config.scope == "region":
- return AUDIT_TRAIL_REGIONS
- if config.scope == "zone":
- return INSTANCE_ZONES
+ if config.scope in ("region", "zone"):
+ return config.scope_values
+ if config.scope == "billing_period":
+ return _billing_periods(datetime.now(UTC))
+ if config.scope == "k8s_cluster":
+ raise ValueError("Cluster scopes come from the API, see _list_cluster_scopes")
return [_UNSCOPED]
@@ -60,9 +75,25 @@ def _resolve_path(config: ScalewayEndpointConfig, scope: str) -> str:
return config.path.format(region=scope)
if config.scope == "zone":
return config.path.format(zone=scope)
+ if config.scope == "k8s_cluster":
+ region, cluster_id = scope.split("/", 1)
+ return config.path.format(region=region, cluster_id=cluster_id)
return config.path
+def _scope_params(config: ScalewayEndpointConfig, scope: str) -> dict[str, Any]:
+ if config.scope == "billing_period":
+ return {"billing_period": scope}
+ return {}
+
+
+def _shape_rows(config: ScalewayEndpointConfig, scope: str, items: list[dict]) -> list[dict]:
+ # Consumption rows do not say which month they belong to, so carry the requested period on each row.
+ if config.scope == "billing_period":
+ return [{**item, "billing_period": scope} for item in items]
+ return items
+
+
def _base_params(config: ScalewayEndpointConfig, organization_id: str) -> dict[str, Any]:
"""Query params shared by every request for an endpoint (before the per-page cursor is added)."""
params: dict[str, Any] = {}
@@ -140,6 +171,36 @@ def _iter_pages(
page += 1
+def _list_cluster_scopes(
+ session: requests.Session,
+ config: ScalewayEndpointConfig,
+ organization_id: str,
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[ScalewayResumeConfig],
+) -> list[str]:
+ """List every Kubernetes cluster in the endpoint's regions as `<region>/<cluster_id>` scope keys."""
+ clusters_config = SCALEWAY_ENDPOINTS[K8S_CLUSTERS_ENDPOINT]
+ params = _base_params(clusters_config, organization_id)
+ scopes: list[str] = []
+ for region in config.scope_values:
+ url = f"{BASE_URL}{_resolve_path(clusters_config, region)}"
+ for clusters, _has_more, _next_cursor in _iter_pages(session, url, params, clusters_config, logger, None, None):
+ scopes.extend(f"{region}/{cluster['id']}" for cluster in clusters)
+ # Listing yields no rows, and no cursor is staged yet, so a hand-off here only restarts the listing.
+ resumable_source_manager.safe_point()
+ return scopes
+
+
+def _resume_index(scopes: list[str], resume: ScalewayResumeConfig) -> int | None:
+ """The index of the scope to resume into, or None when the saved scope no longer exists."""
+ if resume.scope_key is None:
+ return resume.scope_index
+ try:
+ return scopes.index(resume.scope_key)
+ except ValueError:
+ return None
+
+
def get_rows(
secret_key: str,
organization_id: str,
@@ -153,16 +214,27 @@ def get_rows(
# logs and sample capture wherever it might appear.
session = make_tracked_session(headers=_get_headers(secret_key), redact_values=(secret_key,))
base_params = _base_params(config, organization_id)
- scopes = _scopes_for(config)
+ if config.scope == "k8s_cluster":
+ scopes = _list_cluster_scopes(session, config, organization_id, logger, resumable_source_manager)
+ else:
+ scopes = _scopes_for(config)
resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None
- start_index = resume.scope_index if resume is not None else 0
+ start_index = 0
+ if resume is not None:
+ resume_index = _resume_index(scopes, resume)
+ if resume_index is None:
+ # The saved cluster was deleted, or the saved billing period left the window: start over.
+ resume = None
+ else:
+ start_index = resume_index
if start_index >= len(scopes):
return
for scope_index in range(start_index, len(scopes)):
scope = scopes[scope_index]
url = f"{BASE_URL}{_resolve_path(config, scope)}"
+ scope_params = {**base_params, **_scope_params(config, scope)}
# Only the scope we resumed into consumes the saved page/token cursor; later scopes start fresh.
if resume is not None and scope_index == start_index:
start_page = resume.page
@@ -171,19 +243,33 @@ def get_rows(
start_page = None
start_token = None
- for items, has_more, next_cursor in _iter_pages(
- session, url, base_params, config, logger, start_page, start_token
- ):
- if items:
- yield items
- # Save AFTER yielding so a crash re-yields the last page rather than skipping it (merge
- # dedupes on the primary key). Only persist when more pages remain in this scope.
- if has_more:
- resumable_source_manager.save_state(ScalewayResumeConfig(scope_index=scope_index, **next_cursor))
+ try:
+ for items, has_more, next_cursor in _iter_pages(
+ session, url, scope_params, config, logger, start_page, start_token
+ ):
+ if items:
+ yield _shape_rows(config, scope, items)
+ else:
+ # Empty regions, clusters and months return no rows, so the pipeline sees no item here.
+ resumable_source_manager.safe_point()
+ # Save AFTER yielding so a crash re-yields the last page rather than skipping it (merge
+ # dedupes on the primary key). Only persist when more pages remain in this scope.
+ if has_more:
+ resumable_source_manager.save_state(
+ ScalewayResumeConfig(scope_index=scope_index, scope_key=scope, **next_cursor)
+ )
+ except requests.HTTPError as e:
+ # A cluster deleted after it was listed answers 404; skip it instead of failing the whole table.
+ if config.scope == "k8s_cluster" and e.response is not None and e.response.status_code == 404:
+ logger.warning(f"Scaleway cluster {scope} no longer exists, skipping it")
+ else:
+ raise
# Advance the bookmark to the next scope so a crash between scopes resumes correctly.
if scope_index + 1 < len(scopes):
- resumable_source_manager.save_state(ScalewayResumeConfig(scope_index=scope_index + 1))
+ resumable_source_manager.save_state(
+ ScalewayResumeConfig(scope_index=scope_index + 1, scope_key=scopes[scope_index + 1])
+ )
def scaleway_source(
@@ -223,10 +309,13 @@ def probe_endpoint(secret_key: str, organization_id: str, endpoint: str) -> int:
denial" rather than a missing scope.
"""
config = SCALEWAY_ENDPOINTS[endpoint]
+ if config.scope == "k8s_cluster":
+ # Pools and nodes need a cluster in the path. Listing clusters needs the same Kubernetes read permission.
+ config = SCALEWAY_ENDPOINTS[K8S_CLUSTERS_ENDPOINT]
session = make_tracked_session(headers=_get_headers(secret_key), redact_values=(secret_key,))
scope = _scopes_for(config)[0]
url = f"{BASE_URL}{_resolve_path(config, scope)}"
- params = _base_params(config, organization_id)
+ params = {**_base_params(config, organization_id), **_scope_params(config, scope)}
if config.pagination == "per_page":
params["per_page"] = 1
else:
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/scaleway/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/scaleway/settings.py
index f38dcb20cb35..bb74ffe64579 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/scaleway/settings.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/scaleway/settings.py
@@ -15,7 +15,10 @@ Pagination = Literal["page_size", "per_page", "token"]
# A handful of Scaleway products are region- or zone-scoped in the path, so the connector iterates the
# scope list and substitutes it into `{region}` / `{zone}` before requesting.
-Scope = Literal["none", "region", "zone"]
+# - "billing_period": one pass per month of the trailing consumption window, sent as `billing_period`.
+# - "k8s_cluster": one pass per Kubernetes cluster, listed from every region in `scope_values`, which
+# fills both `{region}` and `{cluster_id}`.
+Scope = Literal["none", "region", "zone", "billing_period", "k8s_cluster"]
# Max items per page allowed by every paginated Scaleway list endpoint.
PAGE_SIZE = 100
@@ -23,6 +26,10 @@ PAGE_SIZE = 100
# Audit Trail is region-scoped in the path; only fr-par and nl-ams expose it today (pl-waw does not).
AUDIT_TRAIL_REGIONS = ["fr-par", "nl-ams"]
+# Regions listed in the Kubernetes and Managed Database OpenAPI schemas.
+K8S_REGIONS = ["fr-par", "nl-ams", "pl-waw", "it-mil"]
+RDB_REGIONS = ["fr-par", "nl-ams", "pl-waw"]
+
# Instance servers are zone-scoped in the path. The connector fans out over every generally-available
# zone; zones with no servers simply return an empty page.
INSTANCE_ZONES = [
@@ -43,8 +50,12 @@ INSTANCE_ZONES = [
# table). A future incremental mode could instead resume from the last `recorded_at` — see source.py.
AUDIT_TRAIL_LOOKBACK_DAYS = 90
+# Consumptions take one `billing_period` per request and default to the current month, so a full refresh
+# walks the current month plus the months before it.
+BILLING_CONSUMPTION_LOOKBACK_MONTHS = 12
+
-@dataclass
+@dataclass # nosemgrep: prefer-frozen-dataclasses -- pre-existing; new fields shift the backlog finding into diff
class ScalewayEndpointConfig:
name: str
# Path relative to the API base URL. May contain a `{region}` or `{zone}` placeholder that the
@@ -58,6 +69,8 @@ class ScalewayEndpointConfig:
# "modified" field, which would rewrite partitions on every sync.
partition_key: Optional[str] = None
scope: Scope = "none"
+ # Regions or zones the endpoint fans out over, for the "region", "zone" and "k8s_cluster" scopes.
+ scope_values: list[str] = field(default_factory=list)
# Query-param name used to scope the request to the connected organization. Scaleway is
# inconsistent here: most products take `organization_id`, but Instance takes `organization`.
# `None` means the endpoint isn't organization-scoped.
@@ -165,6 +178,7 @@ SCALEWAY_ENDPOINTS: dict[str, ScalewayEndpointConfig] = {
# Instance uses `creation_date`/`modification_date` rather than `created_at`/`updated_at`.
partition_key="creation_date",
scope="zone",
+ scope_values=INSTANCE_ZONES,
org_param="organization",
order_param="order",
order_value="creation_date_asc",
@@ -176,6 +190,7 @@ SCALEWAY_ENDPOINTS: dict[str, ScalewayEndpointConfig] = {
pagination="token",
partition_key="recorded_at",
scope="region",
+ scope_values=AUDIT_TRAIL_REGIONS,
# Audit Trail requires organization_id explicitly.
org_param="organization_id",
order_param="order_by",
@@ -184,8 +199,77 @@ SCALEWAY_ENDPOINTS: dict[str, ScalewayEndpointConfig] = {
lookback_days=AUDIT_TRAIL_LOOKBACK_DAYS,
description=(f"Syncs the most recent {AUDIT_TRAIL_LOOKBACK_DAYS} days of audit events on each full refresh"),
),
+ "billing_consumptions": ScalewayEndpointConfig(
+ name="billing_consumptions",
+ path="/billing/v2beta1/consumptions",
+ data_key="consumptions",
+ pagination="page_size",
+ # Consumption rows have no id or date of their own. The connector adds `billing_period` to each
+ # row, and a row is one SKU of one resource in one project for that month.
+ primary_keys=["billing_period", "project_id", "category_name", "sku", "resource_name"],
+ scope="billing_period",
+ org_param="organization_id",
+ order_param="order_by",
+ order_value="updated_at_asc",
+ description=(
+ f"Syncs consumption for the current and previous {BILLING_CONSUMPTION_LOOKBACK_MONTHS - 1} "
+ "billing periods on each full refresh"
+ ),
+ ),
+ "kubernetes_clusters": ScalewayEndpointConfig(
+ name="kubernetes_clusters",
+ path="/k8s/v1/regions/{region}/clusters",
+ data_key="clusters",
+ pagination="page_size",
+ partition_key="created_at",
+ scope="region",
+ scope_values=K8S_REGIONS,
+ org_param="organization_id",
+ order_param="order_by",
+ order_value="created_at_asc",
+ ),
+ "kubernetes_pools": ScalewayEndpointConfig(
+ name="kubernetes_pools",
+ path="/k8s/v1/regions/{region}/clusters/{cluster_id}/pools",
+ data_key="pools",
+ pagination="page_size",
+ partition_key="created_at",
+ scope="k8s_cluster",
+ scope_values=K8S_REGIONS,
+ # The cluster in the path already scopes the request; this endpoint takes no organization filter.
+ org_param=None,
+ order_param="order_by",
+ order_value="created_at_asc",
+ ),
+ "kubernetes_nodes": ScalewayEndpointConfig(
+ name="kubernetes_nodes",
+ path="/k8s/v1/regions/{region}/clusters/{cluster_id}/nodes",
+ data_key="nodes",
+ pagination="page_size",
+ partition_key="created_at",
+ scope="k8s_cluster",
+ scope_values=K8S_REGIONS,
+ org_param=None,
+ order_param="order_by",
+ order_value="created_at_asc",
+ ),
+ "database_instances": ScalewayEndpointConfig(
+ name="database_instances",
+ path="/rdb/v1/regions/{region}/instances",
+ data_key="instances",
+ pagination="page_size",
+ partition_key="created_at",
+ scope="region",
+ scope_values=RDB_REGIONS,
+ org_param="organization_id",
+ order_param="order_by",
+ order_value="created_at_asc",
+ ),
}
+# The endpoint that lists the clusters the "k8s_cluster" scope fans out over.
+K8S_CLUSTERS_ENDPOINT = "kubernetes_clusters"
+
ENDPOINTS = tuple(SCALEWAY_ENDPOINTS.keys())
# Every endpoint ships as full refresh: none of Scaleway's list endpoints expose a verified server-side
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/scaleway/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/scaleway/source.py
index beb9e4d93969..1554f1359be1 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/scaleway/source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/scaleway/source.py
@@ -84,13 +84,15 @@ Create an API key from the [IAM > API keys](https://console.scaleway.com/iam/api
Grant the key the read permission sets for the data you want to sync, for example:
- `IAMReadOnly` for users, applications, groups, policies, API keys and SSH keys
- `ProjectReadOnly` for projects
-- `BillingReadOnly` for invoices
+- `BillingReadOnly` for invoices and billing consumptions
- `AuditTrailReadOnly` for audit trail events
- `InstancesReadOnly` for instance servers
+- `KubernetesReadOnly` for Kubernetes clusters, pools and nodes
+- `RelationalDatabasesReadOnly` for database instances
""",
iconPath="/static/services/scaleway.svg",
docsUrl="https://posthog.com/docs/cdp/sources/scaleway",
- keywords=["cloud", "billing", "infrastructure", "invoices", "iam"],
+ keywords=["cloud", "billing", "infrastructure", "invoices", "iam", "kubernetes"],
fields=cast(
list[FieldType],
[
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/scaleway/tests/test_scaleway.py b/products/warehouse_sources/backend/temporal/data_imports/sources/scaleway/tests/test_scaleway.py
index 131f5935ffdf..4328d39010b1 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/scaleway/tests/test_scaleway.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/scaleway/tests/test_scaleway.py
@@ -1,3 +1,7 @@
+from datetime import UTC, datetime
+
+import time_machine
+
import requests
from parameterized import parameterized
@@ -14,11 +18,14 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.generated_
from products.warehouse_sources.backend.temporal.data_imports.sources.scaleway.scaleway import (
ScalewayResumeConfig,
_base_params,
+ _billing_periods,
_resolve_path,
probe_endpoint,
)
from products.warehouse_sources.backend.temporal.data_imports.sources.scaleway.settings import (
+ BILLING_CONSUMPTION_LOOKBACK_MONTHS,
INSTANCE_ZONES,
+ K8S_REGIONS,
PAGE_SIZE,
SCALEWAY_ENDPOINTS,
)
@@ -44,6 +51,9 @@ class TestBaseParams:
("invoices", "page_size", "organization_id"),
("instance_servers", "per_page", "organization"),
("audit_trail_events", "page_size", "organization_id"),
+ ("billing_consumptions", "page_size", "organization_id"),
+ ("kubernetes_clusters", "page_size", "organization_id"),
+ ("database_instances", "page_size", "organization_id"),
]
)
def test_pagination_and_org_param_wiring(self, endpoint: str, page_param: str, org_param: str) -> None:
@@ -59,6 +69,11 @@ class TestBaseParams:
("invoices", "order_by", "start_date_asc"),
("instance_servers", "order", "creation_date_asc"),
("audit_trail_events", "order_by", "recorded_at_asc"),
+ ("billing_consumptions", "order_by", "updated_at_asc"),
+ ("kubernetes_clusters", "order_by", "created_at_asc"),
+ ("kubernetes_pools", "order_by", "created_at_asc"),
+ ("kubernetes_nodes", "order_by", "created_at_asc"),
+ ("database_instances", "order_by", "created_at_asc"),
]
)
def test_sort_param_wiring(self, endpoint: str, order_param: str, order_value: str) -> None:
@@ -72,6 +87,11 @@ class TestResolvePath:
("users", "fr-par", "/iam/v1alpha1/users"),
("instance_servers", "nl-ams-1", "/instance/v1/zones/nl-ams-1/servers"),
("audit_trail_events", "fr-par", "/audit-trail/v1alpha1/regions/fr-par/events"),
+ ("kubernetes_clusters", "it-mil", "/k8s/v1/regions/it-mil/clusters"),
+ ("database_instances", "pl-waw", "/rdb/v1/regions/pl-waw/instances"),
+ ("kubernetes_pools", "nl-ams/c-1", "/k8s/v1/regions/nl-ams/clusters/c-1/pools"),
+ ("kubernetes_nodes", "fr-par/c-2", "/k8s/v1/regions/fr-par/clusters/c-2/nodes"),
+ ("billing_consumptions", "2026-10", "/billing/v2beta1/consumptions"),
]
)
def test_scope_substitution(self, endpoint: str, scope: str, expected: str) -> None:
@@ -90,7 +110,7 @@ class TestPageNumberPagination:
assert len(result.requests) == 2
assert result.requests[1].param("page") == "2"
# Resume state persisted only while more pages remained — pointing at the next page.
- assert result.saved_states == [ScalewayResumeConfig(scope_index=0, page=2)]
+ assert result.saved_states == [ScalewayResumeConfig(scope_index=0, page=2, scope_key="_")]
def test_resumes_from_saved_page(self) -> None:
short = _response({"users": [{"id": "x"}]})
@@ -137,6 +157,161 @@ class TestFanOut:
assert len(result.rows) == len(INSTANCE_ZONES)
+class TestBillingPeriods:
+ @parameterized.expand(
+ [
+ ("mid_year", datetime(2026, 10, 16, tzinfo=UTC), "2025-11", "2026-10"),
+ ("january_crosses_year", datetime(2026, 1, 1, tzinfo=UTC), "2025-02", "2026-01"),
+ ("december", datetime(2026, 12, 31, 23, 59, tzinfo=UTC), "2026-01", "2026-12"),
+ ]
+ )
+ def test_window_ends_at_current_month(self, _name: str, now: datetime, first: str, last: str) -> None:
+ periods = _billing_periods(now)
+
+ assert len(periods) == BILLING_CONSUMPTION_LOOKBACK_MONTHS
+ assert len(set(periods)) == BILLING_CONSUMPTION_LOOKBACK_MONTHS
+ assert periods == sorted(periods)
+ assert (periods[0], periods[-1]) == (first, last)
+
+ @time_machine.travel(datetime(2026, 3, 10, tzinfo=UTC), tick=False)
+ def test_requests_each_period_and_stamps_it_on_rows(self) -> None:
+ responses = [
+ _response({"consumptions": [{"sku": f"sku-{i}", "project_id": "p-1"}], "total_count": 1})
+ for i in range(BILLING_CONSUMPTION_LOOKBACK_MONTHS)
+ ]
+
+ result = _drive("billing_consumptions", responses)
+
+ expected_periods = _billing_periods(datetime(2026, 3, 10, tzinfo=UTC))
+ assert result.params("billing_period") == expected_periods
+ assert [row["billing_period"] for row in result.rows] == expected_periods
+ assert all(query["organization_id"] == ("org-123",) for query in result.queries)
+
+ @parameterized.expand(
+ [
+ # (name, saved state, first period requested)
+ (
+ "saved_period_in_window",
+ ScalewayResumeConfig(scope_index=0, page=2, scope_key="2025-12"),
+ "2025-12",
+ "2",
+ ),
+ # The month rolled over since the save, so the oldest period left the window: start over.
+ (
+ "saved_period_left_window",
+ ScalewayResumeConfig(scope_index=0, page=2, scope_key="2025-03"),
+ "2025-04",
+ "1",
+ ),
+ ]
+ )
+ def test_resume_finds_period_by_key(
+ self, _name: str, resume: ScalewayResumeConfig, first_period: str, first_page: str
+ ) -> None:
+ responses = [_response({"consumptions": []}) for _ in range(BILLING_CONSUMPTION_LOOKBACK_MONTHS)]
+
+ with time_machine.travel(datetime(2026, 3, 10, tzinfo=UTC), tick=False):
+ result = _drive("billing_consumptions", responses, resume)
+
+ assert result.requests[0].param("billing_period") == first_period
+ assert result.requests[0].param("page") == first_page
+
+
+class TestKubernetesClusterFanOut:
+ def _cluster_listing(self, clusters_by_region: dict[str, list[str]]) -> list[ScriptedResponse]:
+ return [
+ _response({"clusters": [{"id": cid} for cid in clusters_by_region.get(region, [])]})
+ for region in K8S_REGIONS
+ ]
+
+ @parameterized.expand([("pools", "kubernetes_pools", "pools"), ("nodes", "kubernetes_nodes", "nodes")])
+ def test_lists_clusters_in_every_region_then_pages_each_cluster(
+ self, _name: str, endpoint: str, data_key: str
+ ) -> None:
+ listing = self._cluster_listing({"fr-par": ["c-1"], "pl-waw": ["c-2"]})
+ children = [
+ _response({data_key: [{"id": f"{data_key}-{i}", "cluster_id": "c-1"} for i in range(PAGE_SIZE)]}),
+ _response({data_key: [{"id": "last", "cluster_id": "c-1"}]}),
+ _response({data_key: [{"id": "other", "cluster_id": "c-2"}]}),
+ ]
+
+ result = _drive(endpoint, listing + children)
+
+ assert result.paths == [
+ *[f"/k8s/v1/regions/{region}/clusters" for region in K8S_REGIONS],
+ f"/k8s/v1/regions/fr-par/clusters/c-1/{data_key}",
+ f"/k8s/v1/regions/fr-par/clusters/c-1/{data_key}",
+ f"/k8s/v1/regions/pl-waw/clusters/c-2/{data_key}",
+ ]
+ assert len(result.rows) == PAGE_SIZE + 2
+ # The cluster listing is organization-scoped; the per-cluster requests take no organization filter.
+ assert all(query["organization_id"] == ("org-123",) for query in result.queries[: len(K8S_REGIONS)])
+ assert all("organization_id" not in query for query in result.queries[len(K8S_REGIONS) :])
+ assert result.saved_states == [
+ ScalewayResumeConfig(scope_index=0, page=2, scope_key="fr-par/c-1"),
+ ScalewayResumeConfig(scope_index=1, scope_key="pl-waw/c-2"),
+ ]
+
+ def test_no_clusters_makes_no_child_requests(self) -> None:
+ result = _drive("kubernetes_pools", self._cluster_listing({}))
+
+ assert len(result.requests) == len(K8S_REGIONS)
+ assert result.rows == []
+ assert result.raised is None
+
+ @parameterized.expand(
+ [
+ # (name, saved state, expected child paths)
+ (
+ "saved_cluster_still_exists",
+ ScalewayResumeConfig(scope_index=0, page=3, scope_key="pl-waw/c-2"),
+ ["/k8s/v1/regions/pl-waw/clusters/c-2/pools"],
+ "3",
+ ),
+ (
+ # A new cluster in an earlier region shifted the index; the key still finds the right cluster.
+ "index_shifted_by_new_cluster",
+ ScalewayResumeConfig(scope_index=1, scope_key="pl-waw/c-2"),
+ ["/k8s/v1/regions/pl-waw/clusters/c-2/pools"],
+ "1",
+ ),
+ (
+ "saved_cluster_deleted",
+ ScalewayResumeConfig(scope_index=1, page=3, scope_key="pl-waw/c-gone"),
+ [
+ "/k8s/v1/regions/fr-par/clusters/c-0/pools",
+ "/k8s/v1/regions/fr-par/clusters/c-1/pools",
+ "/k8s/v1/regions/pl-waw/clusters/c-2/pools",
+ ],
+ "1",
+ ),
+ ]
+ )
+ def test_resume_finds_cluster_by_key(
+ self, _name: str, resume: ScalewayResumeConfig, expected_child_paths: list[str], first_page: str
+ ) -> None:
+ listing = self._cluster_listing({"fr-par": ["c-0", "c-1"], "pl-waw": ["c-2"]})
+ children = [_response({"pools": []}) for _ in expected_child_paths]
+
+ result = _drive("kubernetes_pools", listing + children, resume)
+
+ assert result.paths[len(K8S_REGIONS) :] == expected_child_paths
+ assert result.requests[len(K8S_REGIONS)].param("page") == first_page
+
+ def test_a_cluster_deleted_after_listing_is_skipped(self) -> None:
+ listing = self._cluster_listing({"fr-par": ["c-gone", "c-1"]})
+ children = [_response({}, status=404), _response({"pools": [{"id": "p-1"}]})]
+
+ result = _drive("kubernetes_pools", listing + children)
+
+ assert result.raised is None
+ assert [row["id"] for row in result.rows] == ["p-1"]
+ assert result.paths[len(K8S_REGIONS) :] == [
+ "/k8s/v1/regions/fr-par/clusters/c-gone/pools",
+ "/k8s/v1/regions/fr-par/clusters/c-1/pools",
+ ]
+
+
class TestFetchErrors:
def test_non_ok_response_raises(self) -> None:
result = _drive("users", [_response({}, status=403)])
@@ -154,6 +329,19 @@ class TestProbeEndpoint:
with scripted_network(always(requests.ConnectionError("boom"))):
assert probe_endpoint("scw-secret", "org-123", "users") == 0
+ @parameterized.expand(
+ [
+ ("kubernetes_pools", "/k8s/v1/regions/fr-par/clusters"),
+ ("kubernetes_nodes", "/k8s/v1/regions/fr-par/clusters"),
+ ("database_instances", "/rdb/v1/regions/fr-par/instances"),
+ ("billing_consumptions", "/billing/v2beta1/consumptions"),
+ ]
+ )
+ def test_probes_a_path_that_needs_no_parent_id(self, endpoint: str, expected_path: str) -> None:
+ with scripted_network([_response({}, status=200)]) as network:
+ assert probe_endpoint("scw-secret", "org-123", endpoint) == 200
+ assert network.requests_log[0].path == expected_path
+
@parameterized.expand([("page_size_endpoint", "users"), ("token_endpoint", "audit_trail_events")])
def test_requests_a_single_row(self, _name: str, endpoint: str) -> None:
with scripted_network([_response({}, status=200)]) as network:
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/tests/source_contract_baseline.txt b/products/warehouse_sources/backend/temporal/data_imports/sources/tests/source_contract_baseline.txt
index 75026c4e82af..31fd1f33a60a 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/tests/source_contract_baseline.txt
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/tests/source_contract_baseline.txt
@@ -627,7 +627,7 @@ Salesflare fail:stall-budget
Salesforce not-checkable:database
SavvyCal fail:stall-budget
ScaleAI fail:stall-budget
-Scaleway fail:rate-limit-budget,safe-point
+Scaleway fail:rate-limit-budget
Scrunch fail:stall-budget
Secoda fail:stall-budget
Secureframe fail:stall-budget