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(warehouse_sources): add hetzner metrics, pricing and zones tables (#110747)

Tom Owerse1007b6938dd
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.md b/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.md
index 66992805b5de..1c9b131e358c 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.md
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.md
@@ -4018,11 +4018,11 @@ Today (17): `actions`, `certificates`, `datacenters`, `firewalls`, `floating_ips
Diffed against: <https://docs.hetzner.cloud/cloud.spec.json>
-- [ ] `GET /pricing` — lookup table of hourly/monthly prices per server type, volume, load balancer and location — the only way to cost the servers we already sync (high)
-- [ ] `GET /servers/{id}/metrics` — cpu, disk and network time series per server, the headline analytical data in the API (high)
-- [ ] `GET /zones` — DNS zones, now part of the Cloud API and not exposed at all today (medium)
+- [x] `GET /pricing` — lookup table of hourly/monthly prices per server type, volume, load balancer and location — the only way to cost the servers we already sync (high)
+- [x] `GET /servers/{id}/metrics` — cpu, disk and network time series per server, the headline analytical data in the API (high)
+- [x] `GET /zones` — DNS zones, now part of the Cloud API and not exposed at all today (medium)
- [ ] `GET /zones/{id_or_name}/rrsets` — DNS records per zone — the actual queryable rows behind zones (medium)
-- [ ] `GET /load_balancers/{id}/metrics` — connections, throughput and requests per load balancer for capacity analysis (medium)
+- [x] `GET /load_balancers/{id}/metrics` — connections, throughput and requests per load balancer for capacity analysis (medium)
Note: Note the payload's doc url (docs.hetzner.cloud) is an HTML docs site; the OpenAPI 3.1 spec lives at https://docs.hetzner.cloud/cloud.spec.json (docs.hetzner.cloud/spec.json 404s). Coverage of the plain list collections is essentially complete — every other GET collection in the spec is already synced.
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/hetzner/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/hetzner/canonical_descriptions.py
index ee091174a342..3c58ce35456b 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/hetzner/canonical_descriptions.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/hetzner/canonical_descriptions.py
@@ -220,4 +220,56 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
"architecture": "CPU architecture the ISO is compatible with.",
},
},
+ "zones": {
+ "description": "DNS zones managed in the project.",
+ "docs_url": _API_DOCS,
+ "columns": {
+ "id": "Unique identifier of the zone.",
+ "name": "Domain name of the zone.",
+ "created": "Point in time when the zone was created (ISO 8601).",
+ "mode": "Zone mode: primary (records managed in Hetzner) or secondary (transferred from primary nameservers).",
+ "ttl": "Default time to live (TTL) of the zone's records, in seconds.",
+ "status": "Status of the zone.",
+ "record_count": "Number of resource records within the zone.",
+ "registrar": "Registrar of the domain.",
+ "authoritative_nameservers": "Authoritative nameservers assigned to the zone and their delegation status.",
+ "primary_nameservers": "Primary nameservers the zone is transferred from. Only set for secondary zones.",
+ "labels": "User-defined key/value labels attached to the zone.",
+ },
+ },
+ "pricing": {
+ "description": "Current prices for every resource kind, in the project owner's currency and VAT rate. One row.",
+ "docs_url": _API_DOCS,
+ "columns": {
+ "currency": "ISO 4217 currency code the prices are expressed in.",
+ "vat_rate": "VAT rate used to calculate the gross prices.",
+ "server_types": "Hourly and monthly net/gross prices per server type and location.",
+ "load_balancer_types": "Hourly and monthly net/gross prices per load balancer type and location.",
+ "volume": "Monthly price per GB of volume storage.",
+ "primary_ips": "Hourly and monthly prices per primary IP type and location.",
+ "floating_ips": "Monthly prices per floating IP type and location.",
+ "image": "Monthly price per GB of image (snapshot) storage.",
+ "server_backup": "Backup price as a percentage of the server price.",
+ },
+ },
+ "server_metrics": {
+ "description": "CPU, disk and network time series per server, at a 5-minute resolution. The API keeps 30 days.",
+ "docs_url": _API_DOCS,
+ "columns": {
+ "server_id": "ID of the server the sample belongs to.",
+ "metric": "Time series name, e.g. cpu, disk.0.iops.read, disk.0.bandwidth.write, network.0.pps.in or network.0.bandwidth.out.",
+ "timestamp": "Point in time of the sample (UTC).",
+ "value": "Sample value. cpu is percent per vCPU (100 is one fully used vCPU), iops are operations/s, pps are packets/s, bandwidth is bytes/s.",
+ },
+ },
+ "load_balancer_metrics": {
+ "description": "Connection, request and bandwidth time series per load balancer, at a 5-minute resolution. The API keeps 30 days.",
+ "docs_url": _API_DOCS,
+ "columns": {
+ "load_balancer_id": "ID of the load balancer the sample belongs to.",
+ "metric": "Time series name: open_connections, connections_per_second, requests_per_second, bandwidth.in or bandwidth.out.",
+ "timestamp": "Point in time of the sample (UTC).",
+ "value": "Sample value: a count for open_connections, per second for the rates, bytes/s for bandwidth.",
+ },
+ },
}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/hetzner/hetzner.py b/products/warehouse_sources/backend/temporal/data_imports/sources/hetzner/hetzner.py
index 27ccfd0e24a9..d93f900fb3f7 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/hetzner/hetzner.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/hetzner/hetzner.py
@@ -1,18 +1,29 @@
+import math
import dataclasses
+from collections.abc import Iterator
+from datetime import UTC, datetime, timedelta
from typing import Any, Optional
+from requests import HTTPError
+
from products.warehouse_sources.backend.temporal.data_imports.sources.common.http import make_tracked_session
from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source import (
RESTAPIConfig,
rest_api_resource,
)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.auth import BearerTokenAuth
from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.paginators import (
PageNumberPaginator,
+ SinglePagePaginator,
)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.rest_client import RESTClient
from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
from products.warehouse_sources.backend.temporal.data_imports.sources.common.source_helpers import validate_via_probe
from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceResponse
-from products.warehouse_sources.backend.temporal.data_imports.sources.hetzner.settings import HETZNER_ENDPOINTS
+from products.warehouse_sources.backend.temporal.data_imports.sources.hetzner.settings import (
+ HETZNER_ENDPOINTS,
+ HETZNER_METRICS_ENDPOINTS,
+)
# Single global base URL — Hetzner Cloud has no regional hosts.
HETZNER_BASE_URL = "https://api.hetzner.cloud/v1"
@@ -24,8 +35,17 @@ PAGE_SIZE = 50
# Hetzner list endpoints are 1-indexed.
FIRST_PAGE = 1
+# Metrics: a fixed step keeps sample timestamps on the same grid every run, so a re-read sample
+# merges onto its existing row instead of landing beside it. The API caps a series at 500 samples
+# per request, so each request covers at most 499 steps.
+METRICS_STEP_SECONDS = 300
+METRICS_MAX_SAMPLES = 500
+# The API keeps 30 days of metrics; the margin keeps the oldest window inside it despite clock skew.
+METRICS_RETENTION = timedelta(days=30) - timedelta(hours=1)
+REQUEST_TIMEOUT = (10, 60)
+
[email protected](frozen=True)
class HetznerResumeConfig:
# Page number to fetch first on resume. The framework checkpoints the NEXT page after a page has
# been yielded, so a crash mid-page resumes onto that in-flight page and re-reads it rather than
@@ -35,12 +55,25 @@ class HetznerResumeConfig:
page: int = FIRST_PAGE
[email protected](frozen=True)
+class MetricsWindow:
+ start: int
+ end: int
+
+
def _non_secret_headers() -> dict[str, str]:
# Auth (Bearer) is supplied via the framework auth config so its value is redacted from logs and
# raised error messages; only the non-secret Accept header is set here.
return {"Accept": "application/json"}
+def _list_paginator() -> PageNumberPaginator:
+ # Page-number pagination; `meta.pagination.last_page` is the TOTAL number of pages, so the
+ # paginator stops after the last page instead of paying one extra empty-page request.
+ # stop_after_empty_page (default) is the fallback when a response omits the total.
+ return PageNumberPaginator(base_page=FIRST_PAGE, page_param="page", total_path="meta.pagination.last_page")
+
+
def hetzner_source(
api_token: str,
endpoint: str,
@@ -51,7 +84,7 @@ def hetzner_source(
) -> SourceResponse:
config = HETZNER_ENDPOINTS[endpoint]
- params: dict[str, Any] = {"per_page": PAGE_SIZE}
+ params: dict[str, Any] = {"per_page": PAGE_SIZE} if config.paginated else {}
if config.sort is not None:
params["sort"] = config.sort
@@ -60,14 +93,8 @@ def hetzner_source(
"base_url": HETZNER_BASE_URL,
"headers": _non_secret_headers(),
"auth": {"type": "bearer", "token": api_token},
- # Page-number pagination; `meta.pagination.last_page` is the TOTAL number of pages, so the
- # paginator stops after the last page instead of paying one extra empty-page request.
- # stop_after_empty_page (default) is the fallback when a response omits the total.
- "paginator": PageNumberPaginator(
- base_page=FIRST_PAGE,
- page_param="page",
- total_path="meta.pagination.last_page",
- ),
+ "paginator": _list_paginator() if config.paginated else SinglePagePaginator(),
+ "request_timeout": REQUEST_TIMEOUT,
# Disable redirect following so a 3xx can never replay the Authorization header to another
# host — the SSRF guard the hand-rolled transport used.
"allow_redirects": False,
@@ -124,6 +151,145 @@ def hetzner_source(
)
+def _align_up(epoch: int) -> int:
+ return -(-epoch // METRICS_STEP_SECONDS) * METRICS_STEP_SECONDS
+
+
+def _to_epoch(value: Any) -> Optional[int]:
+ if isinstance(value, str):
+ try:
+ value = datetime.fromisoformat(value)
+ except ValueError:
+ return None
+ if not isinstance(value, datetime):
+ return None
+ if value.tzinfo is None:
+ value = value.replace(tzinfo=UTC)
+ return int(value.timestamp())
+
+
+def _to_rfc3339(epoch: int) -> str:
+ return datetime.fromtimestamp(epoch, tz=UTC).strftime("%Y-%m-%dT%H:%M:%SZ")
+
+
+def _metric_windows(start: int, end: int) -> Iterator[MetricsWindow]:
+ span = METRICS_STEP_SECONDS * (METRICS_MAX_SAMPLES - 1)
+ while start <= end:
+ window_end = min(start + span, end)
+ yield MetricsWindow(start=start, end=window_end)
+ # Windows include both ends, so the next one starts a step later to not repeat a sample.
+ start = window_end + METRICS_STEP_SECONDS
+
+
+def _metrics_start(now: int, created: Any, last_value: Any) -> int:
+ # Never ask for samples older than retention or than the resource itself. On incremental runs
+ # the watermark sample is read again, because the newest sample can still change.
+ candidates = [now - int(METRICS_RETENTION.total_seconds())]
+ for value in (created, last_value):
+ epoch = _to_epoch(value)
+ if epoch is not None:
+ candidates.append(epoch)
+ return _align_up(max(candidates))
+
+
+def _to_float(value: Any) -> Optional[float]:
+ try:
+ number = float(value)
+ except (TypeError, ValueError):
+ return None
+ return number if math.isfinite(number) else None
+
+
+def _metric_rows(parent_id_column: str, parent_id: Any, metrics: dict[str, Any]) -> list[dict[str, Any]]:
+ # The API returns one `{series: {"values": [[epoch, "value"], ...]}}` map per request; flatten it
+ # to one row per series sample.
+ return [
+ {
+ parent_id_column: parent_id,
+ "metric": series,
+ "timestamp": datetime.fromtimestamp(sample[0], tz=UTC),
+ "value": _to_float(sample[1]),
+ }
+ for series, data in (metrics.get("time_series") or {}).items()
+ for sample in (data or {}).get("values") or []
+ ]
+
+
+def hetzner_metrics_source(
+ api_token: str,
+ endpoint: str,
+ resumable_source_manager: ResumableSourceManager[HetznerResumeConfig],
+ db_incremental_field_last_value: Optional[Any] = None,
+) -> SourceResponse:
+ config = HETZNER_METRICS_ENDPOINTS[endpoint]
+ parent = HETZNER_ENDPOINTS[config.parent]
+
+ def items() -> Iterator[list[dict[str, Any]]]:
+ client = RESTClient(
+ base_url=HETZNER_BASE_URL,
+ headers=_non_secret_headers(),
+ auth=BearerTokenAuth(api_token),
+ allow_redirects=False,
+ request_timeout=REQUEST_TIMEOUT,
+ )
+ now = int(datetime.now(UTC).timestamp())
+ end = now - now % METRICS_STEP_SECONDS
+ parent_params = {"per_page": PAGE_SIZE, "sort": parent.sort}
+
+ for resources in client.paginate(
+ parent.path, params=parent_params, paginator=_list_paginator(), data_selector=parent.response_key
+ ):
+ for resource in resources:
+ start = _metrics_start(now, resource.get("created"), db_incremental_field_last_value)
+ for window in _metric_windows(start, end):
+ params = {
+ "type": config.metric_types,
+ "start": _to_rfc3339(window.start),
+ "end": _to_rfc3339(window.end),
+ "step": METRICS_STEP_SECONDS,
+ }
+ try:
+ pages = list(
+ client.paginate(
+ f"{parent.path}/{resource['id']}/metrics",
+ params=params,
+ paginator=SinglePagePaginator(),
+ data_selector="metrics",
+ )
+ )
+ except HTTPError as e:
+ # The resource was deleted after the parent list was read.
+ if e.response is not None and e.response.status_code == 404:
+ break
+ raise
+
+ rows = [
+ row
+ for page in pages
+ for metrics in page
+ for row in _metric_rows(config.parent_id_column, resource["id"], metrics)
+ ]
+ if rows:
+ yield rows
+ else:
+ resumable_source_manager.safe_point()
+
+ return SourceResponse(
+ name=endpoint,
+ items=items,
+ primary_keys=[config.parent_id_column, "metric", "timestamp"],
+ # Rows arrive oldest-first per resource, not across resources, so desc mode keeps the
+ # pipeline from checkpointing one resource's newest sample as the watermark for all of them.
+ # The watermark then commits once, at the end of a successful run.
+ sort_mode="desc",
+ partition_count=1,
+ partition_size=1,
+ partition_mode="datetime",
+ partition_format="week",
+ partition_keys=["timestamp"],
+ )
+
+
def validate_credentials(api_token: str) -> tuple[bool, str | None]:
"""One cheap authenticated probe to confirm the token is genuine. Hetzner project tokens grant
read access to every resource in the project (a read-only token still reads all of them), so
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/hetzner/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/hetzner/settings.py
index b3daf5391647..99ad5877b2d9 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/hetzner/settings.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/hetzner/settings.py
@@ -1,10 +1,10 @@
from dataclasses import dataclass, field
from typing import Optional
-from products.warehouse_sources.backend.types import IncrementalField
+from products.warehouse_sources.backend.types import IncrementalField, IncrementalFieldType
-@dataclass
+@dataclass(frozen=True)
class HetznerEndpointConfig:
name: str
path: str
@@ -20,6 +20,20 @@ class HetznerEndpointConfig:
sort: Optional[str] = None
primary_keys: list[str] = field(default_factory=lambda: ["id"])
should_sync_default: bool = True
+ # False for single-object endpoints (e.g. /pricing) that ignore `page` and carry no
+ # `meta.pagination`, so a page-number paginator would request page 2 forever.
+ paginated: bool = True
+
+
+@dataclass(frozen=True)
+class HetznerMetricsEndpointConfig:
+ name: str
+ # Key into HETZNER_ENDPOINTS for the list whose resources the metrics fan out over.
+ parent: str
+ # Column carrying the parent resource id on every metric row.
+ parent_id_column: str
+ # Comma-separated `type` values; one request returns every series of these types.
+ metric_types: str
# The Hetzner Cloud API exposes no server-side timestamp filter on any list endpoint (no
@@ -140,10 +154,51 @@ HETZNER_ENDPOINTS: dict[str, HetznerEndpointConfig] = {
path="/isos",
response_key="isos",
),
+ "zones": HetznerEndpointConfig(
+ name="zones",
+ path="/zones",
+ response_key="zones",
+ partition_key="created",
+ sort="id:asc",
+ ),
+ # A single object (currency, VAT rate and per-location prices for every resource kind), so it
+ # lands as one row keyed by its currency.
+ "pricing": HetznerEndpointConfig(
+ name="pricing",
+ path="/pricing",
+ response_key="pricing",
+ primary_keys=["currency"],
+ paginated=False,
+ ),
+}
+
+# Time series per resource. Unlike the list endpoints these take a required `start`/`end` window,
+# which is a real server-side filter, so they support incremental sync on `timestamp`.
+HETZNER_METRICS_ENDPOINTS: dict[str, HetznerMetricsEndpointConfig] = {
+ "server_metrics": HetznerMetricsEndpointConfig(
+ name="server_metrics",
+ parent="servers",
+ parent_id_column="server_id",
+ metric_types="cpu,disk,network",
+ ),
+ "load_balancer_metrics": HetznerMetricsEndpointConfig(
+ name="load_balancer_metrics",
+ parent="load_balancers",
+ parent_id_column="load_balancer_id",
+ metric_types="open_connections,connections_per_second,requests_per_second,bandwidth",
+ ),
}
-ENDPOINTS = tuple(HETZNER_ENDPOINTS.keys())
+ENDPOINTS = (*HETZNER_ENDPOINTS.keys(), *HETZNER_METRICS_ENDPOINTS.keys())
+
+_TIMESTAMP_FIELD = IncrementalField(
+ label="timestamp",
+ type=IncrementalFieldType.DateTime,
+ field="timestamp",
+ field_type=IncrementalFieldType.DateTime,
+)
-# Hetzner has no server-side timestamp filter, so no endpoint advertises incremental fields. Kept
-# for parity with the other sources and so `get_schemas` can read a single source of truth.
-INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {name: [] for name in HETZNER_ENDPOINTS}
+INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {
+ **{name: [] for name in HETZNER_ENDPOINTS},
+ **{name: [_TIMESTAMP_FIELD] for name in HETZNER_METRICS_ENDPOINTS},
+}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/hetzner/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/hetzner/source.py
index 4ad3306d7b7e..ea13b43ccce8 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/hetzner/source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/hetzner/source.py
@@ -23,11 +23,13 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.generated_
)
from products.warehouse_sources.backend.temporal.data_imports.sources.hetzner.hetzner import (
HetznerResumeConfig,
+ hetzner_metrics_source,
hetzner_source,
validate_credentials as validate_hetzner_credentials,
)
from products.warehouse_sources.backend.temporal.data_imports.sources.hetzner.settings import (
ENDPOINTS,
+ HETZNER_METRICS_ENDPOINTS,
INCREMENTAL_FIELDS,
)
from products.warehouse_sources.backend.types import ExternalDataSourceType
@@ -99,11 +101,11 @@ Create a token under **Security > API tokens** in the [Hetzner Cloud Console](ht
force_refresh: bool = False,
api_version: str | None = None,
) -> list[SourceSchema]:
- # The Hetzner Cloud API has no server-side timestamp filter on any list endpoint, so every
- # table is full refresh only — no incremental, no append (append would re-append the whole
- # list every run and materialize duplicates). INCREMENTAL_FIELDS is empty for every endpoint,
- # so build_endpoint_schemas yields supports_incremental/supports_append=False for all.
- return build_endpoint_schemas(ENDPOINTS, INCREMENTAL_FIELDS, names)
+ # The Hetzner Cloud API has no server-side timestamp filter on any list endpoint, so those
+ # tables are full refresh only — no incremental, no append (append would re-append the whole
+ # list every run and materialize duplicates). Only the metrics tables take a time window.
+ # They are merge-only, because each run re-reads the latest sample, which append would duplicate.
+ return build_endpoint_schemas(ENDPOINTS, INCREMENTAL_FIELDS, names, merge_only=HETZNER_METRICS_ENDPOINTS.keys())
def validate_credentials(
self,
@@ -123,11 +125,20 @@ Create a token under **Security > API tokens** in the [Hetzner Cloud Console](ht
resumable_source_manager: ResumableSourceManager[HetznerResumeConfig],
inputs: SourceInputs,
) -> SourceResponse:
+ if inputs.schema_name in HETZNER_METRICS_ENDPOINTS:
+ return hetzner_metrics_source(
+ api_token=config.api_token,
+ endpoint=inputs.schema_name,
+ resumable_source_manager=resumable_source_manager,
+ db_incremental_field_last_value=inputs.db_incremental_field_last_value
+ if inputs.should_use_incremental_field
+ else None,
+ )
return hetzner_source(
api_token=config.api_token,
endpoint=inputs.schema_name,
team_id=inputs.team_id,
job_id=inputs.job_id,
resumable_source_manager=resumable_source_manager,
- db_incremental_field_last_value=None, # every Hetzner endpoint is full refresh
+ db_incremental_field_last_value=None, # every Hetzner list endpoint is full refresh
)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/hetzner/tests/test_hetzner.py b/products/warehouse_sources/backend/temporal/data_imports/sources/hetzner/tests/test_hetzner.py
index ba89595ecf84..99b54920df93 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/hetzner/tests/test_hetzner.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/hetzner/tests/test_hetzner.py
@@ -1,7 +1,9 @@
import json
+from datetime import UTC, datetime, timedelta
from typing import Any
import pytest
+import time_machine
from unittest import mock
import requests
@@ -13,7 +15,9 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common.res
)
from products.warehouse_sources.backend.temporal.data_imports.sources.hetzner.hetzner import (
HETZNER_BASE_URL,
+ METRICS_RETENTION,
HetznerResumeConfig,
+ hetzner_metrics_source,
hetzner_source,
validate_credentials,
)
@@ -169,6 +173,23 @@ class TestPagination:
assert params[0]["sort"] == "id:asc"
+ @mock.patch(CLIENT_SESSION_PATCH)
+ def test_pricing_is_one_row_from_one_request(self, MockSession) -> None:
+ # /pricing ignores `page` and has no meta.pagination; a page-number paginator would request
+ # page 2 forever and repeat the same row.
+ session = MockSession.return_value
+ response = Response()
+ response.status_code = 200
+ response._content = json.dumps({"pricing": {"currency": "EUR", "vat_rate": "19.00"}}).encode()
+ response.url = f"{HETZNER_BASE_URL}/pricing"
+ params = _wire(session, [response])
+
+ rows = _rows(_source("pricing", _make_manager()))
+
+ assert rows == [{"currency": "EUR", "vat_rate": "19.00"}]
+ assert session.send.call_count == 1
+ assert "page" not in params[0]
+
@mock.patch(CLIENT_SESSION_PATCH)
def test_catalog_endpoint_omits_sort(self, MockSession) -> None:
# server_types has no verified sort support, so we must not send a sort param that could 400.
@@ -180,6 +201,155 @@ class TestPagination:
assert "sort" not in params[0]
+NOW = datetime(2026, 3, 1, tzinfo=UTC)
+
+
+def _json_response(body: dict[str, Any], *, status: int = 200, reason: str = "") -> Response:
+ resp = Response()
+ resp.status_code = status
+ resp._content = json.dumps(body).encode()
+ resp.url = HETZNER_BASE_URL
+ resp.reason = reason
+ return resp
+
+
+def _metrics(time_series: dict[str, Any]) -> Response:
+ return _json_response({"metrics": {"start": "", "end": "", "step": 300, "time_series": time_series}})
+
+
+def _wire_requests(session: mock.MagicMock, responses: list[Response]) -> list[tuple[str, dict[str, Any]]]:
+ session.headers = {}
+ sent: list[tuple[str, dict[str, Any]]] = []
+
+ def _prepare(request: Any) -> mock.MagicMock:
+ sent.append((request.url, dict(request.params or {})))
+ return mock.MagicMock()
+
+ session.prepare_request.side_effect = _prepare
+ session.send.side_effect = responses
+ return sent
+
+
+def _rfc3339(value: datetime) -> str:
+ return value.strftime("%Y-%m-%dT%H:%M:%SZ")
+
+
+def _metrics_source(endpoint: str, manager: mock.MagicMock, last_value: Any = None):
+ return hetzner_metrics_source(
+ api_token="token",
+ endpoint=endpoint,
+ resumable_source_manager=manager,
+ db_incremental_field_last_value=last_value,
+ )
+
+
+class TestMetrics:
+ @pytest.fixture(autouse=True)
+ def _frozen_now(self):
+ with time_machine.travel(NOW, tick=False):
+ yield
+
+ @parameterized.expand(
+ [
+ ("server_metrics", "servers", "server_id", "cpu,disk,network"),
+ (
+ "load_balancer_metrics",
+ "load_balancers",
+ "load_balancer_id",
+ "open_connections,connections_per_second,requests_per_second,bandwidth",
+ ),
+ ]
+ )
+ @mock.patch(CLIENT_SESSION_PATCH)
+ def test_flattens_series_into_one_row_per_sample(
+ self, endpoint: str, parent: str, id_column: str, types: str, MockSession
+ ) -> None:
+ session = MockSession.return_value
+ created = NOW - timedelta(minutes=58)
+ sample = (NOW - timedelta(minutes=5)).timestamp()
+ sent = _wire_requests(
+ session,
+ [
+ _page([{"id": 7, "created": created.isoformat()}], endpoint=parent),
+ _metrics(
+ {"a": {"values": [[sample, "12.5"]]}, "b": {"values": [[sample, "3"], [sample + 300, "NaN"]]}}
+ ),
+ ],
+ )
+
+ rows = _rows(_metrics_source(endpoint, _make_manager()))
+
+ assert rows == [
+ {id_column: 7, "metric": "a", "timestamp": NOW - timedelta(minutes=5), "value": 12.5},
+ {id_column: 7, "metric": "b", "timestamp": NOW - timedelta(minutes=5), "value": 3.0},
+ {id_column: 7, "metric": "b", "timestamp": NOW, "value": None},
+ ]
+ url, params = sent[1]
+ assert url == f"{HETZNER_BASE_URL}/{parent}/7/metrics"
+ # A start before the resource existed would only fetch empty windows; it rounds up to the grid.
+ assert params == {
+ "type": types,
+ "start": _rfc3339(NOW - timedelta(minutes=55)),
+ "end": _rfc3339(NOW),
+ "step": 300,
+ }
+
+ @mock.patch(CLIENT_SESSION_PATCH)
+ def test_full_refresh_walks_retention_in_contiguous_windows(self, MockSession) -> None:
+ session = MockSession.return_value
+ window_count = 18 # 8629 five-minute samples in the retention span, 500 per request
+ sent = _wire_requests(
+ session,
+ [_page([{"id": 1, "created": "2020-01-01T00:00:00+00:00"}])] + [_metrics({}) for _ in range(window_count)],
+ )
+ manager = _make_manager()
+
+ rows = _rows(_metrics_source("server_metrics", manager))
+
+ assert rows == []
+ windows = [params for _, params in sent[1:]]
+ assert len(windows) == window_count
+ assert windows[0]["start"] == _rfc3339(NOW - METRICS_RETENTION)
+ assert windows[-1]["end"] == _rfc3339(NOW)
+ for previous, following in zip(windows, windows[1:]):
+ gap = datetime.fromisoformat(following["start"]) - datetime.fromisoformat(previous["end"])
+ assert gap == timedelta(seconds=300)
+ # Empty windows still give the pipeline a chance to hand the run off during a shutdown.
+ assert manager.safe_point.call_count == window_count
+
+ @mock.patch(CLIENT_SESSION_PATCH)
+ def test_incremental_starts_at_the_watermark(self, MockSession) -> None:
+ session = MockSession.return_value
+ watermark = NOW - timedelta(minutes=10)
+ sent = _wire_requests(
+ session,
+ [_page([{"id": 1, "created": "2020-01-01T00:00:00+00:00"}]), _metrics({})],
+ )
+
+ _rows(_metrics_source("server_metrics", _make_manager(), last_value=watermark))
+
+ assert len(sent) == 2
+ assert sent[1][1]["start"] == _rfc3339(watermark)
+
+ @mock.patch(CLIENT_SESSION_PATCH)
+ def test_resource_deleted_mid_sync_is_skipped(self, MockSession) -> None:
+ session = MockSession.return_value
+ recent = (NOW - timedelta(minutes=30)).isoformat()
+ sample = NOW.timestamp()
+ _wire_requests(
+ session,
+ [
+ _page([{"id": 1, "created": recent}, {"id": 2, "created": recent}]),
+ _json_response({"error": {"code": "not_found"}}, status=404, reason="Not Found"),
+ _metrics({"cpu": {"values": [[sample, "1"]]}}),
+ ],
+ )
+
+ rows = _rows(_metrics_source("server_metrics", _make_manager()))
+
+ assert [(r["server_id"], r["value"]) for r in rows] == [(2, 1.0)]
+
+
class TestRetries:
@parameterized.expand([("rate_limited", 429), ("server_error", 503)])
@mock.patch(SLEEP_PATCH, lambda *_: None)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/hetzner/tests/test_hetzner_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/hetzner/tests/test_hetzner_source.py
index 3e9a8867fe0b..46334f411081 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/hetzner/tests/test_hetzner_source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/hetzner/tests/test_hetzner_source.py
@@ -10,7 +10,10 @@ from products.warehouse_sources.backend.facade.source_config import (
from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.hetzner import (
HetznerSourceConfig,
)
-from products.warehouse_sources.backend.temporal.data_imports.sources.hetzner.settings import ENDPOINTS
+from products.warehouse_sources.backend.temporal.data_imports.sources.hetzner.settings import (
+ ENDPOINTS,
+ HETZNER_METRICS_ENDPOINTS,
+)
from products.warehouse_sources.backend.temporal.data_imports.sources.hetzner.source import HetznerSource
@@ -34,15 +37,17 @@ class TestHetznerSource:
assert field.required is True
assert field.secret is True
- def test_all_endpoints_are_full_refresh_only(self) -> None:
- # Hetzner exposes no server-side timestamp filter, so no table may advertise incremental or
- # append — otherwise the picker offers a mode that either syncs nothing new or duplicates rows.
+ def test_only_metrics_endpoints_are_incremental(self) -> None:
+ # List endpoints have no server-side timestamp filter, so they must not advertise incremental
+ # or append. Metrics take a start/end window, but re-read their newest sample each run, so
+ # they are merge-only: append would duplicate that sample.
schemas = self.source.get_schemas(mock.MagicMock(), self.team_id)
assert {s.name for s in schemas} == set(ENDPOINTS)
for schema in schemas:
- assert schema.supports_incremental is False, schema.name
+ is_metrics = schema.name in HETZNER_METRICS_ENDPOINTS
+ assert schema.supports_incremental is is_metrics, schema.name
assert schema.supports_append is False, schema.name
- assert schema.incremental_fields == []
+ assert [f["field"] for f in schema.incremental_fields] == (["timestamp"] if is_metrics else [])
@parameterized.expand(
[
@@ -70,13 +75,20 @@ class TestHetznerSource:
non_retryable = self.source.get_non_retryable_errors()
assert not any(key in observed_error for key in non_retryable)
- def test_source_for_pipeline_plumbs_schema_name(self) -> None:
+ @parameterized.expand(
+ [
+ ("list", "servers", ["id"]),
+ ("server_metrics", "server_metrics", ["server_id", "metric", "timestamp"]),
+ ("load_balancer_metrics", "load_balancer_metrics", ["load_balancer_id", "metric", "timestamp"]),
+ ]
+ )
+ def test_source_for_pipeline_routes_schema(self, _name: str, schema_name: str, primary_keys: list[str]) -> None:
config = HetznerSourceConfig(api_token="tok")
inputs = mock.MagicMock()
- inputs.schema_name = "servers"
+ inputs.schema_name = schema_name
response = self.source.source_for_pipeline(config, mock.MagicMock(), inputs)
- assert response.name == "servers"
- assert response.primary_keys == ["id"]
+ assert response.name == schema_name
+ assert response.primary_keys == primary_keys
def test_documented_tables_published_for_docs(self) -> None:
# lists_tables_without_credentials must stay on so the public docs render the table catalog.