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.

7.1 KB
Raw Blame
from typing import Optional, cast

from products.warehouse_sources.sources.metronome._config import MetronomeSourceConfig
from products.warehouse_sources.sources.metronome.metronome import (
    MetronomeResumeConfig,
    metronome_source,
    validate_credentials as validate_metronome_credentials,
)
from products.warehouse_sources.sources.metronome.settings import (
    DEFAULT_USAGE_DAILY_HISTORY_MONTHS,
    DEFAULT_USAGE_HOURLY_HISTORY_DAYS,
    ENDPOINTS,
    INCREMENTAL_FIELDS,
    MERGE_ONLY,
    METRONOME_ENDPOINTS,
    usage_history_window,
)
from products.warehouse_sources.sources.sdk import (
    CanonicalDescriptions,
    DataWarehouseSourceCategory,
    ExternalDataSourceType,
    FieldType,
    ReleaseStatus,
    ResumableSource,
    ResumableSourceManager,
    SourceConfig,
    SourceFieldInputConfig,
    SourceFieldInputConfigType,
    SourceInputs,
    SourceRegistry,
    SourceResponse,
    SourceSchema,
    build_endpoint_schemas,
    detect,
)


@SourceRegistry.register
class MetronomeSource(ResumableSource[MetronomeSourceConfig, MetronomeResumeConfig]):
    codebase_detection = detect(
        env=("^METRONOME_BEARER_TOKEN$",),
        npm=("@metronome/sdk",),
        pypi=("metronome-sdk",),
        go=("github.com/Metronome-Industries/metronome-go",),
        maven=(
            "com.metronome.api:metronome-java",
            "com.metronome.api:metronome-java-client-okhttp",
            "com.metronome.api:metronome-java-core",
        ),
        rubygems=("metronome-sdk",),
    )

    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.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]:
        schemas = build_endpoint_schemas(
            ENDPOINTS,
            INCREMENTAL_FIELDS,
            names,
            # Appending would duplicate every period the lookback re-reads, so a windowed
            # table has to merge on its primary key.
            merge_only=MERGE_ONLY,
            should_sync_default={name: METRONOME_ENDPOINTS[name].should_sync_default for name in ENDPOINTS},
        )
        for schema in schemas:
            schema.default_incremental_lookback_seconds = METRONOME_ENDPOINTS[
                schema.name
            ].default_incremental_lookback_seconds
        return schemas

    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,
            # Resolved per run rather than recorded once, so a depth the user edits after the first
            # sync takes effect, and the window stays the size they asked for rather than widening
            # as the source ages.
            usage_history=usage_history_window(
                inputs.schema_name,
                config.usage_hourly_history_days,
                config.usage_daily_history_months,
            ),
        )

    @property
    def get_source_config(self) -> SourceConfig:
        return SourceConfig(
            name=ExternalDataSourceType.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",
            releaseStatus=ReleaseStatus.GA,
            fields=cast(
                list[FieldType],
                [
                    SourceFieldInputConfig(
                        name="api_key",
                        label="API token",
                        type=SourceFieldInputConfigType.PASSWORD,
                        required=True,
                        placeholder="",
                        secret=True,
                    ),
                    SourceFieldInputConfig(
                        name="usage_hourly_history_days",
                        sync_setting=True,
                        label="Hourly usage history (days)",
                        type=SourceFieldInputConfigType.NUMBER,
                        required=False,
                        placeholder=str(DEFAULT_USAGE_HOURLY_HISTORY_DAYS),
                        secret=False,
                    ),
                    SourceFieldInputConfig(
                        name="usage_daily_history_months",
                        sync_setting=True,
                        label="Daily usage history (months)",
                        type=SourceFieldInputConfigType.NUMBER,
                        required=False,
                        placeholder=str(DEFAULT_USAGE_DAILY_HISTORY_MONTHS),
                        secret=False,
                    ),
                ],
            ),
        )