: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 scaleway import source (#70046)
Tom Owers3c3f5bcd7384
diff --git a/frontend/public/services/scaleway.svg b/frontend/public/services/scaleway.svgnew file mode 100644index 000000000000..78ee477f3024--- /dev/null+++ b/frontend/public/services/scaleway.svg@@ -0,0 +1,4 @@+<svg xmlns="http://www.w3.org/2000/svg" width="64" height="64" viewBox="0 0 64 64" role="img" aria-label="Scaleway">+ <rect width="64" height="64" rx="14" fill="#4F0599" />+ <path d="M40.5 22.5c-2.2-1.6-5-2.5-8.2-2.5-6.6 0-11.3 3.7-11.3 9 0 5 3.6 7.2 9.6 8.4 4.4.9 5.6 1.6 5.6 3.2 0 1.6-1.6 2.6-4.4 2.6-3 0-5.6-1-7.8-2.8l-3 4.8c2.7 2.2 6.4 3.4 10.6 3.4 6.9 0 11.4-3.6 11.4-9.1 0-5.1-3.7-7.1-9.8-8.4-4.2-.9-5.4-1.5-5.4-3.1 0-1.4 1.4-2.4 4-2.4 2.6 0 5 .8 7 2.3l2.9-4.4z" fill="#fff" />+</svg>diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.mdindex 03bd0327952e..3809259351c7 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md@@ -338,6 +338,7 @@ the row lists both.| salesflare | HTTP | requests | ✅ || salesloft | HTTP | requests | ✅ || savvycal | HTTP | requests | ✅ |+| scaleway | HTTP | requests | ✅ || secoda | HTTP | requests | ✅ || segment | HTTP | requests | ✅ || sendgrid | HTTP | requests | ✅ |@@ -755,7 +756,6 @@ doesn't conflict with concurrent PRs.- sap_successfactors- savvycal- scale_ai-- scaleway- search_ads_360- sendpulse- senseforcediff --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 55ceb8f10df8..777bdf9d4ed2 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@@ -3286,7 +3286,8 @@ class ScaleAISourceConfig(config.Config):@config.configclass ScalewaySourceConfig(config.Config):- pass+ secret_key: str+ organization_id: str@config.configdiff --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.pynew file mode 100644index 000000000000..9030a348231a--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/scaleway/canonical_descriptions.py@@ -0,0 +1,171 @@+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (+ CanonicalDescriptions,+)++# Descriptions are taken from Scaleway's official OpenAPI schemas+# (https://www.scaleway.com/en/developers/api/). Partial coverage is fine: any column or table not+# listed here falls back to LLM enrichment using the docs_url below.+CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {+ "users": {+ "description": "IAM users belonging to the organization.",+ "docs_url": "https://www.scaleway.com/en/developers/api/iam/",+ "columns": {+ "id": "Unique identifier of the user.",+ "organization_id": "ID of the organization the user belongs to.",+ "email": "Email address of the user.",+ "username": "Username of the user.",+ "type": "Type of user (guest or owner).",+ "status": "Status of user invitation (invitation_pending or activated).",+ "mfa": "Whether multi-factor authentication is enabled for the user.",+ "last_login_at": "Date of the user's last login.",+ "created_at": "Date the user was created.",+ "updated_at": "Date the user was last updated.",+ },+ },+ "applications": {+ "description": "IAM applications (non-human identities used for automation).",+ "docs_url": "https://www.scaleway.com/en/developers/api/iam/",+ "columns": {+ "id": "Unique identifier of the application.",+ "name": "Name of the application.",+ "description": "Description of the application.",+ "organization_id": "ID of the organization the application belongs to.",+ "editable": "Whether the application can be edited.",+ "nb_api_keys": "Number of API keys attached to the application.",+ "created_at": "Date the application was created.",+ "updated_at": "Date the application was last updated.",+ },+ },+ "groups": {+ "description": "IAM groups that bundle users and applications for shared policy assignment.",+ "docs_url": "https://www.scaleway.com/en/developers/api/iam/",+ "columns": {+ "id": "Unique identifier of the group.",+ "name": "Name of the group.",+ "description": "Description of the group.",+ "organization_id": "ID of the organization the group belongs to.",+ "user_ids": "IDs of the users in the group.",+ "application_ids": "IDs of the applications in the group.",+ "created_at": "Date the group was created.",+ "updated_at": "Date the group was last updated.",+ },+ },+ "policies": {+ "description": "IAM policies that grant permission sets to a principal (user, group or application).",+ "docs_url": "https://www.scaleway.com/en/developers/api/iam/",+ "columns": {+ "id": "Unique identifier of the policy.",+ "name": "Name of the policy.",+ "description": "Description of the policy.",+ "organization_id": "ID of the organization the policy belongs to.",+ "user_id": "ID of the user the policy is assigned to, if any.",+ "group_id": "ID of the group the policy is assigned to, if any.",+ "application_id": "ID of the application the policy is assigned to, if any.",+ "no_principal": "Whether the policy is not attached to any principal.",+ "editable": "Whether the policy can be edited.",+ "created_at": "Date the policy was created.",+ "updated_at": "Date the policy was last updated.",+ },+ },+ "api_keys": {+ "description": "IAM API keys used to authenticate against the Scaleway API.",+ "docs_url": "https://www.scaleway.com/en/developers/api/iam/",+ "columns": {+ "access_key": "Access key of the API key (its unique identifier).",+ "description": "Description of the API key.",+ "application_id": "ID of the application the key is bound to, if any.",+ "user_id": "ID of the user the key is bound to, if any.",+ "expires_at": "Expiration date of the API key, if set.",+ "default_project_id": "Default project ID used by the API key.",+ "editable": "Whether the API key can be edited.",+ "creation_ip": "IP address the API key was created from.",+ "created_at": "Date the API key was created.",+ "updated_at": "Date the API key was last updated.",+ },+ },+ "ssh_keys": {+ "description": "SSH public keys registered in the organization.",+ "docs_url": "https://www.scaleway.com/en/developers/api/iam/",+ "columns": {+ "id": "Unique identifier of the SSH key.",+ "name": "Name of the SSH key.",+ "public_key": "The SSH public key material.",+ "fingerprint": "Fingerprint of the SSH key.",+ "organization_id": "ID of the organization the SSH key belongs to.",+ "project_id": "ID of the project the SSH key belongs to.",+ "disabled": "Whether the SSH key is disabled.",+ "created_at": "Date the SSH key was created.",+ "updated_at": "Date the SSH key was last updated.",+ },+ },+ "projects": {+ "description": "Projects that group and isolate Scaleway resources within the organization.",+ "docs_url": "https://www.scaleway.com/en/developers/api/account/project/",+ "columns": {+ "id": "Unique identifier of the project.",+ "name": "Name of the project.",+ "description": "Description of the project.",+ "organization_id": "ID of the organization the project belongs to.",+ "created_at": "Date the project was created.",+ "updated_at": "Date the project was last updated.",+ },+ },+ "invoices": {+ "description": "Billing invoices for the organization.",+ "docs_url": "https://www.scaleway.com/en/developers/api/billing/",+ "columns": {+ "id": "Unique identifier of the invoice.",+ "organization_id": "ID of the organization the invoice belongs to.",+ "organization_name": "Name of the billed organization.",+ "invoice_type": "Type of invoice (periodic, purchase or credit_note).",+ "number": "Invoice number.",+ "state": "State of the invoice.",+ "start_date": "Start date of the billing period covered by the invoice.",+ "stop_date": "End date of the billing period covered by the invoice.",+ "issued_date": "Date the invoice was issued.",+ "due_date": "Date the invoice is due.",+ "total_untaxed": "Total amount before tax.",+ "total_taxed": "Total amount including tax.",+ "total_tax": "Total tax amount.",+ "total_discount": "Total discount applied.",+ "seller_name": "Name of the Scaleway selling entity.",+ },+ },+ "instance_servers": {+ "description": "Compute instances across all zones the organization operates in.",+ "docs_url": "https://www.scaleway.com/en/developers/api/instance/",+ "columns": {+ "id": "Unique identifier of the server.",+ "name": "Name of the server.",+ "organization": "ID of the organization the server belongs to.",+ "project": "ID of the project the server belongs to.",+ "commercial_type": "Commercial offer type of the server (e.g. DEV1-S).",+ "state": "Current state of the server (running, stopped, etc.).",+ "zone": "Availability zone the server is hosted in.",+ "hostname": "Hostname of the server.",+ "tags": "Tags associated with the server.",+ "image": "Image the server was created from.",+ "arch": "CPU architecture of the server.",+ "boot_type": "Boot type of the server.",+ "creation_date": "Date the server was created.",+ "modification_date": "Date the server was last modified.",+ },+ },+ "audit_trail_events": {+ "description": "Audit trail events recording actions taken on the organization's resources.",+ "docs_url": "https://www.scaleway.com/en/developers/api/audit-trail/",+ "columns": {+ "id": "Unique identifier of the event.",+ "recorded_at": "Date and time the event was recorded.",+ "organization_id": "ID of the organization the event belongs to.",+ "project_id": "ID of the project the event relates to, if any.",+ "principal_id": "ID of the principal (user or application) that triggered the event.",+ "source_ip": "Source IP address the action originated from.",+ "product_name": "Name of the product the event relates to.",+ "service_name": "Name of the API service that handled the action.",+ "method_name": "Name of the API method that was called.",+ "resource_type": "Type of the resource acted upon.",+ "status": "Outcome status code of the action.",+ },+ },+}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.mdnew file mode 100644index 000000000000..f36c7e68a141--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/scaleway/docs/scaleway.md@@ -0,0 +1,66 @@+---+title: Linking Scaleway as a source+sidebar: Docs+showTitle: true+availability: { free: full, selfServe: full, enterprise: full }+sourceId: Scaleway+beta: true+---++import SourceSetupIntro from "../\_snippets/source-setup-intro.mdx"+import SyncModes from "../\_snippets/sync-modes.mdx"+import TroubleshootingLink from "../\_snippets/dw-troubleshooting-link.mdx"+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.++## Prerequisites++Before connecting Scaleway, you need:++- A Scaleway account with an **Organization**.+- An **IAM API key** (secret key) with read permissions for the data you want to sync.+- Your **Organization ID**.++## Adding a data source++<SourceSetupIntro />++You will need the following:++- **API secret key**: create an API key from the [IAM > API keys](https://console.scaleway.com/iam/api-keys) page in the Scaleway console. The secret key is shown only once at creation, so copy it then. Scaleway API secret keys do not expire by default.+- **Organization ID**: find it under [Organization settings](https://console.scaleway.com/organization/settings).++Grant the API key the read permission sets that match the tables you want to sync. You only need the ones for the data you actually want:++- `IAMReadOnly` — users, applications, groups, policies, API keys, SSH keys+- `ProjectReadOnly` — projects+- `BillingReadOnly` — invoices+- `AuditTrailReadOnly` — audit trail events+- `InstancesReadOnly` — instance servers++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.++## Sync modes++<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.++## Configuration++<SourceParameters />++## Supported tables++<SourceTables />++## Troubleshooting++**"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.++<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.pynew file mode 100644index 000000000000..f5496c7b51c5--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/scaleway/scaleway.py@@ -0,0 +1,245 @@+import dataclasses+from collections.abc import Iterator+from datetime import UTC, datetime, timedelta+from typing import Any++import requests+from structlog.types import FilteringBoundLogger++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.scaleway.settings import (+ AUDIT_TRAIL_REGIONS,+ INSTANCE_ZONES,+ PAGE_SIZE,+ SCALEWAY_ENDPOINTS,+ ScalewayEndpointConfig,+)++BASE_URL = "https://api.scaleway.com"+REQUEST_TIMEOUT = 60++# Sentinel scope for endpoints that aren't region/zone-scoped, so the fan-out loop always iterates a+# non-empty list of exactly one pass.+_UNSCOPED = "_"+++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+ # unscoped endpoints.+ scope_index: int = 0+ # Page-number cursor for the `page`/`page_size` and `page`/`per_page` dialects: the next page to+ # fetch within the current scope.+ page: int | None = None+ # Opaque cursor for the token dialect (Audit Trail): the next `page_token` to fetch.+ page_token: str | None = None+++def _get_headers(secret_key: str) -> dict[str, str]:+ # Scaleway authenticates every request with the API secret key in the X-Auth-Token header.+ return {"X-Auth-Token": secret_key, "Accept": "application/json"}+++def _format_rfc3339(dt: datetime) -> str:+ return dt.astimezone(UTC).strftime("%Y-%m-%dT%H:%M:%SZ")+++def _scopes_for(config: ScalewayEndpointConfig) -> list[str]:+ if config.scope == "region":+ return AUDIT_TRAIL_REGIONS+ if config.scope == "zone":+ return INSTANCE_ZONES+ return [_UNSCOPED]+++def _resolve_path(config: ScalewayEndpointConfig, scope: str) -> str:+ if config.scope == "region":+ return config.path.format(region=scope)+ if config.scope == "zone":+ return config.path.format(zone=scope)+ return config.path+++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] = {}+ if config.pagination == "per_page":+ params["per_page"] = PAGE_SIZE+ else:+ params["page_size"] = PAGE_SIZE++ if config.org_param and organization_id:+ params[config.org_param] = organization_id+ if config.order_param and config.order_value:+ params[config.order_param] = config.order_value+ if config.lookback_param and config.lookback_days:+ params[config.lookback_param] = _format_rfc3339(datetime.now(UTC) - timedelta(days=config.lookback_days))++ params.update(config.extra_params)+ return params+++def _fetch(session: requests.Session, url: str, params: dict[str, Any], logger: FilteringBoundLogger) -> dict:+ # The tracked session already retries 429 and transient 5xx (urllib3 Retry), so a non-ok response+ # here is a terminal status (401/403/404/400) — log and raise so get_non_retryable_errors can+ # classify auth/permission failures.+ response = session.get(url, params=params, timeout=REQUEST_TIMEOUT)+ if not response.ok:+ log = logger.warning if response.status_code == 404 else logger.error+ log(f"Scaleway API error: status={response.status_code}, url={url}, body={response.text[:500]}")+ response.raise_for_status()+ return response.json()+++def _iter_pages(+ session: requests.Session,+ url: str,+ base_params: dict[str, Any],+ config: ScalewayEndpointConfig,+ logger: FilteringBoundLogger,+ start_page: int | None,+ start_token: str | None,+) -> Iterator[tuple[list[dict], bool, dict[str, Any]]]:+ """Page through one scope, yielding ``(items, has_more, next_cursor)`` per response.++ ``next_cursor`` is the resume-state fragment (``{"page": n}`` or ``{"page_token": t}``) pointing at+ the page after the one just yielded; the caller persists it after handing the batch downstream.+ """+ if config.pagination == "token":+ token = start_token+ while True:+ # A page_token carries the original window/order server-side, so subsequent requests must+ # send only the token (plus page size) — re-sending the time filter alongside it can be+ # rejected or shift the window.+ if token:+ params = {"page_size": PAGE_SIZE, "page_token": token}+ else:+ params = {**base_params}+ data = _fetch(session, url, params, logger)+ items = data.get(config.data_key) or []+ next_token = data.get("next_page_token") or None+ has_more = next_token is not None+ yield items, has_more, {"page_token": next_token}+ if not has_more:+ break+ token = next_token+ else:+ page = start_page or 1+ while True:+ params = {**base_params, "page": page}+ data = _fetch(session, url, params, logger)+ items = data.get(config.data_key) or []+ # No total_count is trusted across all three dialects; a short page marks the end.+ has_more = len(items) >= PAGE_SIZE+ yield items, has_more, {"page": page + 1}+ if not has_more:+ break+ page += 1+++def get_rows(+ secret_key: str,+ organization_id: str,+ endpoint: str,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[ScalewayResumeConfig],+) -> Iterator[list[dict]]:+ config = SCALEWAY_ENDPOINTS[endpoint]+ # One session reused across every page (and, for fan-out, every scope) so urllib3 keeps the+ # connection alive instead of re-handshaking per request. redact_values masks the secret key in+ # 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)++ 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+ 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)}"+ # 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+ start_token = resume.page_token+ else:+ 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))++ # 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))+++def scaleway_source(+ secret_key: str,+ organization_id: str,+ endpoint: str,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[ScalewayResumeConfig],+) -> SourceResponse:+ config = SCALEWAY_ENDPOINTS[endpoint]++ return SourceResponse(+ name=endpoint,+ items=lambda: get_rows(+ secret_key=secret_key,+ organization_id=organization_id,+ endpoint=endpoint,+ logger=logger,+ resumable_source_manager=resumable_source_manager,+ ),+ primary_keys=config.primary_keys,+ # Every endpoint is full refresh; sort is only for stable pagination. Requests ask for the+ # configured ascending order where the API supports it.+ sort_mode="asc",+ partition_count=1,+ partition_size=1,+ partition_mode="datetime" if config.partition_key else None,+ partition_format="month" if config.partition_key else None,+ partition_keys=[config.partition_key] if config.partition_key else None,+ )+++def probe_endpoint(secret_key: str, organization_id: str, endpoint: str) -> int:+ """Issue a minimal one-row request against an endpoint and return the HTTP status code.++ Returns 0 for a network-level failure so the caller can treat it as "not a definitive auth+ denial" rather than a missing scope.+ """+ config = SCALEWAY_ENDPOINTS[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)+ if config.pagination == "per_page":+ params["per_page"] = 1+ else:+ params["page_size"] = 1+ if config.pagination != "token":+ params["page"] = 1+ try:+ response = session.get(url, params=params, timeout=REQUEST_TIMEOUT)+ return response.status_code+ except requests.RequestException:+ return 0+++def validate_credentials(secret_key: str, organization_id: str) -> int:+ """Probe the cheapest organization-scoped endpoint (IAM users) and return its HTTP status code."""+ return probe_endpoint(secret_key, organization_id, "users")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.pynew file mode 100644index 000000000000..f38dcb20cb35--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/scaleway/settings.py@@ -0,0 +1,195 @@+from dataclasses import dataclass, field+from typing import Literal, Optional++from products.warehouse_sources.backend.types import IncrementalField++# Scaleway exposes three different pagination dialects across its products, so each endpoint declares+# which one it uses:+# - "page_size": `page` + `page_size` query params, body wraps `{"<key>": [...], "total_count": N}`+# (IAM, Account, Billing).+# - "per_page": `page` + `per_page` query params, body is `{"<key>": [...]}` and the total lives in+# the `X-Total-Count` response header (Instance).+# - "token": `page_size` + `page_token` query params, body carries `next_page_token`+# (Audit Trail).+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"]++# Max items per page allowed by every paginated Scaleway list endpoint.+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"]++# 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 = [+ "fr-par-1",+ "fr-par-2",+ "fr-par-3",+ "nl-ams-1",+ "nl-ams-2",+ "nl-ams-3",+ "pl-waw-1",+ "pl-waw-2",+ "pl-waw-3",+ "it-mil-1",+]++# Audit Trail's list endpoint defaults `recorded_after` to one hour ago, so a full pull must pass an+# explicit lower bound. Each full refresh re-pulls this trailing window (older events age out of the+# table). A future incremental mode could instead resume from the last `recorded_at` — see source.py.+AUDIT_TRAIL_LOOKBACK_DAYS = 90+++@dataclass+class ScalewayEndpointConfig:+ name: str+ # Path relative to the API base URL. May contain a `{region}` or `{zone}` placeholder that the+ # connector fills from the scope list before requesting.+ path: str+ # JSON key in the response body holding the array of rows.+ data_key: str+ pagination: Pagination+ primary_keys: list[str] = field(default_factory=lambda: ["id"])+ # Stable creation-timestamp field used for datetime partitioning. Never a mutable "updated"/+ # "modified" field, which would rewrite partitions on every sync.+ partition_key: Optional[str] = None+ scope: Scope = "none"+ # 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.+ org_param: Optional[str] = "organization_id"+ # Sort param name + value. Scaleway uses `order_by` on most products but `order` on Instance.+ # An explicit ascending sort keeps pagination stable across page boundaries. Values are taken+ # from the products' OpenAPI schemas.+ order_param: Optional[str] = None+ order_value: Optional[str] = None+ # Extra static query params merged into every request.+ extra_params: dict[str, str] = field(default_factory=dict)+ # Server-side lower-bound time filter (e.g. Audit Trail's `recorded_after`). When set, the+ # connector passes `<lookback_param>=now-<lookback_days>` so a full refresh pulls a bounded+ # trailing window instead of relying on the endpoint's tiny default window.+ lookback_param: Optional[str] = None+ lookback_days: Optional[int] = None+ should_sync_default: bool = True+ description: Optional[str] = None+++SCALEWAY_ENDPOINTS: dict[str, ScalewayEndpointConfig] = {+ "users": ScalewayEndpointConfig(+ name="users",+ path="/iam/v1alpha1/users",+ data_key="users",+ pagination="page_size",+ partition_key="created_at",+ order_param="order_by",+ order_value="created_at_asc",+ ),+ "applications": ScalewayEndpointConfig(+ name="applications",+ path="/iam/v1alpha1/applications",+ data_key="applications",+ pagination="page_size",+ partition_key="created_at",+ order_param="order_by",+ order_value="created_at_asc",+ ),+ "groups": ScalewayEndpointConfig(+ name="groups",+ path="/iam/v1alpha1/groups",+ data_key="groups",+ pagination="page_size",+ partition_key="created_at",+ order_param="order_by",+ order_value="created_at_asc",+ ),+ "policies": ScalewayEndpointConfig(+ name="policies",+ path="/iam/v1alpha1/policies",+ data_key="policies",+ pagination="page_size",+ partition_key="created_at",+ order_param="order_by",+ order_value="created_at_asc",+ ),+ "api_keys": ScalewayEndpointConfig(+ name="api_keys",+ path="/iam/v1alpha1/api-keys",+ data_key="api_keys",+ # API keys are identified by their public access key, not an `id`.+ primary_keys=["access_key"],+ pagination="page_size",+ partition_key="created_at",+ order_param="order_by",+ order_value="created_at_asc",+ ),+ "ssh_keys": ScalewayEndpointConfig(+ name="ssh_keys",+ path="/iam/v1alpha1/ssh-keys",+ data_key="ssh_keys",+ pagination="page_size",+ partition_key="created_at",+ order_param="order_by",+ order_value="created_at_asc",+ ),+ "projects": ScalewayEndpointConfig(+ name="projects",+ path="/account/v3/projects",+ data_key="projects",+ pagination="page_size",+ partition_key="created_at",+ # Account requires organization_id explicitly.+ org_param="organization_id",+ order_param="order_by",+ order_value="created_at_asc",+ ),+ "invoices": ScalewayEndpointConfig(+ name="invoices",+ path="/billing/v2beta1/invoices",+ data_key="invoices",+ pagination="page_size",+ # Invoices have no created_at/updated_at; start_date is the stable period start.+ partition_key="start_date",+ org_param="organization_id",+ order_param="order_by",+ order_value="start_date_asc",+ ),+ "instance_servers": ScalewayEndpointConfig(+ name="instance_servers",+ path="/instance/v1/zones/{zone}/servers",+ data_key="servers",+ pagination="per_page",+ # Instance uses `creation_date`/`modification_date` rather than `created_at`/`updated_at`.+ partition_key="creation_date",+ scope="zone",+ org_param="organization",+ order_param="order",+ order_value="creation_date_asc",+ ),+ "audit_trail_events": ScalewayEndpointConfig(+ name="audit_trail_events",+ path="/audit-trail/v1alpha1/regions/{region}/events",+ data_key="events",+ pagination="token",+ partition_key="recorded_at",+ scope="region",+ # Audit Trail requires organization_id explicitly.+ org_param="organization_id",+ order_param="order_by",+ order_value="recorded_at_asc",+ lookback_param="recorded_after",+ lookback_days=AUDIT_TRAIL_LOOKBACK_DAYS,+ description=(f"Syncs the most recent {AUDIT_TRAIL_LOOKBACK_DAYS} days of audit events on each full refresh"),+ ),+}++ENDPOINTS = tuple(SCALEWAY_ENDPOINTS.keys())++# Every endpoint ships as full refresh: none of Scaleway's list endpoints expose a verified server-side+# "updated since" filter with a matching stable ascending sort, and the resource inventories are small.+# Kept as an explicit (empty) map so the shape matches the other sources and incremental fields can be+# added per endpoint once behavior is curl-verified against the live API.+INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {}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.pyindex adb1bf0b2ecd..09de17b18df3 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@@ -1,19 +1,44 @@-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 ScalewaySourceConfig+from products.warehouse_sources.backend.temporal.data_imports.sources.scaleway.scaleway import (+ ScalewayResumeConfig,+ probe_endpoint,+ scaleway_source,+ validate_credentials as validate_scaleway_credentials,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.scaleway.settings import (+ ENDPOINTS,+ INCREMENTAL_FIELDS,+ SCALEWAY_ENDPOINTS,+)from products.warehouse_sources.backend.types import ExternalDataSourceType@SourceRegistry.register-class ScalewaySource(SimpleSource[ScalewaySourceConfig]):+class ScalewaySource(ResumableSource[ScalewaySourceConfig, ScalewayResumeConfig]):+ lists_tables_without_credentials = True # static endpoint catalog — safe for public docs+@propertydef source_type(self) -> ExternalDataSourceType:return ExternalDataSourceType.SCALEWAY@@ -24,8 +49,142 @@ class ScalewaySource(SimpleSource[ScalewaySourceConfig]):name=SchemaExternalDataSourceType.SCALEWAY,category=DataWarehouseSourceCategory.ENGINEERING___MONITORING,label="Scaleway",- iconPath="/static/services/scaleway.png",- keywords=["cloud", "billing", "infrastructure", "invoices"],- fields=cast(list[FieldType], []),+ releaseStatus=ReleaseStatus.ALPHA,unreleasedSource=True,+ caption="""Enter your Scaleway API secret key and Organization ID to pull your Scaleway data into the PostHog Data warehouse.++Create an API key from the [IAM > API keys](https://console.scaleway.com/iam/api-keys) page in the Scaleway console, and find your Organization ID under [Organization settings](https://console.scaleway.com/organization/settings).++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+- `AuditTrailReadOnly` for audit trail events+- `InstancesReadOnly` for instance servers+""",+ iconPath="/static/services/scaleway.svg",+ docsUrl="https://posthog.com/docs/cdp/sources/scaleway",+ keywords=["cloud", "billing", "infrastructure", "invoices", "iam"],+ fields=cast(+ list[FieldType],+ [+ SourceFieldInputConfig(+ name="secret_key",+ label="API secret key",+ type=SourceFieldInputConfigType.PASSWORD,+ required=True,+ placeholder="",+ secret=True,+ ),+ SourceFieldInputConfig(+ name="organization_id",+ label="Organization ID",+ type=SourceFieldInputConfigType.TEXT,+ required=True,+ placeholder="00000000-0000-0000-0000-000000000000",+ secret=False,+ ),+ ],+ ),+ )++ def get_canonical_descriptions(self) -> CanonicalDescriptions:+ from products.warehouse_sources.backend.temporal.data_imports.sources.scaleway.canonical_descriptions import (+ CANONICAL_DESCRIPTIONS,+ )++ return CANONICAL_DESCRIPTIONS++ def get_non_retryable_errors(self) -> dict[str, str | None]:+ return {+ # An invalid/revoked secret key surfaces as a requests HTTPError from raise_for_status().+ # Retrying can never satisfy a credential problem, so stop the sync. Match the stable+ # status text and base host, not the per-request path/query.+ "401 Client Error: Unauthorized for url: https://api.scaleway.com": "Your Scaleway API secret key is invalid or has been revoked. Create a new key in the Scaleway console and reconnect.",+ "403 Client Error: Forbidden for url: https://api.scaleway.com": "Your Scaleway API key is missing the read permission set needed to sync this data. Grant the matching read permissions in the Scaleway console and reconnect.",+ }++ def get_schemas(+ self,+ config: ScalewaySourceConfig,+ 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 = SCALEWAY_ENDPOINTS[endpoint]+ return SourceSchema(+ name=endpoint,+ # Full refresh only — no verified server-side "updated since" filter across endpoints.+ supports_incremental=False,+ supports_append=False,+ incremental_fields=INCREMENTAL_FIELDS.get(endpoint, []),+ should_sync_default=endpoint_config.should_sync_default,+ description=endpoint_config.description,+ detected_primary_keys=endpoint_config.primary_keys,+ )++ 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: ScalewaySourceConfig, team_id: int, schema_name: Optional[str] = None+ ) -> tuple[bool, str | None]:+ if not config.organization_id:+ return False, "Organization ID is required"++ if schema_name is None or schema_name not in SCALEWAY_ENDPOINTS:+ status = validate_scaleway_credentials(config.secret_key, config.organization_id)+ # Accept 403 at source-create: the token is genuine but may only be scoped to the+ # endpoints the user actually wants to sync. Per-table scope is surfaced separately.+ if status in (200, 403):+ return True, None+ if status == 401:+ return False, "Invalid Scaleway API secret key"+ return False, f"Could not validate Scaleway credentials (HTTP {status})"++ status = probe_endpoint(config.secret_key, config.organization_id, schema_name)+ if status == 200:+ return True, None+ if status == 401:+ return False, "Invalid Scaleway API secret key"+ if status == 403:+ return False, f"Your API key is missing the read permission set required to sync '{schema_name}'"+ return False, f"Could not validate access to '{schema_name}' (HTTP {status})"++ def get_endpoint_permissions(+ self, config: ScalewaySourceConfig, team_id: int, endpoints: list[str]+ ) -> dict[str, str | None]:+ # Only a genuine 403 denial marks a table as needing extra scopes; throttles, 5xx and network+ # blips are left reachable so a transient hiccup never blocks the picker.+ result: dict[str, str | None] = {}+ for name in endpoints:+ if name not in SCALEWAY_ENDPOINTS:+ result[name] = None+ continue+ status = probe_endpoint(config.secret_key, config.organization_id, name)+ result[name] = (+ "Requires a Scaleway API key with the matching read permission set" if status == 403 else None+ )+ return result++ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[ScalewayResumeConfig]:+ return ResumableSourceManager[ScalewayResumeConfig](inputs, ScalewayResumeConfig)++ def source_for_pipeline(+ self,+ config: ScalewaySourceConfig,+ resumable_source_manager: ResumableSourceManager[ScalewayResumeConfig],+ inputs: SourceInputs,+ ) -> SourceResponse:+ return scaleway_source(+ secret_key=config.secret_key,+ organization_id=config.organization_id,+ endpoint=inputs.schema_name,+ logger=inputs.logger,+ resumable_source_manager=resumable_source_manager,)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.pynew file mode 100644index 000000000000..d520dba0af4c--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/scaleway/tests/test_scaleway.py@@ -0,0 +1,214 @@+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.sources.scaleway import scaleway+from products.warehouse_sources.backend.temporal.data_imports.sources.scaleway.scaleway import (+ ScalewayResumeConfig,+ _base_params,+ _resolve_path,+ get_rows,+ probe_endpoint,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.scaleway.settings import (+ INSTANCE_ZONES,+ PAGE_SIZE,+ SCALEWAY_ENDPOINTS,+)+++def _response(body: dict, status: int = 200, ok: bool = True) -> MagicMock:+ resp = MagicMock()+ resp.status_code = status+ resp.ok = ok+ resp.text = ""+ resp.json.return_value = body+ resp.raise_for_status = MagicMock()+ return resp+++def _manager(resume: ScalewayResumeConfig | None = None) -> MagicMock:+ manager = MagicMock()+ manager.can_resume.return_value = resume is not None+ manager.load_state.return_value = resume+ return manager+++def _drive(endpoint: str, responses: list[MagicMock], manager: MagicMock) -> tuple[list[list[dict]], MagicMock]:+ """Run get_rows for `endpoint` against a session that returns `responses` in order."""+ session = MagicMock()+ session.get.side_effect = responses+ with patch.object(scaleway, "make_tracked_session", return_value=session):+ pages = list(+ get_rows(+ secret_key="scw-secret",+ organization_id="org-123",+ endpoint=endpoint,+ logger=MagicMock(),+ resumable_source_manager=manager,+ )+ )+ return pages, session+++class TestBaseParams:+ @parameterized.expand(+ [+ # (endpoint, expected page-size param, expected org param name)+ ("users", "page_size", "organization_id"),+ ("projects", "page_size", "organization_id"),+ ("invoices", "page_size", "organization_id"),+ ("instance_servers", "per_page", "organization"),+ ("audit_trail_events", "page_size", "organization_id"),+ ]+ )+ def test_pagination_and_org_param_wiring(self, endpoint: str, page_param: str, org_param: str) -> None:+ # Guards the three-dialect wiring: Instance must use per_page + `organization`, everything else+ # page_size + `organization_id`. A swap here silently breaks pagination or org scoping.+ params = _base_params(SCALEWAY_ENDPOINTS[endpoint], "org-123")+ assert params[page_param] == PAGE_SIZE+ assert params[org_param] == "org-123"++ @parameterized.expand(+ [+ ("users", "order_by", "created_at_asc"),+ ("invoices", "order_by", "start_date_asc"),+ ("instance_servers", "order", "creation_date_asc"),+ ("audit_trail_events", "order_by", "recorded_at_asc"),+ ]+ )+ def test_sort_param_wiring(self, endpoint: str, order_param: str, order_value: str) -> None:+ params = _base_params(SCALEWAY_ENDPOINTS[endpoint], "org-123")+ assert params[order_param] == order_value++ def test_audit_trail_sets_recorded_after_lower_bound(self) -> None:+ # Audit Trail defaults to a 1h window, so a full pull must send an explicit recorded_after.+ params = _base_params(SCALEWAY_ENDPOINTS["audit_trail_events"], "org-123")+ assert "recorded_after" in params+ assert params["recorded_after"].endswith("Z")++ def test_non_audit_endpoint_has_no_time_filter(self) -> None:+ assert "recorded_after" not in _base_params(SCALEWAY_ENDPOINTS["users"], "org-123")+++class TestResolvePath:+ @parameterized.expand(+ [+ ("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"),+ ]+ )+ def test_scope_substitution(self, endpoint: str, scope: str, expected: str) -> None:+ assert _resolve_path(SCALEWAY_ENDPOINTS[endpoint], scope) == expected+++class TestPageNumberPagination:+ def test_terminates_on_short_page_and_saves_resume_after_full_page(self) -> None:+ full = _response({"users": [{"id": str(i)} for i in range(PAGE_SIZE)]})+ short = _response({"users": [{"id": "x"}]})+ manager = _manager()++ pages, session = _drive("users", [full, short], manager)++ assert [len(p) for p in pages] == [PAGE_SIZE, 1]+ # Two page requests, second asks for page 2.+ assert session.get.call_count == 2+ assert session.get.call_args_list[1].kwargs["params"]["page"] == 2+ # Resume state persisted only while more pages remained — pointing at the next page.+ saved = [c.args[0] for c in manager.save_state.call_args_list]+ assert ScalewayResumeConfig(scope_index=0, page=2) in saved++ def test_resumes_from_saved_page(self) -> None:+ short = _response({"users": [{"id": "x"}]})+ manager = _manager(ScalewayResumeConfig(scope_index=0, page=7))++ _pages, session = _drive("users", [short], manager)++ assert session.get.call_args_list[0].kwargs["params"]["page"] == 7+++class TestTokenPagination:+ def test_chains_tokens_and_drops_window_filter_on_subsequent_requests(self) -> None:+ page1 = _response({"events": [{"id": "a"}], "next_page_token": "tok2"})+ page2 = _response({"events": [{"id": "b"}], "next_page_token": None})+ # audit_trail_events fans out over two regions; give each region a single terminal page after+ # the first region's two-page chain.+ region2 = _response({"events": [], "next_page_token": None})+ manager = _manager()++ pages, session = _drive("audit_trail_events", [page1, page2, region2], manager)++ assert [row["id"] for page in pages for row in page] == ["a", "b"]+ # First request carries the recorded_after window; the token follow-up must not (the token+ # already encodes it server-side).+ first_params = session.get.call_args_list[0].kwargs["params"]+ second_params = session.get.call_args_list[1].kwargs["params"]+ assert "recorded_after" in first_params+ assert second_params == {"page_size": PAGE_SIZE, "page_token": "tok2"}++ def test_resumes_from_saved_token(self) -> None:+ terminal = _response({"events": [], "next_page_token": None})+ manager = _manager(ScalewayResumeConfig(scope_index=1, page_token="saved-tok"))++ _pages, session = _drive("audit_trail_events", [terminal], manager)++ # scope_index=1 skips the already-finished first region; the saved token drives the request.+ assert session.get.call_args_list[0].kwargs["params"]["page_token"] == "saved-tok"+++class TestFanOut:+ def test_iterates_every_zone_and_advances_scope_between_them(self) -> None:+ # Each zone returns one short page, so the connector visits every zone once.+ responses = [_response({"servers": [{"id": f"srv-{z}"}]}) for z in INSTANCE_ZONES]+ manager = _manager()++ pages, session = _drive("instance_servers", responses, manager)++ assert session.get.call_count == len(INSTANCE_ZONES)+ requested_urls = [c.args[0] for c in session.get.call_args_list]+ for zone in INSTANCE_ZONES:+ assert any(f"/zones/{zone}/servers" in url for url in requested_urls)+ # Between scopes the bookmark advances so a crash resumes at the next zone, not the first.+ saved_scope_indices = [c.args[0].scope_index for c in manager.save_state.call_args_list]+ assert saved_scope_indices == list(range(1, len(INSTANCE_ZONES)))+ assert sum(len(p) for p in pages) == len(INSTANCE_ZONES)+++class TestFetchErrors:+ def test_non_ok_response_raises(self) -> None:+ err = _response({}, status=403, ok=False)+ err.raise_for_status.side_effect = requests.HTTPError("403 Client Error: Forbidden", response=err)+ manager = _manager()++ with pytest.raises(requests.HTTPError):+ _drive("users", [err], manager)+++class TestProbeEndpoint:+ @parameterized.expand([("ok", 200, 200), ("unauthorized", 401, 401), ("forbidden", 403, 403)])+ def test_returns_status_code(self, _name: str, status: int, expected: int) -> None:+ session = MagicMock()+ session.get.return_value = _response({}, status=status, ok=status < 400)+ with patch.object(scaleway, "make_tracked_session", return_value=session):+ assert probe_endpoint("scw-secret", "org-123", "users") == expected++ def test_network_error_returns_zero(self) -> None:+ session = MagicMock()+ session.get.side_effect = requests.ConnectionError("boom")+ with patch.object(scaleway, "make_tracked_session", return_value=session):+ assert probe_endpoint("scw-secret", "org-123", "users") == 0++ @parameterized.expand([("page_size_endpoint", "users"), ("token_endpoint", "audit_trail_events")])+ def test_requests_a_single_row(self, _name: str, endpoint: str) -> None:+ session = MagicMock()+ session.get.return_value = _response({}, status=200)+ with patch.object(scaleway, "make_tracked_session", return_value=session):+ probe_endpoint("scw-secret", "org-123", endpoint)+ params: dict[str, Any] = session.get.call_args.kwargs["params"]+ size_key = "per_page" if SCALEWAY_ENDPOINTS[endpoint].pagination == "per_page" else "page_size"+ assert params[size_key] == 1diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/scaleway/tests/test_scaleway_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/scaleway/tests/test_scaleway_source.pynew file mode 100644index 000000000000..9de5862e02f1--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/scaleway/tests/test_scaleway_source.py@@ -0,0 +1,130 @@+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.pipelines.pipeline.typings import SourceInputs+from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs import ScalewaySourceConfig+from products.warehouse_sources.backend.temporal.data_imports.sources.scaleway import source as source_module+from products.warehouse_sources.backend.temporal.data_imports.sources.scaleway.scaleway import ScalewayResumeConfig+from products.warehouse_sources.backend.temporal.data_imports.sources.scaleway.settings import ENDPOINTS+from products.warehouse_sources.backend.temporal.data_imports.sources.scaleway.source import ScalewaySource+from products.warehouse_sources.backend.types import ExternalDataSourceType+++def _config() -> ScalewaySourceConfig:+ return ScalewaySourceConfig(secret_key="scw-secret", organization_id="org-123")+++class TestScalewaySource:+ def setup_method(self) -> None:+ self.source = ScalewaySource()+ self.team_id = 123++ def test_source_type(self) -> None:+ assert self.source.source_type == ExternalDataSourceType.SCALEWAY++ def test_secret_key_field_is_marked_secret(self) -> None:+ # A secret leaking as a plain (non-secret) field would be stored/echoed in cleartext, so lock+ # this down: secret_key must be a secret PASSWORD field; organization_id is a plain identifier.+ fields = {f.name: f for f in self.source.get_source_config.fields}+ secret_key_field = fields["secret_key"]+ organization_id_field = fields["organization_id"]+ assert isinstance(secret_key_field, SourceFieldInputConfig)+ assert isinstance(organization_id_field, SourceFieldInputConfig)+ assert secret_key_field.type == SourceFieldInputConfigType.PASSWORD+ assert secret_key_field.secret is True+ assert organization_id_field.secret is not True++ def test_ships_as_alpha_and_unreleased(self) -> None:+ config = self.source.get_source_config+ assert config.releaseStatus == ReleaseStatus.ALPHA+ assert config.unreleasedSource is True+ assert config.docsUrl == "https://posthog.com/docs/cdp/sources/scaleway"++ @parameterized.expand([("unauthorized", "401"), ("forbidden", "403")])+ def test_auth_errors_are_non_retryable(self, _name: str, status: str) -> None:+ assert any(status in key for key in self.source.get_non_retryable_errors())++ @parameterized.expand([(e,) for e in ENDPOINTS])+ def test_every_schema_is_full_refresh_only(self, endpoint: str) -> None:+ # No endpoint has a verified server-side "updated since" filter, so none may advertise+ # incremental/append — otherwise the picker offers a mode that would sync nothing new.+ schemas = {s.name: s for s in self.source.get_schemas(_config(), self.team_id)}+ schema = schemas[endpoint]+ assert schema.supports_incremental is False+ assert schema.supports_append is False++ def test_api_keys_primary_key_is_access_key(self) -> None:+ # API keys have no `id`; keying on the wrong column seeds duplicate rows that every merge+ # multi-matches.+ schemas = {s.name: s for s in self.source.get_schemas(_config(), self.team_id)}+ assert schemas["api_keys"].detected_primary_keys == ["access_key"]++ def test_get_schemas_filters_by_name(self) -> None:+ schemas = self.source.get_schemas(_config(), self.team_id, names=["invoices", "users"])+ assert {s.name for s in schemas} == {"invoices", "users"}++ @parameterized.expand(+ [+ # (probe status, schema_name, expected valid)+ ("create_ok", 200, None, True),+ ("create_missing_scope_accepted", 403, None, True),+ ("create_bad_token", 401, None, False),+ ("schema_ok", 200, "invoices", True),+ ("schema_missing_scope_rejected", 403, "invoices", False),+ ("schema_bad_token", 401, "invoices", False),+ ]+ )+ def test_validate_credentials(self, _name: str, status: int, schema_name: str | None, expected: bool) -> None:+ with (+ patch.object(source_module, "validate_scaleway_credentials", return_value=status),+ patch.object(source_module, "probe_endpoint", return_value=status),+ ):+ valid, _message = self.source.validate_credentials(_config(), self.team_id, schema_name=schema_name)+ assert valid is expected++ def test_validate_credentials_requires_organization_id(self) -> None:+ valid, message = self.source.validate_credentials(+ ScalewaySourceConfig(secret_key="scw-secret", organization_id=""), self.team_id+ )+ assert valid is False+ assert "Organization ID" in (message or "")++ @parameterized.expand([("forbidden", 403, True), ("reachable", 200, False), ("throttled", 429, False)])+ def test_endpoint_permissions_only_flags_real_denials(self, _name: str, status: int, is_blocked: bool) -> None:+ # Only a genuine 403 marks a table as needing extra scopes; a throttle or 5xx must not block+ # the picker (get_endpoint_permissions must never fail source creation for a transient blip).+ with patch.object(source_module, "probe_endpoint", return_value=status):+ result = self.source.get_endpoint_permissions(_config(), self.team_id, ["invoices"])+ assert (result["invoices"] is not None) is is_blocked++ def test_resumable_manager_bound_to_resume_config(self) -> None:+ inputs = self._source_inputs("users")+ manager = self.source.get_resumable_source_manager(inputs)+ assert manager._data_class is ScalewayResumeConfig++ def test_source_for_pipeline_plumbs_endpoint(self) -> None:+ inputs = self._source_inputs("api_keys")+ response = self.source.source_for_pipeline(_config(), MagicMock(), inputs)+ assert response.name == "api_keys"+ assert response.primary_keys == ["access_key"]+ assert response.partition_mode == "datetime"+ assert response.partition_keys == ["created_at"]++ def _source_inputs(self, schema_name: str) -> SourceInputs:+ return SourceInputs(+ schema_name=schema_name,+ schema_id="schema-1",+ source_id="source-1",+ team_id=self.team_id,+ should_use_incremental_field=False,+ db_incremental_field_last_value=None,+ db_incremental_field_earliest_value=None,+ incremental_field=None,+ incremental_field_type=None,+ job_id="job-1",+ logger=MagicMock(),+ reset_pipeline=False,+ )