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): implement the Metronome data warehouse source (#89549)

Tom Owersc3f4941d797c
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 0fc1f325b9bb..99b8f094f93e 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
@@ -455,6 +455,7 @@ the row lists both.
| metaplane | HTTP | requests | ✅ |
| meteostat | HTTP | requests | ✅ |
| metorial | HTTP | requests | ✅ |
+| metronome | HTTP | requests + `rest_source.RESTClient` | ✅ |
| microsoft_clarity | HTTP | requests | ✅ |
| mighty_networks | HTTP | requests + `rest_source.RESTClient` | ✅ |
| mistral_ai | HTTP | requests | ✅ |
@@ -1172,7 +1173,6 @@ doesn't conflict with concurrent PRs.
- merge
- metricool
- metriport
-- metronome
- mews
- mezmo
- microsoft_365_usage_reports
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/metronome.py b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/metronome.py
index 43572e4957dd..307e09e93f9c 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/metronome.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/metronome.py
@@ -6,4 +6,4 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common imp
@config.config
class MetronomeSourceConfig(config.Config):
- pass
+ api_key: str
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/metronome/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/metronome/canonical_descriptions.py
new file mode 100644
index 000000000000..7abac689b54c
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/metronome/canonical_descriptions.py
@@ -0,0 +1,169 @@
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (
+ CanonicalDescriptions,
+)
+
+CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
+ "customers": {
+ "description": "The companies or accounts you bill. Usage events, contracts and invoices all hang off a customer. Only active customers are synced; Metronome's list endpoint returns archived customers only as a separate, exclusive result set.",
+ "docs_url": "https://docs.metronome.com/api-reference/customers/list-customers",
+ "columns": {
+ "id": "The Metronome id of the customer.",
+ "external_id": "Your own id for the customer. Deprecated by Metronome in favor of ingest aliases.",
+ "ingest_aliases": "Alternate ids that usage events may use to address this customer.",
+ "name": "The customer's display name.",
+ "customer_config": "Billing-provider configuration for the customer, including its Salesforce account id.",
+ "custom_fields": "Arbitrary key/value pairs set on the customer by your account.",
+ "created_at": "When the customer was created.",
+ "updated_at": "When the customer was last modified.",
+ "archived_at": "When the customer was archived. Null while the customer is active.",
+ "current_billable_status": "Whether the customer is currently billable, and when that status took effect. Only populated when your account is configured for it.",
+ },
+ },
+ "contracts": {
+ "description": "Contracts define what a customer is charged: the rate card in force, plus its commits, credits, overrides, discounts and scheduled charges. Fetched per customer from the v2 endpoint.",
+ "docs_url": "https://docs.metronome.com/api-reference/contracts/list-customer-contracts-v2",
+ "columns": {
+ "id": "The contract's id.",
+ "customer_id": "The customer the contract belongs to.",
+ "name": "The contract's display name.",
+ "starting_at": "When the contract takes effect.",
+ "ending_before": "When the contract stops applying. Null for an open-ended contract.",
+ "created_at": "When the contract was created.",
+ "created_by": "Who created the contract.",
+ "archived_at": "When the contract was archived. Null while it is active.",
+ "rate_card_id": "The rate card the contract prices against.",
+ "package_id": "The package the contract was created from, if any.",
+ "commits": "Prepaid or postpaid commitments on the contract. Truncated when `has_more` says so.",
+ "credits": "Credits granted on the contract. Truncated when `has_more` says so.",
+ "overrides": "Contract-specific rate overrides applied on top of the rate card.",
+ "discounts": "Negotiated discounts applied to the contract.",
+ "scheduled_charges": "Fixed charges billed on a schedule rather than from usage.",
+ "transitions": "Renewals and supersessions linking this contract to others.",
+ "subscriptions": "Recurring subscription charges on the contract.",
+ "recurring_commits": "Commitments that recur each billing period.",
+ "recurring_credits": "Credits that recur each billing period.",
+ "usage_filter": "Filter restricting which usage the contract bills.",
+ "usage_statement_schedule": "How often usage statements are generated for the contract.",
+ "total_contract_value": "The contract's total value.",
+ "net_payment_terms_days": "Days the customer has to pay an invoice under this contract.",
+ "priority": "Ordering used when several contracts could bill the same usage.",
+ "custom_fields": "Arbitrary key/value pairs set on the contract by your account.",
+ "has_more": "Flags whether `commits` or `credits` were truncated in this response.",
+ },
+ },
+ "invoices": {
+ "description": "Invoices issued to a customer, with their line items. Fetched per customer; Metronome has no account-wide invoice list endpoint.",
+ "docs_url": "https://docs.metronome.com/api-reference/invoices/list-invoices",
+ "columns": {
+ "id": "The invoice's id.",
+ "customer_id": "The customer the invoice was issued to.",
+ "contract_id": "The contract the invoice bills against, if any.",
+ "amendment_id": "The contract amendment the invoice bills against, if any.",
+ "type": "The invoice type: usage, consolidated usage, or scheduled.",
+ "status": "Where the invoice is in its lifecycle, for example draft, finalized or void.",
+ "total": "The invoice total, in the invoice's credit type.",
+ "credit_type": "The currency or pricing unit the invoice is denominated in.",
+ "line_items": "The individual charges making up the invoice.",
+ "start_timestamp": "Start of the billing period the invoice covers.",
+ "end_timestamp": "End of the billing period the invoice covers.",
+ "issued_at": "When the invoice was issued.",
+ "created_at": "When the invoice record was created. Metronome only sets this on correction invoices.",
+ "external_invoice": "The matching invoice in your billing provider, when one has been synced.",
+ "net_payment_terms_days": "Days the customer has to pay this invoice.",
+ "correction_record": "Details of the invoice this one corrects, when it is a correction.",
+ "billable_status": "Whether the invoice is billable or was marked unbillable.",
+ "regenerated_from_invoice_id": "The invoice this one replaced, when it was regenerated.",
+ },
+ },
+ "products": {
+ "description": "Products are the billable things a rate card prices: usage, subscription, composite, fixed, or professional-services. Includes archived products.",
+ "docs_url": "https://docs.metronome.com/api-reference/products/list-products",
+ "columns": {
+ "id": "The product's id.",
+ "type": "The product type: USAGE, SUBSCRIPTION, COMPOSITE, FIXED or PRO_SERVICE.",
+ "initial": "The product's first version, including its name and billable metric.",
+ "current": "The product's version in effect now.",
+ "updates": "Every version of the product, in the order it was updated.",
+ "archived_at": "When the product was archived. Null while it is active.",
+ "custom_fields": "Arbitrary key/value pairs set on the product by your account.",
+ },
+ },
+ "rate_cards": {
+ "description": "Rate cards hold the prices charged for products. Contracts reference a rate card rather than carrying prices themselves. The rates on a card are fetched separately and are not part of this table.",
+ "docs_url": "https://docs.metronome.com/api-reference/rate-cards/list-rate-cards",
+ "columns": {
+ "id": "The rate card's id.",
+ "name": "The rate card's display name.",
+ "description": "The rate card's description.",
+ "created_at": "When the rate card was created.",
+ "created_by": "Who created the rate card.",
+ "fiat_credit_type": "The currency the rate card's fiat prices are denominated in.",
+ "credit_type_conversions": "Conversion rates between the card's pricing units and its fiat currency.",
+ "aliases": "Alternate names the rate card can be referenced by, with the window each applies in.",
+ "custom_fields": "Arbitrary key/value pairs set on the rate card by your account.",
+ },
+ },
+ "packages": {
+ "description": "Packages are reusable contract templates: a rate card plus the commits, credits, overrides and charges a new contract should start with. Includes archived packages.",
+ "docs_url": "https://docs.metronome.com/api-reference/list-all-packages",
+ "columns": {
+ "id": "The package's id.",
+ "name": "The package's display name.",
+ "rate_card_id": "The rate card contracts created from this package price against.",
+ "duration": "How long a contract created from this package runs for.",
+ "commits": "Commitments a contract created from this package starts with.",
+ "credits": "Credits a contract created from this package starts with.",
+ "overrides": "Rate overrides applied on top of the rate card.",
+ "scheduled_charges": "Fixed charges billed on a schedule.",
+ "subscriptions": "Recurring subscription charges included in the package.",
+ "recurring_commits": "Commitments that recur each billing period.",
+ "recurring_credits": "Credits that recur each billing period.",
+ "net_payment_terms_days": "Days a customer has to pay an invoice under contracts from this package.",
+ "usage_statement_schedule": "How often usage statements are generated.",
+ "created_at": "When the package was created.",
+ "created_by": "Who created the package.",
+ "archived_at": "When the package was archived. Null while it is active.",
+ "uniqueness_key": "Idempotency key supplied when the package was created.",
+ },
+ },
+ "billable_metrics": {
+ "description": "Billable metrics turn raw usage events into the quantities products charge for, by filtering events and aggregating a property. Includes archived metrics.",
+ "docs_url": "https://docs.metronome.com/api-reference/billable-metrics/list-all-billable-metrics",
+ "columns": {
+ "id": "The billable metric's id.",
+ "name": "The billable metric's display name.",
+ "event_type_filter": "Which usage event types the metric counts.",
+ "property_filters": "Event property conditions a usage event must meet to be counted.",
+ "aggregation_type": "How matching events are aggregated, for example count, sum, max or unique.",
+ "aggregation_key": "The event property that is aggregated. Not set for a count.",
+ "group_keys": "Event properties the metric is broken down by.",
+ "sql": "The SQL definition, for metrics defined in SQL rather than with filters.",
+ "archived_at": "When the metric was archived. Null while it is active.",
+ "custom_fields": "Arbitrary key/value pairs set on the metric by your account.",
+ },
+ },
+ "pricing_units": {
+ "description": "The units prices and balances are denominated in: fiat currencies plus any custom credit types your account defines.",
+ "docs_url": "https://docs.metronome.com/api-reference/settings/list-pricing-units",
+ "columns": {
+ "id": "The pricing unit's id.",
+ "name": "The pricing unit's display name, for example USD or a custom credit name.",
+ "is_currency": "Whether the unit is a fiat currency rather than a custom credit type.",
+ },
+ },
+ "audit_logs": {
+ "description": "One row per change made through the Metronome app or API: who did it, to what, and whether it succeeded. This is the only Metronome endpoint with a server-side time filter, so it is the only table that syncs incrementally.",
+ "docs_url": "https://docs.metronome.com/api-reference/security/get-audit-logs",
+ "columns": {
+ "id": "The audit log entry's id.",
+ "timestamp": "When the action happened.",
+ "actor": "Who performed the action, whether a user or an API token.",
+ "request": "The API request that performed the action, including its id and user agent.",
+ "resource_type": "The kind of object acted on, for example customer or contract.",
+ "resource_id": "The id of the object acted on.",
+ "action": "What was done to the resource.",
+ "status": "Whether the action succeeded, failed, or is still pending.",
+ "description": "A readable summary of the action.",
+ },
+ },
+}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/metronome/metronome.py b/products/warehouse_sources/backend/temporal/data_imports/sources/metronome/metronome.py
new file mode 100644
index 000000000000..6f51430350bf
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/metronome/metronome.py
@@ -0,0 +1,356 @@
+import dataclasses
+from collections.abc import Callable, Iterable, Iterator
+from typing import Any, Optional, cast
+
+from requests import Request, Response
+
+from posthog.dataclasses import frozen
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.datetime_utils import (
+ coerce_datetime_to_utc,
+)
+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,
+ RESTClient,
+ rest_api_resource,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.config_setup import create_auth
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.fanout import (
+ build_dependent_resource,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.paginators import (
+ BasePaginator,
+ JSONResponseCursorPaginator,
+ SinglePagePaginator,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.typing import (
+ ClientConfig,
+ Endpoint,
+ EndpointResource,
+ IncrementalConfig,
+)
+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.metronome.settings import (
+ CURSOR_PARAM,
+ CURSOR_PATH,
+ DATA_SELECTOR,
+ METRONOME_BASE_URL,
+ METRONOME_ENDPOINTS,
+ MetronomeEndpointConfig,
+)
+
+REQUEST_TIMEOUT_SECONDS = 30.0
+
+# Metronome accepts RFC 3339 timestamps and returns them in this shape.
+RFC_3339_FORMAT = "%Y-%m-%dT%H:%M:%SZ"
+
+# Lower bound for a first incremental run — earlier than any Metronome account.
+EPOCH_RFC_3339 = "1970-01-01T00:00:00Z"
+
+
+@frozen
+class MetronomeResumeConfig:
+ """Paginator checkpoint — the `next_page` cursor of the page we have not yet fetched."""
+
+ next_page: str
+
+
+class MetronomeCursorPaginator(JSONResponseCursorPaginator):
+ """Follows Metronome's `next_page` cursor, handling two vendor behaviours.
+
+ `GET /v1/auditLogs` returns a cursor even for an empty page — the docs say it is always
+ returned "to support ongoing log retrieval" — so stopping only when the cursor goes null
+ never terminates. An empty page means the collection is exhausted on every Metronome list
+ endpoint, so stop there too.
+
+ That same endpoint rejects its `starting_on` window when a cursor is also sent, so the
+ window only rides the request that has no cursor on it.
+ """
+
+ def __init__(self, first_page_only_params: tuple[str, ...] = ()) -> None:
+ super().__init__(cursor_path=CURSOR_PATH, cursor_param=CURSOR_PARAM)
+ self._first_page_only_params = first_page_only_params
+
+ def _drop_first_page_only_params(self, request: Request) -> None:
+ if not request.params:
+ return
+ for name in self._first_page_only_params:
+ request.params.pop(name, None)
+
+ def init_request(self, request: Request) -> None:
+ super().init_request(request)
+ # A resumed run starts mid-pagination, so its very first request already carries a cursor.
+ if self._cursor_value is not None:
+ self._drop_first_page_only_params(request)
+
+ def update_state(self, response: Response, data: Optional[list[Any]] = None) -> None:
+ super().update_state(response, data)
+ if data is not None and len(data) == 0:
+ self._has_next_page = False
+
+ def update_request(self, request: Request) -> None:
+ super().update_request(request)
+ self._drop_first_page_only_params(request)
+
+
+def _paginator_for(config: MetronomeEndpointConfig) -> BasePaginator:
+ if not config.paginated:
+ return SinglePagePaginator()
+ first_page_only: tuple[str, ...] = (config.incremental_start_param,) if config.incremental_start_param else ()
+ return MetronomeCursorPaginator(first_page_only_params=first_page_only)
+
+
+def _format_rfc3339(value: Any) -> str:
+ normalized_value = coerce_datetime_to_utc(value)
+ if normalized_value is None:
+ return str(value)
+ return normalized_value.strftime(RFC_3339_FORMAT)
+
+
+def _incremental_window(config: MetronomeEndpointConfig, cursor_path: str) -> IncrementalConfig | None:
+ """The request window for an incremental sync, or None when the endpoint has no time filter."""
+ if not config.incremental_start_param or not config.incremental_fields:
+ return None
+ return {
+ "cursor_path": cursor_path,
+ "start_param": config.incremental_start_param,
+ "initial_value": EPOCH_RFC_3339,
+ "convert": _format_rfc3339,
+ }
+
+
+def _rest_api_client_config(api_key: str) -> ClientConfig:
+ return {
+ "base_url": METRONOME_BASE_URL,
+ "auth": {"type": "bearer", "token": api_key},
+ "headers": {"Accept": "application/json"},
+ # `capture=False`: customer, invoice and contract payloads carry customer names alongside
+ # arbitrary `custom_fields` key/values the account sets itself, so the name-based sample
+ # scrubbers can't be relied on to redact them. Requests stay metered and logged.
+ "session": make_tracked_session(redact_values=(api_key,), capture=False, allow_redirects=False),
+ # Pin every request (and the bearer header) to the Metronome host and refuse to follow a
+ # 3xx, so a server-side redirect can never replay the credential off-host.
+ "allowed_hosts": [],
+ "allow_redirects": False,
+ "request_timeout": REQUEST_TIMEOUT_SECONDS,
+ }
+
+
+def _rest_client(api_key: str) -> RESTClient:
+ """The same client the framework builds from `_rest_api_client_config`, for the fan-out that
+ can't be expressed declaratively. Read off the config so the two paths can't drift apart."""
+ config = _rest_api_client_config(api_key)
+ return RESTClient(
+ base_url=config["base_url"],
+ headers=config["headers"],
+ auth=create_auth(config["auth"]),
+ session=config["session"],
+ allowed_hosts=config["allowed_hosts"],
+ allow_redirects=config["allow_redirects"],
+ request_timeout=config["request_timeout"],
+ )
+
+
+def _list_params(config: MetronomeEndpointConfig) -> dict[str, Any]:
+ params: dict[str, Any] = {} if not config.paginated else {"limit": config.page_size}
+ params.update(config.extra_params)
+ return params
+
+
+def get_resource(
+ endpoint: str,
+ should_use_incremental_field: bool,
+ incremental_field_name: str | None = None,
+) -> EndpointResource:
+ config = METRONOME_ENDPOINTS[endpoint]
+ if config.fanout or config.body_fanout:
+ raise ValueError(f"Fan-out endpoint '{endpoint}' must use the fan-out path")
+
+ endpoint_config: Endpoint = {
+ "path": config.path,
+ "method": config.method,
+ "params": _list_params(config),
+ "data_selector": DATA_SELECTOR,
+ # Every documented list response wraps its rows in `data`, so a body without it means the
+ # shape changed — fail loud rather than silently syncing 0 rows.
+ "data_selector_required": True,
+ "paginator": _paginator_for(config),
+ }
+ # The POST list endpoints take their filters as a body. Two of them accept no filters at all,
+ # and still expect a JSON document rather than an empty request.
+ if config.method == "post":
+ endpoint_config["json"] = dict(config.json_body)
+
+ incremental = _incremental_window(config, incremental_field_name or config.default_incremental_field or "")
+ use_incremental = should_use_incremental_field and incremental is not None
+ if use_incremental:
+ endpoint_config["incremental"] = cast(IncrementalConfig, incremental)
+
+ return {
+ "name": config.name,
+ "table_name": config.name,
+ "write_disposition": {"disposition": "merge", "strategy": "upsert"} if use_incremental else "replace",
+ "endpoint": endpoint_config,
+ "table_format": "delta",
+ }
+
+
+def _body_fanout_pages(client: RESTClient, config: MetronomeEndpointConfig) -> Iterator[list[dict[str, Any]]]:
+ """Walk the parent list and call the child once per parent row, binding the id into the body."""
+ fanout = config.body_fanout
+ if fanout is None:
+ raise ValueError(f"'{config.name}' has no body fan-out configured")
+
+ parent = METRONOME_ENDPOINTS[fanout.parent_name]
+
+ for parent_page in client.paginate(
+ parent.path,
+ params=_list_params(parent),
+ data_selector=DATA_SELECTOR,
+ data_selector_required=True,
+ paginator=_paginator_for(parent),
+ ):
+ for parent_row in parent_page:
+ parent_id = parent_row.get(fanout.resolve_field)
+ if not parent_id:
+ continue
+ for page in client.paginate(
+ config.path,
+ method=config.method,
+ json={**config.json_body, fanout.body_param: parent_id},
+ data_selector=DATA_SELECTOR,
+ data_selector_required=True,
+ paginator=_paginator_for(config),
+ ):
+ if page:
+ yield page
+
+
+def _make_source_response(
+ config: MetronomeEndpointConfig,
+ items_fn: Callable[[], Iterable[Any]],
+) -> SourceResponse:
+ # `audit_logs` is the only table that syncs incrementally, and it pins `sort=date_asc`, so the
+ # default ascending `sort_mode` matches the order rows actually arrive in. Metronome documents
+ # no order for the rest, and none of them checkpoint a watermark.
+ return SourceResponse(
+ name=config.name,
+ items=items_fn,
+ primary_keys=config.primary_key,
+ 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 metronome_source(
+ api_key: str,
+ endpoint: str,
+ team_id: int,
+ job_id: str,
+ resumable_source_manager: Optional[ResumableSourceManager[MetronomeResumeConfig]] = None,
+ should_use_incremental_field: bool = False,
+ db_incremental_field_last_value: Optional[Any] = None,
+ incremental_field: str | None = None,
+) -> SourceResponse:
+ endpoint_config = METRONOME_ENDPOINTS[endpoint]
+
+ if endpoint_config.body_fanout:
+ # One client for the whole fan-out, so every per-customer request reuses its connection
+ # pool. Mirrors the framework path, which builds its session at source-build time too.
+ client = _rest_client(api_key)
+ return _make_source_response(endpoint_config, lambda: _body_fanout_pages(client, endpoint_config))
+
+ if endpoint_config.fanout:
+ parent_config = METRONOME_ENDPOINTS[endpoint_config.fanout.parent_name]
+ # Dependent resources don't support resume in the rest_source framework, so the manager is
+ # intentionally not threaded into this path.
+ dependent_resource = cast(
+ Iterable[Any],
+ build_dependent_resource(
+ endpoint_configs=METRONOME_ENDPOINTS,
+ child_endpoint=endpoint,
+ fanout=dataclasses.replace(endpoint_config.fanout, child_params=dict(endpoint_config.extra_params)),
+ client_config=_rest_api_client_config(api_key),
+ path_format_values={},
+ team_id=team_id,
+ job_id=job_id,
+ db_incremental_field_last_value=db_incremental_field_last_value,
+ should_use_incremental_field=should_use_incremental_field,
+ incremental_field=incremental_field,
+ parent_endpoint_extra={
+ "paginator": _paginator_for(parent_config),
+ "data_selector": DATA_SELECTOR,
+ "data_selector_required": True,
+ },
+ child_endpoint_extra={
+ "paginator": _paginator_for(endpoint_config),
+ "data_selector": DATA_SELECTOR,
+ "data_selector_required": True,
+ },
+ ),
+ )
+ return _make_source_response(endpoint_config, lambda: dependent_resource)
+
+ config: RESTAPIConfig = {
+ "client": _rest_api_client_config(api_key),
+ "resource_defaults": {},
+ "resources": [get_resource(endpoint, should_use_incremental_field, incremental_field)],
+ }
+
+ initial_paginator_state: Optional[dict[str, Any]] = None
+ resume_hook: Optional[Callable[[Optional[dict[str, Any]]], None]] = None
+ if resumable_source_manager is not None:
+ if resumable_source_manager.can_resume():
+ resume_config = resumable_source_manager.load_state()
+ if resume_config is not None:
+ initial_paginator_state = {"cursor": resume_config.next_page}
+
+ def save_checkpoint(state: Optional[dict[str, Any]]) -> None:
+ # Persist only while there is another page to resume to; the Redis TTL cleans up on
+ # completion.
+ if resumable_source_manager is None or not state:
+ return
+ cursor = state.get("cursor")
+ if cursor:
+ resumable_source_manager.save_state(MetronomeResumeConfig(next_page=str(cursor)))
+
+ resume_hook = save_checkpoint
+
+ resource = rest_api_resource(
+ config,
+ team_id,
+ job_id,
+ db_incremental_field_last_value,
+ resume_hook=resume_hook,
+ initial_paginator_state=initial_paginator_state,
+ )
+ return _make_source_response(endpoint_config, lambda: resource)
+
+
+def validate_credentials(api_key: str) -> tuple[bool, str | None]:
+ valid, status_code = validate_via_probe(
+ lambda: make_tracked_session(redact_values=(api_key,), capture=False, allow_redirects=False),
+ f"{METRONOME_BASE_URL}/v1/customers?limit=1",
+ headers={"Authorization": f"Bearer {api_key}", "Accept": "application/json"},
+ timeout=REQUEST_TIMEOUT_SECONDS,
+ allow_redirects=False,
+ )
+ if valid:
+ return True, None
+ if status_code is None:
+ return False, "Couldn't reach Metronome to validate the API token. Check your connection and try again."
+ if status_code in (401, 403):
+ # Metronome's auth docs say a token it won't accept comes back as "a 401 or 403", so both
+ # codes point at the same fix.
+ return (
+ False,
+ "Metronome rejected the API token. Create a new one in Metronome under "
+ "Developer > API tokens and reconnect.",
+ )
+ return False, f"Metronome API returned an unexpected status code: {status_code}"
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/metronome/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/metronome/settings.py
new file mode 100644
index 000000000000..83f9175f8fd6
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/metronome/settings.py
@@ -0,0 +1,159 @@
+from dataclasses import dataclass, field
+from typing import Any, Literal
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.fanout import (
+ DependentEndpointConfig,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.schema import incremental_field
+from products.warehouse_sources.backend.types import IncrementalField
+
+METRONOME_BASE_URL = "https://api.metronome.com"
+
+# Every paginated Metronome list endpoint caps `limit` at 100.
+PAGE_SIZE = 100
+
+# List responses share a `{"data": [...], "next_page": "..."}` envelope, and the cursor goes back
+# out under the name it arrived under.
+DATA_SELECTOR = "data"
+CURSOR_PATH = "next_page"
+CURSOR_PARAM = "next_page"
+
+# `GET /v1/auditLogs` is the only endpoint with a server-side lower bound on record time.
+AUDIT_LOG_START_PARAM = "starting_on"
+
+
+@dataclass(frozen=True)
+class BodyFanoutConfig:
+ """Fan-out whose parent id belongs in the child's JSON body.
+
+ The declarative fan-out helper binds a resolved parent field into the child's *path* only, so
+ a child like `POST /v2/contracts/list` — which takes `customer_id` in its body — walks the
+ parent itself instead.
+ """
+
+ parent_name: str
+ resolve_field: str
+ body_param: str
+
+
+# frozen=False: MetronomeEndpointConfig is passed as `endpoint_configs: Mapping[str, FanoutEndpointLike]`,
+# and mypy treats a frozen dataclass's fields as read-only, which is incompatible with that
+# Protocol's plain (read-write) attributes.
+@dataclass(frozen=False)
+class MetronomeEndpointConfig:
+ name: str
+ path: str
+ primary_key: list[str]
+ method: Literal["get", "post"] = "get"
+ # Filter payload for the POST list endpoints. `limit` and `next_page` stay in the query string
+ # on these; only the filters move into the body.
+ json_body: dict[str, Any] = field(default_factory=dict)
+ extra_params: dict[str, Any] = field(default_factory=dict)
+ # Endpoints whose response carries a `next_page` cursor; the rest return the whole collection.
+ paginated: bool = True
+ # Server-side lower bound for incremental syncs. Metronome rejects this window when a cursor
+ # is also sent, so it only rides the first request of a run.
+ incremental_start_param: str | None = None
+ incremental_fields: list[IncrementalField] = field(default_factory=list)
+ default_incremental_field: str | None = None
+ partition_key: str | None = None
+ page_size: int = PAGE_SIZE
+ fanout: DependentEndpointConfig | None = None
+ body_fanout: BodyFanoutConfig | None = None
+
+
+# Customer-scoped children bind the parent's `id` into their path as `customer_id`. Every child
+# row already carries its own `customer_id`, so nothing needs copying down from the parent.
+_CUSTOMER_PATH_FANOUT = DependentEndpointConfig(
+ parent_name="customers",
+ resolve_param="customer_id",
+ resolve_field="id",
+ include_from_parent=[],
+)
+
+
+METRONOME_ENDPOINTS: dict[str, MetronomeEndpointConfig] = {
+ "customers": MetronomeEndpointConfig(
+ name="customers",
+ path="/v1/customers",
+ primary_key=["id"],
+ partition_key="created_at",
+ # No created/updated filter exists on this endpoint, so every run reads the whole list.
+ # `only_archived` swaps the result set rather than widening it, so archived customers are
+ # out of scope for this table.
+ ),
+ "invoices": MetronomeEndpointConfig(
+ name="invoices",
+ path="/v1/customers/{customer_id}/invoices",
+ primary_key=["id"],
+ # The endpoint's own docs give two different default orders, so pin one.
+ extra_params={"sort": "date_asc"},
+ # `line_items` is unbounded, so a full page of invoices can be very large. A smaller page
+ # keeps each response, and the Arrow table built from it, within reach.
+ page_size=25,
+ fanout=_CUSTOMER_PATH_FANOUT,
+ ),
+ "contracts": MetronomeEndpointConfig(
+ name="contracts",
+ path="/v2/contracts/list",
+ method="post",
+ primary_key=["id"],
+ partition_key="created_at",
+ # Returns every contract for the customer in one response — no cursor, no `limit`.
+ paginated=False,
+ json_body={"include_archived": True},
+ body_fanout=BodyFanoutConfig(parent_name="customers", resolve_field="id", body_param="customer_id"),
+ ),
+ "products": MetronomeEndpointConfig(
+ name="products",
+ path="/v1/contract-pricing/products/list",
+ method="post",
+ primary_key=["id"],
+ # Archived products stay in the warehouse copy; the default filter hides them.
+ json_body={"archive_filter": "ALL"},
+ ),
+ "rate_cards": MetronomeEndpointConfig(
+ name="rate_cards",
+ path="/v1/contract-pricing/rate-cards/list",
+ method="post",
+ primary_key=["id"],
+ partition_key="created_at",
+ ),
+ "packages": MetronomeEndpointConfig(
+ name="packages",
+ path="/v1/packages/list",
+ method="post",
+ primary_key=["id"],
+ partition_key="created_at",
+ json_body={"archive_filter": "ALL"},
+ ),
+ "billable_metrics": MetronomeEndpointConfig(
+ name="billable_metrics",
+ path="/v1/billable-metrics",
+ primary_key=["id"],
+ extra_params={"include_archived": "true"},
+ ),
+ "pricing_units": MetronomeEndpointConfig(
+ name="pricing_units",
+ path="/v1/credit-types/list",
+ primary_key=["id"],
+ ),
+ "audit_logs": MetronomeEndpointConfig(
+ name="audit_logs",
+ path="/v1/auditLogs",
+ primary_key=["id"],
+ # `date_asc` is the documented default, but pin it so the rows arrive in the order the
+ # incremental watermark assumes.
+ extra_params={"sort": "date_asc"},
+ incremental_start_param=AUDIT_LOG_START_PARAM,
+ incremental_fields=[incremental_field("timestamp")],
+ default_incremental_field="timestamp",
+ partition_key="timestamp",
+ ),
+}
+
+ENDPOINTS = tuple(METRONOME_ENDPOINTS)
+
+INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {
+ name: config.incremental_fields for name, config in METRONOME_ENDPOINTS.items()
+}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/metronome/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/metronome/source.py
index 6db27f3d5489..fc0683eba5cf 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/metronome/source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/metronome/source.py
@@ -1,32 +1,129 @@
-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.sources.common.base import FieldType, SimpleSource
+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 (
+ SourceSchema,
+ build_endpoint_schemas,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceInputs, SourceResponse
from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.metronome import (
MetronomeSourceConfig,
)
+from products.warehouse_sources.backend.temporal.data_imports.sources.metronome.metronome import (
+ MetronomeResumeConfig,
+ metronome_source,
+ validate_credentials as validate_metronome_credentials,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.metronome.settings import (
+ ENDPOINTS,
+ INCREMENTAL_FIELDS,
+)
from products.warehouse_sources.backend.types import ExternalDataSourceType
@SourceRegistry.register
-class MetronomeSource(SimpleSource[MetronomeSourceConfig]):
+class MetronomeSource(ResumableSource[MetronomeSourceConfig, MetronomeResumeConfig]):
+ lists_tables_without_credentials = True # static endpoint catalog — safe for public docs
+ # Metronome exposes no pinnable API version. `/v1/` and `/v2/` are route namespaces that
+ # coexist permanently — v2 contracts sit alongside v1 rate cards and packages — and no header,
+ # path or query parameter selects a version.
+ api_docs_url = "https://docs.metronome.com/api-reference/"
+
@property
def source_type(self) -> ExternalDataSourceType:
return ExternalDataSourceType.METRONOME
+ def get_non_retryable_errors(self) -> dict[str, str | None]:
+ return {
+ "401 Client Error: Unauthorized for url": "Metronome rejected the API token. Create a new one under Developer > API tokens and reconnect.",
+ "403 Client Error: Forbidden for url": "The Metronome API token can't read this data. Check the token's scopes, or create an unscoped one under Developer > API tokens.",
+ }
+
+ def get_canonical_descriptions(self) -> CanonicalDescriptions:
+ from products.warehouse_sources.backend.temporal.data_imports.sources.metronome.canonical_descriptions import (
+ CANONICAL_DESCRIPTIONS,
+ )
+
+ return CANONICAL_DESCRIPTIONS
+
+ def get_schemas(
+ self,
+ config: MetronomeSourceConfig,
+ team_id: int,
+ with_counts: bool = False,
+ names: list[str] | None = None,
+ force_refresh: bool = False,
+ api_version: str | None = None,
+ ) -> list[SourceSchema]:
+ return build_endpoint_schemas(ENDPOINTS, INCREMENTAL_FIELDS, names)
+
+ def validate_credentials(
+ self,
+ config: MetronomeSourceConfig,
+ team_id: int,
+ schema_name: Optional[str] = None,
+ api_version: str | None = None,
+ ) -> tuple[bool, str | None]:
+ return validate_metronome_credentials(config.api_key)
+
+ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[MetronomeResumeConfig]:
+ return ResumableSourceManager[MetronomeResumeConfig](inputs, MetronomeResumeConfig)
+
+ def source_for_pipeline(
+ self,
+ config: MetronomeSourceConfig,
+ resumable_source_manager: ResumableSourceManager[MetronomeResumeConfig],
+ inputs: SourceInputs,
+ ) -> SourceResponse:
+ return metronome_source(
+ api_key=config.api_key,
+ endpoint=inputs.schema_name,
+ team_id=inputs.team_id,
+ job_id=inputs.job_id,
+ resumable_source_manager=resumable_source_manager,
+ should_use_incremental_field=inputs.should_use_incremental_field,
+ db_incremental_field_last_value=inputs.db_incremental_field_last_value
+ if inputs.should_use_incremental_field
+ else None,
+ incremental_field=inputs.incremental_field,
+ )
+
@property
def get_source_config(self) -> SourceConfig:
return SourceConfig(
name=SchemaExternalDataSourceType.METRONOME,
category=DataWarehouseSourceCategory.PAYMENTS___BILLING,
+ keywords=["billing", "usage-based billing"],
label="Metronome",
+ caption="Create an API token in Metronome under **Developer > API tokens**. Metronome shows the token once, so copy it before closing the dialog.",
+ docsUrl="https://posthog.com/docs/cdp/sources/metronome",
iconPath="/static/services/metronome.png",
- fields=cast(list[FieldType], []),
- unreleasedSource=True,
+ releaseStatus=ReleaseStatus.ALPHA,
+ fields=cast(
+ list[FieldType],
+ [
+ SourceFieldInputConfig(
+ name="api_key",
+ label="API token",
+ type=SourceFieldInputConfigType.PASSWORD,
+ required=True,
+ placeholder="",
+ secret=True,
+ ),
+ ],
+ ),
)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/metronome/tests/test_metronome.py b/products/warehouse_sources/backend/temporal/data_imports/sources/metronome/tests/test_metronome.py
new file mode 100644
index 000000000000..083381569c81
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/metronome/tests/test_metronome.py
@@ -0,0 +1,262 @@
+from datetime import UTC, datetime
+from typing import Any, cast
+
+import pytest
+from unittest.mock import MagicMock, Mock, patch
+
+import requests
+from parameterized import parameterized
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.paginators import (
+ SinglePagePaginator,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.metronome.metronome import (
+ MetronomeCursorPaginator,
+ MetronomeResumeConfig,
+ _format_rfc3339,
+ _paginator_for,
+ get_resource,
+ metronome_source,
+ validate_credentials,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.metronome.settings import METRONOME_ENDPOINTS
+
+TRANSPORT = "products.warehouse_sources.backend.temporal.data_imports.sources.metronome.metronome"
+
+
+def _response(body: dict[str, Any]) -> Mock:
+ response = Mock()
+ response.json.return_value = body
+ return response
+
+
+def _request(params: dict[str, Any] | None = None) -> Mock:
+ request = Mock()
+ request.params = params if params is not None else {}
+ return request
+
+
+class TestMetronomePaginator:
+ def test_follows_next_page_and_stops_when_it_goes_null(self) -> None:
+ paginator = MetronomeCursorPaginator()
+ request = _request()
+
+ paginator.update_state(_response({"data": [{"id": "a"}], "next_page": "cursor-2"}), data=[{"id": "a"}])
+ assert paginator.has_next_page is True
+ paginator.update_request(request)
+ assert request.params["next_page"] == "cursor-2"
+
+ # Metronome sends an explicit null once the collection is exhausted.
+ paginator.update_state(_response({"data": [{"id": "b"}], "next_page": None}), data=[{"id": "b"}])
+ assert paginator.has_next_page is False
+
+ def test_stops_on_an_empty_page_that_still_carries_a_cursor(self) -> None:
+ # `GET /v1/auditLogs` always returns a cursor, so a cursor-only stop condition would loop
+ # forever once the account has no newer entries.
+ paginator = MetronomeCursorPaginator()
+
+ paginator.update_state(_response({"data": [], "next_page": "cursor-2"}), data=[])
+
+ assert paginator.has_next_page is False
+
+ def test_time_window_only_rides_the_request_without_a_cursor(self) -> None:
+ # Metronome rejects `starting_on` when a cursor is also sent.
+ paginator = MetronomeCursorPaginator(first_page_only_params=("starting_on",))
+ request = _request({"starting_on": "2026-01-01T00:00:00Z", "sort": "date_asc"})
+
+ paginator.init_request(request)
+ assert request.params["starting_on"] == "2026-01-01T00:00:00Z"
+
+ paginator.update_state(_response({"data": [{"id": "a"}], "next_page": "cursor-2"}), data=[{"id": "a"}])
+ paginator.update_request(request)
+
+ assert "starting_on" not in request.params
+ assert request.params["next_page"] == "cursor-2"
+ assert request.params["sort"] == "date_asc"
+
+ def test_resumed_run_drops_the_time_window_from_its_first_request(self) -> None:
+ # A resumed run starts mid-pagination, so even its first request carries a cursor.
+ paginator = MetronomeCursorPaginator(first_page_only_params=("starting_on",))
+ paginator.set_resume_state({"cursor": "cursor-9"})
+ request = _request({"starting_on": "2026-01-01T00:00:00Z"})
+
+ paginator.init_request(request)
+
+ assert request.params == {"next_page": "cursor-9"}
+
+ def test_contracts_endpoint_is_not_paginated(self) -> None:
+ # `POST /v2/contracts/list` returns every contract for the customer in one response.
+ assert isinstance(_paginator_for(METRONOME_ENDPOINTS["contracts"]), SinglePagePaginator)
+
+
+class TestMetronomeResources:
+ @parameterized.expand(
+ [
+ ("naive_datetime", datetime(2026, 3, 1, 12, 30, 45, 999999), "2026-03-01T12:30:45Z"),
+ ("aware_datetime", datetime(2026, 3, 1, 23, 59, 59, tzinfo=UTC), "2026-03-01T23:59:59Z"),
+ ("passthrough_string", "1970-01-01T00:00:00Z", "1970-01-01T00:00:00Z"),
+ ]
+ )
+ def test_format_rfc3339(self, _name, value, expected) -> None:
+ assert _format_rfc3339(value) == expected
+
+ def test_audit_logs_incremental_resource_uses_starting_on(self) -> None:
+ resource = cast(dict[str, Any], get_resource("audit_logs", should_use_incremental_field=True))
+
+ assert resource["write_disposition"] == {"disposition": "merge", "strategy": "upsert"}
+ incremental = resource["endpoint"]["incremental"]
+ assert incremental["start_param"] == "starting_on"
+ assert incremental["cursor_path"] == "timestamp"
+ assert incremental["convert"] is _format_rfc3339
+
+ def test_audit_logs_full_refresh_sends_no_window(self) -> None:
+ resource = cast(dict[str, Any], get_resource("audit_logs", should_use_incremental_field=False))
+
+ assert resource["write_disposition"] == "replace"
+ assert "incremental" not in resource["endpoint"]
+ assert "starting_on" not in resource["endpoint"]["params"]
+
+ @parameterized.expand([("customers",), ("products",), ("packages",), ("billable_metrics",)])
+ def test_endpoints_without_a_time_filter_never_go_incremental(self, endpoint) -> None:
+ # Metronome exposes no created/updated filter on these, so an "incremental" sync would
+ # still fetch every page and cost the same as a full refresh.
+ resource = cast(dict[str, Any], get_resource(endpoint, should_use_incremental_field=True))
+
+ assert resource["write_disposition"] == "replace"
+ assert "incremental" not in resource["endpoint"]
+
+ @parameterized.expand(
+ [
+ ("products", {"archive_filter": "ALL"}),
+ ("packages", {"archive_filter": "ALL"}),
+ # The rate cards endpoint takes no filters but still expects a JSON document.
+ ("rate_cards", {}),
+ ]
+ )
+ def test_post_endpoints_send_filters_in_the_body_and_paginate_in_the_query(self, endpoint, expected_body) -> None:
+ resource = cast(dict[str, Any], get_resource(endpoint, should_use_incremental_field=False))
+
+ assert resource["endpoint"]["method"] == "post"
+ assert resource["endpoint"]["json"] == expected_body
+ assert resource["endpoint"]["params"] == {"limit": 100}
+
+ @parameterized.expand([("invoices",), ("contracts",)])
+ def test_get_resource_rejects_fanout_endpoints(self, endpoint) -> None:
+ with pytest.raises(ValueError, match="Fan-out endpoint"):
+ get_resource(endpoint, should_use_incremental_field=False)
+
+
+class TestMetronomeSourceResponse:
+ @parameterized.expand(
+ [
+ ("customers", ["id"], "created_at"),
+ ("audit_logs", ["id"], "timestamp"),
+ ("pricing_units", ["id"], None),
+ ]
+ )
+ @patch(f"{TRANSPORT}.rest_api_resource")
+ def test_top_level_response_shape(self, endpoint, primary_keys, partition_key, _mock) -> None:
+ response = metronome_source(api_key="tok", endpoint=endpoint, team_id=1, job_id="job-1")
+
+ assert response.primary_keys == primary_keys
+ assert response.partition_keys == ([partition_key] if partition_key else None)
+
+ @patch(f"{TRANSPORT}.rest_api_resource")
+ def test_resume_state_seeds_the_paginator_cursor(self, mock_rest_api_resource) -> None:
+ manager = MagicMock()
+ manager.can_resume.return_value = True
+ manager.load_state.return_value = MetronomeResumeConfig(next_page="cursor-9")
+
+ metronome_source(
+ api_key="tok", endpoint="customers", team_id=1, job_id="job-1", resumable_source_manager=manager
+ )
+
+ assert mock_rest_api_resource.call_args.kwargs["initial_paginator_state"] == {"cursor": "cursor-9"}
+
+ @patch(f"{TRANSPORT}.build_dependent_resource")
+ def test_invoices_fan_out_over_customers(self, mock_build) -> None:
+ mock_build.return_value = iter([])
+
+ metronome_source(api_key="tok", endpoint="invoices", team_id=1, job_id="job-1")
+
+ kwargs = mock_build.call_args.kwargs
+ assert kwargs["fanout"].parent_name == "customers"
+ assert kwargs["fanout"].resolve_param == "customer_id"
+ # The invoice payload already carries `customer_id`, so nothing is copied down.
+ assert kwargs["fanout"].include_from_parent == []
+ assert kwargs["fanout"].child_params == {"sort": "date_asc"}
+ assert kwargs["parent_endpoint_extra"]["data_selector"] == "data"
+ assert kwargs["child_endpoint_extra"]["data_selector"] == "data"
+
+
+class TestMetronomeBodyFanout:
+ @patch(f"{TRANSPORT}._rest_client")
+ def test_contracts_are_requested_once_per_customer_with_the_id_in_the_body(self, mock_client_factory) -> None:
+ client = MagicMock()
+ client.paginate.side_effect = [
+ # Parent customers, across two pages.
+ iter([[{"id": "cust_1"}], [{"id": "cust_2"}]]),
+ iter([[{"id": "contract_1", "customer_id": "cust_1"}]]),
+ iter([[{"id": "contract_2", "customer_id": "cust_2"}]]),
+ ]
+ mock_client_factory.return_value = client
+
+ response = metronome_source(api_key="tok", endpoint="contracts", team_id=1, job_id="job-1")
+ pages = list(cast(Any, response.items()))
+
+ assert pages == [
+ [{"id": "contract_1", "customer_id": "cust_1"}],
+ [{"id": "contract_2", "customer_id": "cust_2"}],
+ ]
+ child_calls = client.paginate.call_args_list[1:]
+ assert [call.kwargs["json"] for call in child_calls] == [
+ {"include_archived": True, "customer_id": "cust_1"},
+ {"include_archived": True, "customer_id": "cust_2"},
+ ]
+ assert {call.args[0] for call in child_calls} == {"/v2/contracts/list"}
+
+ @patch(f"{TRANSPORT}._rest_client")
+ def test_customer_without_an_id_is_skipped(self, mock_client_factory) -> None:
+ client = MagicMock()
+ client.paginate.side_effect = [iter([[{"name": "no id here"}]])]
+ mock_client_factory.return_value = client
+
+ response = metronome_source(api_key="tok", endpoint="contracts", team_id=1, job_id="job-1")
+
+ assert list(cast(Any, response.items())) == []
+ assert client.paginate.call_count == 1
+
+
+class TestMetronomeCredentials:
+ @parameterized.expand(
+ [
+ (200, True, None),
+ (
+ 401,
+ False,
+ "Metronome rejected the API token. Create a new one in Metronome under Developer > API tokens and reconnect.",
+ ),
+ (
+ 403,
+ False,
+ "Metronome rejected the API token. Create a new one in Metronome under Developer > API tokens and reconnect.",
+ ),
+ (500, False, "Metronome API returned an unexpected status code: 500"),
+ ]
+ )
+ @patch(f"{TRANSPORT}.make_tracked_session")
+ def test_status_maps_to_message(self, status_code, expected_valid, expected_message, mock_session) -> None:
+ # Metronome's own auth docs say a rejected token comes back as "a 401 or 403", so both
+ # codes have to land on the same message.
+ mock_session.return_value.get.return_value = Mock(status_code=status_code)
+
+ assert validate_credentials("tok") == (expected_valid, expected_message)
+
+ @patch(f"{TRANSPORT}.make_tracked_session")
+ def test_unreachable_host_is_not_reported_as_a_bad_token(self, mock_session) -> None:
+ mock_session.return_value.get.side_effect = requests.ConnectionError("boom")
+
+ valid, message = validate_credentials("tok")
+
+ assert valid is False
+ assert message == "Couldn't reach Metronome to validate the API token. Check your connection and try again."