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): implement aiven import source (#70009)

Tom Owers6670a0c2b1da
diff --git a/frontend/public/services/aiven.svg b/frontend/public/services/aiven.svg
new file mode 100644
index 000000000000..818673862025
--- /dev/null
+++ b/frontend/public/services/aiven.svg
@@ -0,0 +1 @@
+<svg xmlns="http://www.w3.org/2000/svg" width="64" height="64" fill="none" viewBox="0 0 64 64"><path fill="#05080f" d="M0 0H64V64H0z"/><path fill="#fff" d="M44.706 38.723C45.514 38.723 46.297 38.871 47.033 39.138 48.186 37.805 48.809 36.344 48.809 34.846 48.809 32.374 47.14 29.994 44.111 28.145 40.868 26.163 36.533 25.073 31.899 25.073 27.265 25.073 22.929 26.166 19.686 28.145 16.658 29.997 14.988 32.374 14.988 34.846 14.988 36.344 15.609 37.805 16.765 39.138 17.501 38.871 18.283 38.723 19.092 38.723 20.912 38.723 22.622 39.431 23.915 40.72 24.804 41.613 25.416 42.726 25.708 43.926 27.656 44.378 29.743 44.624 31.899 44.624 34.055 44.624 36.142 44.378 38.089 43.926 38.382 42.726 38.993 41.613 39.883 40.72 41.176 39.431 42.888 38.723 44.708 38.723H44.706ZM31.896 33.04C29.803 33.04 28.102 31.339 28.102 29.247H35.692C35.692 31.339 33.988 33.04 31.899 33.04H31.896ZM18.75 26.357C19.115 26.134 19.498 25.928 19.886 25.729L19.872 25.717C18.912 24.995 17.785 24.648 16.669 24.648 15.046 24.648 13.447 25.381 12.4 26.775L11.951 27.372 14.971 29.644C15.907 28.432 17.177 27.322 18.753 26.357H18.75ZM15.002 40.086C13.991 38.787 13.362 37.367 13.162 35.886 13.116 35.542 13.087 35.194 13.087 34.843 13.087 33.116 13.663 31.452 14.75 29.937H14.359C11.414 29.937 9.018 32.328 9.018 35.269V36.017H12.997C11.959 36.878 11.29 38.072 11.11 39.413 10.922 40.828 11.293 42.23 12.159 43.364L12.492 43.798C12.797 42.642 13.394 41.581 14.26 40.715 14.492 40.483 14.741 40.277 14.999 40.083L15.002 40.086ZM48.823 29.644 51.843 27.372 51.394 26.775C50.348 25.381 48.745 24.648 47.122 24.648 46.006 24.648 44.879 24.995 43.92 25.717L43.905 25.729C44.294 25.931 44.676 26.134 45.041 26.357 46.618 27.322 47.887 28.432 48.823 29.644ZM54.768 35.272C54.768 32.33 52.371 29.94 49.427 29.94H49.035C50.122 31.455 50.699 33.116 50.699 34.846 50.699 35.197 50.67 35.544 50.624 35.889 50.424 37.37 49.795 38.787 48.783 40.089 49.041 40.283 49.29 40.489 49.522 40.72 50.389 41.587 50.986 42.648 51.29 43.804L51.623 43.369C52.49 42.236 52.861 40.834 52.673 39.419 52.493 38.077 51.823 36.883 50.786 36.026H54.765V35.275L54.768 35.272ZM25.47 23.851C28.412 23.851 30.809 21.454 30.809 18.512 30.809 15.571 28.412 13.174 25.47 13.174 22.529 13.174 20.132 15.568 20.132 18.512 20.132 21.457 22.526 23.851 25.47 23.851ZM25.473 15.585C25.473 15.585 25.49 15.585 25.499 15.585 25.12 15.959 24.882 16.475 24.882 17.052 24.882 18.185 25.801 19.103 26.934 19.103 27.51 19.103 28.029 18.866 28.4 18.483 28.4 18.492 28.4 18.501 28.4 18.512 28.4 20.129 27.09 21.439 25.473 21.439 23.856 21.439 22.546 20.129 22.546 18.512 22.546 16.895 23.856 15.585 25.473 15.585ZM38.318 23.851C41.259 23.851 43.656 21.454 43.656 18.512 43.656 15.571 41.259 13.174 38.318 13.174 35.376 13.174 32.98 15.568 32.98 18.512 32.98 21.457 35.373 23.851 38.318 23.851ZM38.318 15.585C38.318 15.585 38.335 15.585 38.344 15.585 37.964 15.959 37.727 16.475 37.727 17.052 37.727 18.185 38.645 19.103 39.779 19.103 40.355 19.103 40.874 18.866 41.245 18.483 41.245 18.492 41.245 18.501 41.245 18.512 41.245 20.129 39.935 21.439 38.318 21.439 36.701 21.439 35.391 20.129 35.391 18.512 35.391 16.895 36.701 15.585 38.318 15.585Z"/><path fill="#fff" d="M19.084 40.205C16.136 40.205 13.748 42.593 13.748 45.541 13.748 48.488 16.136 50.876 19.084 50.876 19.704 50.876 20.295 50.766 20.846 50.572 20.796 50.525 20.744 50.479 20.695 50.43 19.144 48.879 18.623 46.891 19.527 45.984 20.431 45.08 22.422 45.601 23.973 47.152 24.022 47.201 24.068 47.253 24.115 47.306 24.309 46.752 24.419 46.161 24.419 45.541 24.419 42.593 22.031 40.205 19.084 40.205ZM44.714 40.205C41.767 40.205 39.379 42.593 39.379 45.541 39.379 46.161 39.489 46.752 39.683 47.306 39.733 47.253 39.776 47.204 39.825 47.152 41.376 45.601 43.364 45.08 44.271 45.984 45.175 46.888 44.654 48.879 43.103 50.43 43.054 50.479 43.002 50.525 42.952 50.572 43.506 50.766 44.097 50.876 44.714 50.876 47.662 50.876 50.05 48.488 50.05 45.541 50.05 42.593 47.662 40.205 44.714 40.205Z"/></svg>
\ No newline at end of file
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
index d7c75aa8b226..690657b14918 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
@@ -50,6 +50,7 @@ the row lists both.
| aircall | HTTP | requests | ✅ |
| airops | HTTP | requests | ✅ |
| airtable | HTTP | requests | ✅ |
+| aiven | HTTP | requests | ✅ |
| algolia | HTTP | requests | ✅ |
| alguna | HTTP | requests | ✅ |
| alpha_vantage | HTTP | requests | ✅ |
@@ -503,6 +504,7 @@ doesn't conflict with concurrent PRs.
- aikido_security
- airbrake
- airbyte
+- airops
- aiven
- akeneo
- alpaca_broker_api
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/aiven/aiven.py b/products/warehouse_sources/backend/temporal/data_imports/sources/aiven/aiven.py
new file mode 100644
index 000000000000..68987cc2226e
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/aiven/aiven.py
@@ -0,0 +1,171 @@
+from collections.abc import Iterator
+from typing import Any
+
+import requests
+from structlog.types import FilteringBoundLogger
+from tenacity import retry, retry_if_exception_type, stop_after_attempt, wait_exponential_jitter
+
+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import SourceResponse
+from products.warehouse_sources.backend.temporal.data_imports.sources.aiven.settings import (
+ AIVEN_ENDPOINTS,
+ AivenEndpointConfig,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.http import make_tracked_session
+
+AIVEN_BASE_URL = "https://api.aiven.io/v1"
+REQUEST_TIMEOUT_SECONDS = 60
+MAX_RETRIES = 5
+
+
+class AivenRetryableError(Exception):
+ pass
+
+
+def _get_headers(api_token: str) -> dict[str, str]:
+ # Aiven expects the literal `aivenv1` prefix before the token, not `Bearer`.
+ return {
+ "Authorization": f"aivenv1 {api_token}",
+ "Accept": "application/json",
+ }
+
+
+def _make_session(api_token: str) -> requests.Session:
+ # Redact the token everywhere it could surface: the `aivenv1 <token>` scheme is
+ # non-standard, so the tracked transport's name-based scrubbers can't recognise it.
+ return make_tracked_session(redact_values=(api_token,))
+
+
+@retry(
+ retry=retry_if_exception_type((AivenRetryableError, requests.ReadTimeout, requests.ConnectionError)),
+ stop=stop_after_attempt(MAX_RETRIES),
+ wait=wait_exponential_jitter(initial=1, max=60),
+ reraise=True,
+)
+def _fetch(
+ url: str, headers: dict[str, str], logger: FilteringBoundLogger, session: requests.Session
+) -> dict[str, Any]:
+ response = session.get(url, headers=headers, timeout=REQUEST_TIMEOUT_SECONDS)
+
+ # Aiven does not publish rate limits; treat 429 and transient 5xx as retryable and let the
+ # exponential backoff handle spacing. Everything else (401/403/404) is surfaced immediately.
+ if response.status_code == 429 or response.status_code >= 500:
+ raise AivenRetryableError(f"Aiven API error (retryable): status={response.status_code}, url={url}")
+
+ if not response.ok:
+ # Never log the raw body: these are authenticated third-party responses whose error
+ # payloads can echo tenant metadata or request details into centralized logs.
+ logger.error(f"Aiven API error: status={response.status_code}, url={url}")
+ response.raise_for_status()
+
+ return response.json()
+
+
+def _list(
+ path: str, data_key: str, headers: dict[str, str], logger: FilteringBoundLogger, session: requests.Session
+) -> list[dict[str, Any]]:
+ """Fetch a single unpaginated Aiven list endpoint and return the rows under ``data_key``.
+
+ Aiven list endpoints return the whole collection in one JSON response (``{"<data_key>": [...]}``)
+ with no pagination params documented or accepted, so a single GET is the complete result.
+ """
+ data = _fetch(f"{AIVEN_BASE_URL}{path}", headers, logger, session)
+ rows = data.get(data_key) or []
+ return rows if isinstance(rows, list) else []
+
+
+def _iter_rows(
+ config: AivenEndpointConfig, headers: dict[str, str], logger: FilteringBoundLogger, session: requests.Session
+) -> Iterator[list[dict[str, Any]]]:
+ """Yield one batch of rows per upstream request, fanning out over parents as needed.
+
+ Child rows get their parent identifiers injected as top-level fields so composite primary
+ keys stay unique table-wide and rows remain traceable to their parent resource.
+ """
+ if config.fan_out == "none":
+ rows = _list(config.path_template, config.data_key, headers, logger, session)
+ if rows:
+ yield rows
+ return
+
+ if config.fan_out == "project":
+ for project in _list("/project", "projects", headers, logger, session):
+ project_name = project["project_name"]
+ path = config.path_template.format(project=project_name)
+ rows = _list(path, config.data_key, headers, logger, session)
+ for row in rows:
+ row["project_name"] = project_name
+ if rows:
+ yield rows
+ return
+
+ if config.fan_out == "organization":
+ for org in _list("/organizations", "organizations", headers, logger, session):
+ organization_id = org["organization_id"]
+ path = config.path_template.format(organization_id=organization_id)
+ rows = _list(path, config.data_key, headers, logger, session)
+ for row in rows:
+ row.setdefault("organization_id", organization_id)
+ if rows:
+ yield rows
+ return
+
+ if config.fan_out == "invoice":
+ for org in _list("/organizations", "organizations", headers, logger, session):
+ organization_id = org["organization_id"]
+ invoices = _list(f"/organization/{organization_id}/invoices", "invoices", headers, logger, session)
+ for invoice in invoices:
+ invoice_number = invoice["invoice_number"]
+ path = config.path_template.format(organization_id=organization_id, invoice_number=invoice_number)
+ rows = _list(path, config.data_key, headers, logger, session)
+ for row in rows:
+ row.setdefault("organization_id", organization_id)
+ row["invoice_number"] = invoice_number
+ if rows:
+ yield rows
+ return
+
+ raise ValueError(f"Unknown fan_out mode: {config.fan_out}")
+
+
+def get_rows(
+ api_token: str,
+ endpoint: str,
+ logger: FilteringBoundLogger,
+) -> Iterator[list[dict[str, Any]]]:
+ config = AIVEN_ENDPOINTS[endpoint]
+ headers = _get_headers(api_token)
+ # One session for the whole run so fan-out requests reuse pooled connections.
+ session = _make_session(api_token)
+ yield from _iter_rows(config, headers, logger, session)
+
+
+def validate_credentials(api_token: str) -> bool:
+ """Confirm the token is valid. ``/me`` reflects the token itself and needs no resource scope."""
+ try:
+ response = _make_session(api_token).get(
+ f"{AIVEN_BASE_URL}/me",
+ headers=_get_headers(api_token),
+ timeout=10,
+ )
+ return response.status_code == 200
+ except Exception:
+ return False
+
+
+def aiven_source(
+ api_token: str,
+ endpoint: str,
+ logger: FilteringBoundLogger,
+) -> SourceResponse:
+ config = AIVEN_ENDPOINTS[endpoint]
+
+ return SourceResponse(
+ name=endpoint,
+ items=lambda: get_rows(api_token=api_token, endpoint=endpoint, logger=logger),
+ primary_keys=config.primary_keys,
+ partition_count=1,
+ partition_size=1,
+ partition_mode="datetime" if config.partition_key else None,
+ partition_format="week" if config.partition_key else None,
+ partition_keys=[config.partition_key] if config.partition_key else None,
+ )
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/aiven/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/aiven/canonical_descriptions.py
new file mode 100644
index 000000000000..0d5d3dda02be
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/aiven/canonical_descriptions.py
@@ -0,0 +1,142 @@
+"""Canonical, documentation-sourced descriptions for Aiven endpoints and columns.
+
+Sourced from the official Aiven API reference (https://api.aiven.io/doc). Keyed by the endpoint
+names in `settings.py` `AIVEN_ENDPOINTS`, which match the `ExternalDataSchema.name` of a synced
+Aiven table. Columns absent here fall back to LLM enrichment.
+"""
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (
+ CanonicalDescriptions,
+)
+
+CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
+ "projects": {
+ "description": "An Aiven project — the container that groups services and their billing.",
+ "docs_url": "https://api.aiven.io/doc/#tag/Project",
+ "columns": {
+ "project_name": "Unique name of the project (its identifier).",
+ "account_id": "Identifier of the account the project belongs to.",
+ "organization_id": "Identifier of the organization the project belongs to.",
+ "billing_group_id": "Identifier of the billing group the project is billed under.",
+ "billing_currency": "Currency used for billing this project.",
+ "default_cloud": "Default cloud region for services created in this project.",
+ "estimated_balance": "Estimated unbilled balance for the current period.",
+ },
+ },
+ "organizations": {
+ "description": "An Aiven organization — the top-level tenant that owns projects and billing.",
+ "docs_url": "https://api.aiven.io/doc/#tag/Organizations",
+ "columns": {
+ "organization_id": "Unique identifier of the organization.",
+ "organization_name": "Display name of the organization.",
+ "account_id": "Identifier of the underlying account.",
+ "tier": "Subscription tier of the organization.",
+ "create_time": "Timestamp when the organization was created.",
+ "update_time": "Timestamp when the organization was last updated.",
+ },
+ },
+ "services": {
+ "description": "A running Aiven managed service (Kafka, PostgreSQL, ClickHouse, OpenSearch, etc.).",
+ "docs_url": "https://api.aiven.io/doc/#tag/Service",
+ "columns": {
+ "project_name": "Name of the project the service belongs to (injected from the parent).",
+ "service_name": "Name of the service (unique within its project).",
+ "service_type": "Service type code (e.g. kafka, pg, clickhouse).",
+ "cloud_name": "Cloud region the service runs in.",
+ "plan": "Subscription plan of the service.",
+ "state": "Current state of the service (e.g. RUNNING, POWEROFF).",
+ "create_time": "Service creation timestamp (ISO 8601).",
+ "update_time": "Service last update timestamp (ISO 8601).",
+ "node_count": "Number of service nodes in the active plan.",
+ },
+ },
+ "billing_groups": {
+ "description": "A billing group that aggregates charges for one or more projects.",
+ "docs_url": "https://api.aiven.io/doc/#tag/BillingGroup",
+ "columns": {
+ "billing_group_id": "Unique identifier of the billing group.",
+ "billing_group_name": "Display name of the billing group.",
+ "organization_id": "Identifier of the owning organization.",
+ "payment_method": "Payment method used for the billing group.",
+ "vat_id": "VAT identifier associated with the billing group.",
+ "create_time": "Timestamp when the billing group was created.",
+ },
+ },
+ "invoices": {
+ "description": "An issued invoice for a billing group.",
+ "docs_url": "https://api.aiven.io/doc/#tag/Invoice",
+ "columns": {
+ "invoice_number": "Invoice identifier.",
+ "billing_group_id": "Identifier of the billing group the invoice is for.",
+ "organization_id": "Identifier of the owning organization.",
+ "currency": "Currency the invoice is denominated in.",
+ "state": "State of the invoice (e.g. estimate, mailed, paid).",
+ "net": "Total invoice amount without taxes, in local currency.",
+ "net_usd": "Total invoice amount without taxes, in USD.",
+ "total": "Total invoice amount including taxes, in local currency.",
+ "total_usd": "Total invoice amount including taxes, in USD.",
+ "invoice_period": "Billing period the invoice covers.",
+ "issue_date": "Date the invoice was issued.",
+ "due_date": "Date the invoice is due.",
+ "create_time": "Date when the invoice was created.",
+ },
+ },
+ "invoice_lines": {
+ "description": "A single cost line on an invoice — the per-service breakdown used for BI cost export.",
+ "docs_url": "https://api.aiven.io/doc/#tag/Invoice",
+ "columns": {
+ "invoice_number": "Invoice the line belongs to (injected from the parent).",
+ "organization_id": "Owning organization identifier (injected from the parent).",
+ "description": "Human-readable description of the line item.",
+ "line_type": "Type of the line item.",
+ "service_id": "Identifier of the service the charge is for.",
+ "service_type": "Type of the service the charge is for.",
+ "project_id": "Name of the project the charge is for.",
+ "cloud": "Cloud provider/region the charge is for.",
+ "plan": "Plan of the service being charged.",
+ "begin_time": "Start timestamp of the line item's billing window.",
+ "end_time": "End timestamp of the line item's billing window.",
+ "total": "Total amount for the line, in local currency.",
+ "total_usd": "Total amount for the line, in USD.",
+ "currency": "Currency the line is denominated in.",
+ },
+ },
+ "organization_users": {
+ "description": "A member of an Aiven organization.",
+ "docs_url": "https://api.aiven.io/doc/#tag/Organizations",
+ "columns": {
+ "organization_id": "Organization the membership is in (injected from the parent).",
+ "user_id": "Unique identifier of the user.",
+ "is_super_admin": "Whether the user is a super admin of the organization.",
+ "join_time": "Timestamp when the user joined the organization.",
+ "last_activity_time": "Timestamp of the user's last activity.",
+ },
+ },
+ "user_groups": {
+ "description": "A user group within an organization for grouping members and permissions.",
+ "docs_url": "https://api.aiven.io/doc/#tag/Organizations",
+ "columns": {
+ "organization_id": "Organization the group belongs to (injected from the parent).",
+ "user_group_id": "Unique identifier of the user group.",
+ "user_group_name": "Display name of the user group.",
+ "description": "Description of the user group.",
+ "member_count": "Number of members in the group.",
+ "managed_by_scim": "Whether the group is managed via SCIM.",
+ "create_time": "Timestamp when the group was created.",
+ "update_time": "Timestamp when the group was last updated.",
+ },
+ },
+ "clouds": {
+ "description": "Global catalogue of Aiven cloud regions across AWS, GCP and Azure.",
+ "docs_url": "https://api.aiven.io/doc/#tag/Cloud",
+ "columns": {
+ "cloud_name": "Unique cloud region identifier (e.g. aws-eu-west-1).",
+ "cloud_description": "Human-readable region description.",
+ "provider": "Cloud provider code (aws, gcp, azure).",
+ "provider_description": "Human-readable cloud provider name.",
+ "geo_region": "Geographic region the cloud sits in.",
+ "geo_latitude": "Latitude of the cloud region.",
+ "geo_longitude": "Longitude of the cloud region.",
+ },
+ },
+}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/aiven/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/aiven/settings.py
new file mode 100644
index 000000000000..8c63daf46ef5
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/aiven/settings.py
@@ -0,0 +1,124 @@
+from dataclasses import dataclass, field
+from typing import Literal, Optional
+
+from products.warehouse_sources.backend.types import IncrementalField
+
+# How an endpoint's request URLs are derived:
+# "none" -> a single top-level list endpoint (no parent fan-out)
+# "project" -> one request per project the token can see
+# "organization" -> one request per organization the token can see
+# "invoice" -> one request per (organization, invoice) pair (two-level fan-out)
+FanOut = Literal["none", "project", "organization", "invoice"]
+
+
+@dataclass
+class AivenEndpointConfig:
+ name: str
+ fan_out: FanOut
+ # Relative path appended to the API base. Fan-out endpoints carry ``{project}``,
+ # ``{organization_id}`` and/or ``{invoice_number}`` placeholders filled in per parent.
+ path_template: str
+ # Response wrapper key: Aiven list endpoints return ``{"<data_key>": [...]}``.
+ data_key: str
+ primary_keys: list[str] = field(default_factory=lambda: ["id"])
+ # Stable creation-time field used for datetime partitioning. Never an ``update_time``-style
+ # field, which would rewrite partitions on every sync.
+ partition_key: Optional[str] = None
+ should_sync_default: bool = True
+
+
+AIVEN_ENDPOINTS: dict[str, AivenEndpointConfig] = {
+ # Top-level inventory.
+ "projects": AivenEndpointConfig(
+ name="projects",
+ fan_out="none",
+ path_template="/project",
+ data_key="projects",
+ primary_keys=["project_name"],
+ ),
+ "organizations": AivenEndpointConfig(
+ name="organizations",
+ fan_out="none",
+ path_template="/organizations",
+ data_key="organizations",
+ primary_keys=["organization_id"],
+ partition_key="create_time",
+ ),
+ # Fan out one request per project.
+ "services": AivenEndpointConfig(
+ name="services",
+ fan_out="project",
+ path_template="/project/{project}/service",
+ data_key="services",
+ # `service_name` is unique within a project but not across projects, so the injected
+ # parent `project_name` is part of the key to keep it unique table-wide.
+ primary_keys=["project_name", "service_name"],
+ partition_key="create_time",
+ ),
+ # Fan out one request per organization.
+ "billing_groups": AivenEndpointConfig(
+ name="billing_groups",
+ fan_out="organization",
+ path_template="/organization/{organization_id}/billing-groups",
+ data_key="billing_groups",
+ primary_keys=["billing_group_id"],
+ partition_key="create_time",
+ ),
+ "invoices": AivenEndpointConfig(
+ name="invoices",
+ fan_out="organization",
+ path_template="/organization/{organization_id}/invoices",
+ data_key="invoices",
+ # `invoice_number` is only unique within an organization, so the injected
+ # `organization_id` keeps the row unique table-wide.
+ primary_keys=["organization_id", "invoice_number"],
+ partition_key="create_time",
+ ),
+ "organization_users": AivenEndpointConfig(
+ name="organization_users",
+ fan_out="organization",
+ path_template="/organization/{organization_id}/user",
+ data_key="users",
+ # A user can belong to more than one organization, so the injected `organization_id`
+ # keeps the row unique across organizations.
+ primary_keys=["organization_id", "user_id"],
+ partition_key="join_time",
+ ),
+ "user_groups": AivenEndpointConfig(
+ name="user_groups",
+ fan_out="organization",
+ path_template="/organization/{organization_id}/user-groups",
+ data_key="user_groups",
+ primary_keys=["organization_id", "user_group_id"],
+ partition_key="create_time",
+ ),
+ # Two-level fan-out: per organization, per invoice. Aiven markets these per-line cost rows
+ # as the canonical way to export billing into a warehouse/BI tool.
+ "invoice_lines": AivenEndpointConfig(
+ name="invoice_lines",
+ fan_out="invoice",
+ path_template="/organization/{organization_id}/invoice/{invoice_number}/lines",
+ data_key="lines",
+ # Invoice lines carry no server-assigned id. This composite is best-effort unique and the
+ # table is full-refresh (replace), so a collision cannot accumulate duplicates across syncs.
+ # `organization_id` scopes the key so identical invoice numbers across organizations don't collide.
+ primary_keys=["organization_id", "invoice_number", "service_id", "line_type", "begin_time", "end_time"],
+ partition_key="begin_time",
+ ),
+ # Global Aiven cloud/region catalogue. Not account-specific, so off by default.
+ "clouds": AivenEndpointConfig(
+ name="clouds",
+ fan_out="none",
+ path_template="/clouds",
+ data_key="clouds",
+ primary_keys=["cloud_name"],
+ should_sync_default=False,
+ ),
+}
+
+ENDPOINTS = tuple(AIVEN_ENDPOINTS.keys())
+
+# Aiven's list endpoints expose no server-side timestamp filter (no `since`/`updated_after` query
+# params on any of them), so every table ships full-refresh only. Declaring incremental support
+# without a real server filter would make each "incremental" run cost the same as a full refresh.
+INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/aiven/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/aiven/source.py
index 909aa836bd97..5eccbe906b12 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/aiven/source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/aiven/source.py
@@ -1,19 +1,41 @@
-from typing import cast
+from typing import Optional, cast
from posthog.schema import (
DataWarehouseSourceCategory,
ExternalDataSourceType as SchemaExternalDataSourceType,
+ ReleaseStatus,
SourceConfig,
+ SourceFieldInputConfig,
+ SourceFieldInputConfigType,
)
+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import (
+ SourceInputs,
+ SourceResponse,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.aiven.aiven import (
+ aiven_source,
+ validate_credentials as validate_aiven_credentials,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.aiven.settings import (
+ AIVEN_ENDPOINTS,
+ ENDPOINTS,
+ INCREMENTAL_FIELDS,
+)
from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, SimpleSource
+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.schema import SourceSchema
from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs import AivenSourceConfig
from products.warehouse_sources.backend.types import ExternalDataSourceType
@SourceRegistry.register
class AivenSource(SimpleSource[AivenSourceConfig]):
+ lists_tables_without_credentials = True # static endpoint catalog — safe for public docs
+
@property
def source_type(self) -> ExternalDataSourceType:
return ExternalDataSourceType.AIVEN
@@ -24,8 +46,82 @@ class AivenSource(SimpleSource[AivenSourceConfig]):
name=SchemaExternalDataSourceType.AIVEN,
category=DataWarehouseSourceCategory.ENGINEERING___MONITORING,
label="Aiven",
- iconPath="/static/services/aiven.png",
+ releaseStatus=ReleaseStatus.ALPHA,
+ caption="""Enter an Aiven API token to pull your Aiven projects, services and billing data into the PostHog Data warehouse.
+
+You can create a personal token from your [Aiven profile authentication page](https://console.aiven.io/profile/auth).
+
+Billing tables (billing groups, invoices, invoice lines) and organization membership tables require organization-level read access on the token.
+""",
+ iconPath="/static/services/aiven.svg",
+ docsUrl="https://posthog.com/docs/cdp/sources/aiven",
keywords=["aiven", "cloud", "billing", "infrastructure"],
- fields=cast(list[FieldType], []),
- unreleasedSource=True,
+ fields=cast(
+ list[FieldType],
+ [
+ SourceFieldInputConfig(
+ name="api_token",
+ label="API token",
+ type=SourceFieldInputConfigType.PASSWORD,
+ required=True,
+ placeholder="",
+ secret=True,
+ ),
+ ],
+ ),
+ )
+
+ def get_canonical_descriptions(self) -> CanonicalDescriptions:
+ from products.warehouse_sources.backend.temporal.data_imports.sources.aiven.canonical_descriptions import (
+ CANONICAL_DESCRIPTIONS,
+ )
+
+ return CANONICAL_DESCRIPTIONS
+
+ def get_non_retryable_errors(self) -> dict[str, str | None]:
+ return {
+ # An invalid, revoked, or insufficiently-scoped token surfaces as an HTTPError when
+ # `_fetch` calls `raise_for_status()`. Retrying can never satisfy a credential problem.
+ "401 Client Error: Unauthorized for url: https://api.aiven.io": "Your Aiven API token is invalid or has expired. Create a new token on your Aiven profile authentication page, then reconnect.",
+ "403 Client Error: Forbidden for url: https://api.aiven.io": "Your Aiven API token is missing the access needed to sync this data. Grant organization-level read access, then reconnect.",
+ }
+
+ def get_schemas(
+ self,
+ config: AivenSourceConfig,
+ team_id: int,
+ with_counts: bool = False,
+ names: list[str] | None = None,
+ force_refresh: bool = False,
+ ) -> list[SourceSchema]:
+ schemas = [
+ SourceSchema(
+ name=endpoint,
+ supports_incremental=INCREMENTAL_FIELDS.get(endpoint, None) is not None,
+ supports_append=INCREMENTAL_FIELDS.get(endpoint, None) is not None,
+ incremental_fields=INCREMENTAL_FIELDS.get(endpoint, []),
+ should_sync_default=AIVEN_ENDPOINTS[endpoint].should_sync_default,
+ )
+ 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: AivenSourceConfig, team_id: int, schema_name: Optional[str] = None
+ ) -> tuple[bool, str | None]:
+ if validate_aiven_credentials(config.api_token):
+ return True, None
+
+ return False, "Invalid Aiven API token"
+
+ def source_for_pipeline(self, config: AivenSourceConfig, inputs: SourceInputs) -> SourceResponse:
+ return aiven_source(
+ api_token=config.api_token,
+ endpoint=inputs.schema_name,
+ logger=inputs.logger,
)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/aiven/tests/test_aiven.py b/products/warehouse_sources/backend/temporal/data_imports/sources/aiven/tests/test_aiven.py
new file mode 100644
index 000000000000..0ff7d249bccd
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/aiven/tests/test_aiven.py
@@ -0,0 +1,221 @@
+from typing import Any, cast
+
+import pytest
+from unittest.mock import MagicMock, patch
+
+import requests
+from parameterized import parameterized
+from tenacity import stop_after_attempt, wait_none
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.aiven import aiven
+from products.warehouse_sources.backend.temporal.data_imports.sources.aiven.aiven import (
+ _fetch,
+ _get_headers,
+ _iter_rows,
+ _list,
+ aiven_source,
+ get_rows,
+ validate_credentials,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.aiven.settings import AIVEN_ENDPOINTS
+
+
+def _response(status_code: int, body: dict[str, Any] | None = None) -> MagicMock:
+ resp = MagicMock(spec=requests.Response)
+ resp.status_code = status_code
+ resp.ok = status_code < 400
+ resp.text = ""
+ resp.json.return_value = body or {}
+
+ def _raise() -> None:
+ if not resp.ok:
+ raise requests.HTTPError(
+ f"{status_code} Client Error: for url: https://api.aiven.io/v1/x",
+ response=cast(requests.Response, resp),
+ )
+
+ resp.raise_for_status.side_effect = _raise
+ return resp
+
+
+class TestGetHeaders:
+ def test_uses_aivenv1_scheme_not_bearer(self) -> None:
+ headers = _get_headers("tok-123")
+ # Aiven requires the literal `aivenv1` prefix; a `Bearer` prefix is rejected by the API.
+ assert headers["Authorization"] == "aivenv1 tok-123"
+ assert "Bearer" not in headers["Authorization"]
+
+
+class TestFetch:
+ def test_success_returns_json(self) -> None:
+ session = MagicMock()
+ session.get.return_value = _response(200, {"projects": [{"project_name": "p1"}]})
+ result = _fetch("https://api.aiven.io/v1/project", {}, MagicMock(), session)
+ assert result == {"projects": [{"project_name": "p1"}]}
+
+ @parameterized.expand([("rate_limited", 429), ("server_error", 500), ("bad_gateway", 503)])
+ def test_retryable_statuses_retry_then_raise(self, _name: str, status: int) -> None:
+ session = MagicMock()
+ session.get.return_value = _response(status)
+ # tenacity attaches `retry_with` to the wrapped fn at runtime; the type stub omits it.
+ fetch = _fetch.retry_with(stop=stop_after_attempt(3), wait=wait_none()) # type: ignore[attr-defined]
+ with pytest.raises(aiven.AivenRetryableError):
+ fetch("https://api.aiven.io/v1/project", {}, MagicMock(), session)
+ assert session.get.call_count == 3
+
+ @parameterized.expand([("unauthorized", 401), ("forbidden", 403), ("not_found", 404)])
+ def test_client_errors_raise_immediately_without_retry(self, _name: str, status: int) -> None:
+ session = MagicMock()
+ session.get.return_value = _response(status)
+ with pytest.raises(requests.HTTPError):
+ _fetch("https://api.aiven.io/v1/project", {}, MagicMock(), session)
+ # Credential/permission failures must not burn retries.
+ assert session.get.call_count == 1
+
+
+class TestList:
+ @parameterized.expand(
+ [
+ ("present", {"projects": [{"project_name": "p1"}]}, [{"project_name": "p1"}]),
+ ("missing_key", {"other": []}, []),
+ ("null_value", {"projects": None}, []),
+ ("non_list", {"projects": {"nested": 1}}, []),
+ ]
+ )
+ def test_extracts_rows_under_data_key(self, _name: str, body: dict[str, Any], expected: list) -> None:
+ with patch.object(aiven, "_fetch", return_value=body):
+ assert _list("/project", "projects", {}, MagicMock(), MagicMock()) == expected
+
+
+class TestFanOut:
+ def test_fan_out_none_yields_single_batch(self) -> None:
+ with patch.object(aiven, "_fetch", return_value={"clouds": [{"cloud_name": "aws-x"}]}):
+ batches = list(_iter_rows(AIVEN_ENDPOINTS["clouds"], {}, MagicMock(), MagicMock()))
+ assert batches == [[{"cloud_name": "aws-x"}]]
+
+ def test_fan_out_project_injects_parent_project_name(self) -> None:
+ # `services` items carry no project field, so the parent's `project_name` must be injected
+ # to keep the composite primary key unique across projects.
+ responses = {
+ "/project": {"projects": [{"project_name": "p1"}, {"project_name": "p2"}]},
+ "/project/p1/service": {"services": [{"service_name": "s1"}]},
+ "/project/p2/service": {"services": [{"service_name": "s2"}]},
+ }
+
+ def fake_fetch(url: str, *args: Any, **kwargs: Any) -> dict[str, Any]:
+ return responses[url.replace(aiven.AIVEN_BASE_URL, "")]
+
+ with patch.object(aiven, "_fetch", side_effect=fake_fetch):
+ batches = list(_iter_rows(AIVEN_ENDPOINTS["services"], {}, MagicMock(), MagicMock()))
+
+ assert batches == [
+ [{"service_name": "s1", "project_name": "p1"}],
+ [{"service_name": "s2", "project_name": "p2"}],
+ ]
+
+ def test_fan_out_organization_injects_org_without_overwriting(self) -> None:
+ responses = {
+ "/organizations": {"organizations": [{"organization_id": "org1"}]},
+ "/organization/org1/user": {"users": [{"user_id": "u1"}]},
+ }
+
+ def fake_fetch(url: str, *args: Any, **kwargs: Any) -> dict[str, Any]:
+ return responses[url.replace(aiven.AIVEN_BASE_URL, "")]
+
+ with patch.object(aiven, "_fetch", side_effect=fake_fetch):
+ batches = list(_iter_rows(AIVEN_ENDPOINTS["organization_users"], {}, MagicMock(), MagicMock()))
+
+ assert batches == [[{"user_id": "u1", "organization_id": "org1"}]]
+
+ def test_fan_out_organization_setdefault_keeps_existing_org_id(self) -> None:
+ # billing_groups already carry organization_id; injection must not clobber it.
+ responses = {
+ "/organizations": {"organizations": [{"organization_id": "org1"}]},
+ "/organization/org1/billing-groups": {
+ "billing_groups": [{"billing_group_id": "bg1", "organization_id": "org-real"}]
+ },
+ }
+
+ def fake_fetch(url: str, *args: Any, **kwargs: Any) -> dict[str, Any]:
+ return responses[url.replace(aiven.AIVEN_BASE_URL, "")]
+
+ with patch.object(aiven, "_fetch", side_effect=fake_fetch):
+ batches = list(_iter_rows(AIVEN_ENDPOINTS["billing_groups"], {}, MagicMock(), MagicMock()))
+
+ assert batches[0][0]["organization_id"] == "org-real"
+
+ def test_fan_out_invoice_two_levels_injects_org_and_invoice(self) -> None:
+ responses = {
+ "/organizations": {"organizations": [{"organization_id": "org1"}]},
+ "/organization/org1/invoices": {"invoices": [{"invoice_number": "inv1"}, {"invoice_number": "inv2"}]},
+ "/organization/org1/invoice/inv1/lines": {"lines": [{"line_type": "usage"}]},
+ "/organization/org1/invoice/inv2/lines": {"lines": [{"line_type": "credit"}]},
+ }
+
+ def fake_fetch(url: str, *args: Any, **kwargs: Any) -> dict[str, Any]:
+ return responses[url.replace(aiven.AIVEN_BASE_URL, "")]
+
+ with patch.object(aiven, "_fetch", side_effect=fake_fetch):
+ batches = list(_iter_rows(AIVEN_ENDPOINTS["invoice_lines"], {}, MagicMock(), MagicMock()))
+
+ assert batches == [
+ [{"line_type": "usage", "organization_id": "org1", "invoice_number": "inv1"}],
+ [{"line_type": "credit", "organization_id": "org1", "invoice_number": "inv2"}],
+ ]
+
+ def test_empty_batches_are_not_yielded(self) -> None:
+ responses: dict[str, dict[str, Any]] = {
+ "/project": {"projects": [{"project_name": "p1"}, {"project_name": "p2"}]},
+ "/project/p1/service": {"services": []},
+ "/project/p2/service": {"services": [{"service_name": "s2"}]},
+ }
+
+ def fake_fetch(url: str, *args: Any, **kwargs: Any) -> dict[str, Any]:
+ return responses[url.replace(aiven.AIVEN_BASE_URL, "")]
+
+ with patch.object(aiven, "_fetch", side_effect=fake_fetch):
+ batches = list(_iter_rows(AIVEN_ENDPOINTS["services"], {}, MagicMock(), MagicMock()))
+
+ assert batches == [[{"service_name": "s2", "project_name": "p2"}]]
+
+
+class TestValidateCredentials:
+ @parameterized.expand([("ok", 200, True), ("unauthorized", 401, False), ("server_error", 500, False)])
+ def test_maps_status_to_bool(self, _name: str, status: int, expected: bool) -> None:
+ session = MagicMock()
+ session.get.return_value = _response(status)
+ with patch.object(aiven, "make_tracked_session", return_value=session):
+ assert validate_credentials("tok") is expected
+
+ def test_network_error_is_false(self) -> None:
+ session = MagicMock()
+ session.get.side_effect = requests.ConnectionError("boom")
+ with patch.object(aiven, "make_tracked_session", return_value=session):
+ assert validate_credentials("tok") is False
+
+
+class TestAivenSource:
+ def test_get_rows_uses_single_tracked_session(self) -> None:
+ session = MagicMock()
+ with (
+ patch.object(aiven, "make_tracked_session", return_value=session) as make_session,
+ patch.object(aiven, "_iter_rows", return_value=iter([])) as iter_rows,
+ ):
+ list(get_rows("tok", "projects", MagicMock()))
+ make_session.assert_called_once()
+ # The one session is threaded into the fan-out so requests reuse pooled connections.
+ assert iter_rows.call_args.args[3] is session
+
+ @parameterized.expand(list(AIVEN_ENDPOINTS.keys()))
+ def test_source_response_matches_endpoint_settings(self, endpoint: str) -> None:
+ config = AIVEN_ENDPOINTS[endpoint]
+ response = aiven_source("tok", endpoint, MagicMock())
+
+ assert response.name == endpoint
+ assert response.primary_keys == config.primary_keys
+ if config.partition_key:
+ assert response.partition_mode == "datetime"
+ assert response.partition_keys == [config.partition_key]
+ else:
+ assert response.partition_mode is None
+ assert response.partition_keys is None
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/aiven/tests/test_aiven_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/aiven/tests/test_aiven_source.py
new file mode 100644
index 000000000000..a370d470d34c
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/aiven/tests/test_aiven_source.py
@@ -0,0 +1,91 @@
+from unittest.mock import MagicMock, patch
+
+from parameterized import parameterized
+
+from posthog.schema import SourceFieldInputConfig
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.aiven import source as source_module
+from products.warehouse_sources.backend.temporal.data_imports.sources.aiven.settings import AIVEN_ENDPOINTS, ENDPOINTS
+from products.warehouse_sources.backend.temporal.data_imports.sources.aiven.source import AivenSource
+from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs import AivenSourceConfig
+from products.warehouse_sources.backend.types import ExternalDataSourceType
+
+
+def _config() -> AivenSourceConfig:
+ return AivenSourceConfig.from_dict({"api_token": "tok"})
+
+
+class TestSourceConfig:
+ def test_source_type(self) -> None:
+ assert AivenSource().source_type == ExternalDataSourceType.AIVEN
+
+ def test_config_shape(self) -> None:
+ config = AivenSource().get_source_config
+ assert config.name == "Aiven"
+ assert config.releaseStatus == "alpha"
+ assert config.docsUrl == "https://posthog.com/docs/cdp/sources/aiven"
+
+ def test_single_secret_token_field(self) -> None:
+ fields = AivenSource().get_source_config.fields
+ assert [f.name for f in fields] == ["api_token"]
+ token = fields[0]
+ assert isinstance(token, SourceFieldInputConfig)
+ assert token.required is True
+ assert token.secret is True
+ assert token.type == "password"
+
+
+class TestGetSchemas:
+ def test_lists_all_endpoints_full_refresh_only(self) -> None:
+ schemas = AivenSource().get_schemas(_config(), team_id=1)
+ assert {s.name for s in schemas} == set(ENDPOINTS)
+ # Aiven exposes no server-side timestamp filter, so nothing is incremental.
+ assert all(s.supports_incremental is False for s in schemas)
+ assert all(s.supports_append is False for s in schemas)
+
+ def test_clouds_off_by_default(self) -> None:
+ by_name = {s.name: s for s in AivenSource().get_schemas(_config(), team_id=1)}
+ assert by_name["clouds"].should_sync_default is False
+ assert by_name["invoices"].should_sync_default is True
+
+ def test_names_filter(self) -> None:
+ schemas = AivenSource().get_schemas(_config(), team_id=1, names=["invoices", "invoice_lines"])
+ assert {s.name for s in schemas} == {"invoices", "invoice_lines"}
+
+
+class TestValidateCredentials:
+ @parameterized.expand([("valid", True, True), ("invalid", False, False)])
+ def test_maps_validation_result(self, _name: str, valid: bool, expected: bool) -> None:
+ with patch.object(source_module, "validate_aiven_credentials", return_value=valid):
+ ok, error = AivenSource().validate_credentials(_config(), team_id=1)
+ assert ok is expected
+ assert (error is None) is expected
+
+
+class TestSourceForPipeline:
+ def test_passes_token_and_schema_through(self) -> None:
+ inputs = MagicMock()
+ inputs.schema_name = "invoices"
+ with patch.object(source_module, "aiven_source", return_value=MagicMock()) as aiven_source:
+ AivenSource().source_for_pipeline(_config(), inputs)
+ kwargs = aiven_source.call_args.kwargs
+ assert kwargs["api_token"] == "tok"
+ assert kwargs["endpoint"] == "invoices"
+ assert kwargs["logger"] is inputs.logger
+
+
+class TestDocsAndErrors:
+ def test_documented_tables_cover_every_endpoint(self) -> None:
+ # `lists_tables_without_credentials` is True, so the static catalog renders in public docs.
+ tables = AivenSource().get_documented_tables()
+ assert {t["name"] for t in tables} == set(ENDPOINTS)
+
+ def test_canonical_descriptions_key_on_real_endpoints(self) -> None:
+ canonical = AivenSource().get_canonical_descriptions()
+ assert set(canonical.keys()) <= set(AIVEN_ENDPOINTS.keys())
+ assert set(canonical.keys()) == set(ENDPOINTS)
+
+ def test_auth_errors_are_non_retryable(self) -> None:
+ keys = AivenSource().get_non_retryable_errors().keys()
+ assert any("401" in k for k in keys)
+ assert any("403" in k for k in keys)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.py b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.py
index d5b049fcc60b..1ca5387c7214 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
@@ -212,7 +212,7 @@ class AirtableSourceConfig(config.Config):
@config.config
class AivenSourceConfig(config.Config):
- pass
+ api_token: str
@config.config