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.

6.5 KB
Raw Blame
from typing import Optional, cast

from products.warehouse_sources.sources.hetzner._config import HetznerSourceConfig
from products.warehouse_sources.sources.hetzner.hetzner import (
    HetznerResumeConfig,
    hetzner_child_source,
    hetzner_metrics_source,
    hetzner_source,
    validate_credentials as validate_hetzner_credentials,
)
from products.warehouse_sources.sources.hetzner.settings import (
    ENDPOINTS,
    HETZNER_CHILD_ENDPOINTS,
    HETZNER_METRICS_ENDPOINTS,
    INCREMENTAL_FIELDS,
)
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 HetznerSource(ResumableSource[HetznerSourceConfig, HetznerResumeConfig]):
    codebase_detection = detect(
        env=("^HETZNER_", "^HCLOUD_TOKEN$"),
        pypi=("hcloud",),
        go=(
            "github.com/hetznercloud/hcloud-go",
            "github.com/hetznercloud/hcloud-cloud-controller-manager",
            "github.com/hetznercloud/packer-plugin-hcloud",
            "gitlab.com/hetznercloud/fleeting-plugin-hetzner",
        ),
    )

    # get_schemas iterates a static endpoint catalog with no I/O, so the table list is safe to
    # publish in the public docs.
    lists_tables_without_credentials = True
    supported_versions = ("v1",)
    default_version = "v1"
    api_docs_url = "https://docs.hetzner.cloud/"

    @property
    def source_type(self) -> ExternalDataSourceType:
        return ExternalDataSourceType.HETZNER

    @property
    def get_source_config(self) -> SourceConfig:
        return SourceConfig(
            name=ExternalDataSourceType.HETZNER,
            category=DataWarehouseSourceCategory.ENGINEERING___MONITORING,
            label="Hetzner Cloud",
            releaseStatus=ReleaseStatus.GA,
            caption="""Enter a Hetzner Cloud API token to sync your Hetzner Cloud project into the PostHog Data warehouse.

Create a token under **Security > API tokens** in the [Hetzner Cloud Console](https://console.hetzner.cloud/). A `Read` token is enough. Each token is scoped to a single project, so connect one source per project you want to sync.""",
            iconPath="/static/services/hetzner.svg",
            docsUrl="https://posthog.com/docs/cdp/sources/hetzner",
            keywords=["cloud", "infrastructure", "servers", "hosting"],
            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.sources.hetzner.canonical_descriptions import CANONICAL_DESCRIPTIONS

        return CANONICAL_DESCRIPTIONS

    def get_non_retryable_errors(self) -> dict[str, str | None]:
        return {
            # A revoked or invalid token surfaces as an HTTPError when the client calls
            # `raise_for_status()`. Retrying can never fix a credential problem, so stop the sync.
            # Match the stable status text and base host, not the per-request path/query.
            "401 Client Error: Unauthorized for url: https://api.hetzner.cloud": "Your Hetzner Cloud API token is invalid or has been revoked. Create a new token in the Hetzner Cloud Console, then reconnect.",
            "403 Client Error: Forbidden for url: https://api.hetzner.cloud": "Your Hetzner Cloud API token does not have access to this project. Check the token and reconnect.",
        }

    def get_schemas(
        self,
        config: HetznerSourceConfig,
        team_id: int,
        with_counts: bool = False,
        names: list[str] | None = None,
        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 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,
        config: HetznerSourceConfig,
        team_id: int,
        schema_name: Optional[str] = None,
        api_version: str | None = None,
    ) -> tuple[bool, str | None]:
        return validate_hetzner_credentials(config.api_token)

    def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[HetznerResumeConfig]:
        return ResumableSourceManager[HetznerResumeConfig](inputs, HetznerResumeConfig)

    def source_for_pipeline(
        self,
        config: HetznerSourceConfig,
        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,
            )
        if inputs.schema_name in HETZNER_CHILD_ENDPOINTS:
            return hetzner_child_source(
                api_token=config.api_token,
                endpoint=inputs.schema_name,
                resumable_source_manager=resumable_source_manager,
            )
        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 list endpoint is full refresh
        )