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.

11.9 KB
Raw Blame
from typing import Optional, cast

from products.warehouse_sources.sources.honeycomb._config import HoneycombSourceConfig
from products.warehouse_sources.sources.honeycomb.honeycomb import (
    HoneycombResumeConfig,
    honeycomb_source,
    validate_credentials as validate_honeycomb_credentials,
)
from products.warehouse_sources.sources.honeycomb.settings import (
    ENDPOINTS,
    HONEYCOMB_ENDPOINTS,
    INCREMENTAL_FIELDS,
    HoneycombScope,
)
from products.warehouse_sources.sources.sdk import (
    CanonicalDescriptions,
    DataWarehouseSourceCategory,
    ExternalDataSourceType,
    FieldType,
    ProductKey,
    ReleaseStatus,
    ResumableSource,
    ResumableSourceManager,
    SourceConfig,
    SourceFieldInputConfig,
    SourceFieldInputConfigType,
    SourceFieldSelectConfig,
    SourceFieldSelectConfigOption,
    SourceInputs,
    SourceRegistry,
    SourceResponse,
    SourceSchema,
    detect,
)


@SourceRegistry.register
class HoneycombSource(ResumableSource[HoneycombSourceConfig, HoneycombResumeConfig]):
    codebase_detection = detect(
        env=(
            "^HONEYCOMB_",
            "^HONEYCOMBIO_APIKEY$",
            "^LIBHONEY_API_KEY$",
            "^LIBHONEY_DATASET$",
            "^LIBHONEY_API_HOST$",
            "^BUILDEVENT_APIKEY$",
            "^BUILDEVENT_DATASET$",
            "^BUILDEVENT_APIHOST$",
            "^REFINERY_HONEYCOMB_",
        ),
        npm=(
            "@honeycombio/opentelemetry-node",
            "honeycomb-beeline",
            "@honeycombio/opentelemetry-web",
            "libhoney",
            "@honeycombio/opentelemetry-react-native",
            "@honeycombio/experimental-opentelemetry-web",
            "@cloudflare/workers-honeycomb-logger",
            "@cloudflare/pages-plugin-honeycomb",
        ),
        pypi=(
            "honeycomb-beeline",
            "libhoney",
            "honeycomb-opentelemetry",
            "honeycomb-pycpp",
            "opentelemetry-ext-honeycomb",
        ),
        cargo=("libhoney-rust", "tracing-honeycomb"),
        cocoapods=("LibHoney",),
        go=(
            "github.com/honeycombio/beeline-go",
            "github.com/honeycombio/libhoney-go",
            "github.com/honeycombio/otel-config-go",
            "github.com/honeycombio/honeycomb-opentelemetry-go",
            "github.com/honeycombio/opentelemetry-exporter-go",
            "github.com/honeycombio/opentelemetry-samplers-go",
            "github.com/honeycombio/opencensus-exporter",
        ),
        maven=(
            "io.honeycomb.libhoney:libhoney-java",
            "io.honeycomb:honeycomb-opentelemetry-sdk",
            "io.honeycomb:honeycomb-opentelemetry-javaagent",
            "io.honeycomb:libhoney-java",
            "io.honeycomb.android:honeycomb-opentelemetry-android",
            "io.honeycomb.android:honeycomb-opentelemetry-android-compose",
            "io.honeycomb.android:honeycomb-opentelemetry-android-interaction",
            "io.honeycomb.android:honeycomb-proguard-uuid-plugin",
            "io.honeycomb.beeline:beeline-core",
            "io.honeycomb.beeline:beeline-spring-boot-starter",
            "io.honeycomb.beeline:beeline-spring-boot-sleuth-starter",
            "io.honeycomb.opentelemetry:honeycomb-opentelemetry-exporters",
            "io.honeycomb.opentelemetry:honeycomb-opentelemetry-samplers",
        ),
        rubygems=(
            "honeycomb-beeline",
            "libhoney",
            "honeycomb-opentelemetry",
            "honeycomb-rails",
            "rack-honeycomb",
            "faraday-honeycomb",
            "sequel-honeycomb",
            "activerecord-honeycomb",
            "fluent-plugin-honeycomb",
            "logstash-output-honeycomb_json_batch",
        ),
        swiftpm=("github.com/honeycombio/honeycomb-opentelemetry-swift", "github.com/honeycombio/libhoney-cocoa"),
        alternative_to=(ProductKey.TRACING,),
    )

    lists_tables_without_credentials = True  # static endpoint catalog — safe for public docs
    supported_versions = ("1",)  # v1 API, addressed via the /1/ URL path prefix
    default_version = "1"
    api_docs_url = "https://docs.honeycomb.io/api/"

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

    @property
    def get_source_config(self) -> SourceConfig:
        return SourceConfig(
            name=ExternalDataSourceType.HONEYCOMB,
            category=DataWarehouseSourceCategory.ENGINEERING___MONITORING,
            label="Honeycomb",
            releaseStatus=ReleaseStatus.BETA,
            caption="""Enter a Honeycomb configuration API key to pull your Honeycomb observability configuration — datasets, SLOs, burn alerts, triggers, markers, boards, and more — into the PostHog Data warehouse.

You can create a configuration key under **Environment settings → API keys** in your [Honeycomb account](https://ui.honeycomb.io/). Grant read access for the resources you want to sync: Manage Queries and Columns, Manage SLOs, Manage Triggers, Manage Markers, Manage Boards, Manage Recipients, and Manage Signals.

Keys are region-specific — pick the region that matches your Honeycomb account.""",
            iconPath="/static/services/honeycomb.png",
            docsUrl="https://posthog.com/docs/cdp/sources/honeycomb",
            keywords=["observability", "slo", "tracing"],
            fields=cast(
                list[FieldType],
                [
                    SourceFieldInputConfig(
                        name="api_key",
                        label="Configuration API key",
                        type=SourceFieldInputConfigType.PASSWORD,
                        required=True,
                        placeholder="Configuration key",
                        secret=True,
                    ),
                    SourceFieldSelectConfig(
                        name="region",
                        label="Region",
                        required=True,
                        defaultValue="us",
                        options=[
                            SourceFieldSelectConfigOption(label="US (api.honeycomb.io)", value="us"),
                            SourceFieldSelectConfigOption(label="EU (api.eu1.honeycomb.io)", value="eu"),
                        ],
                    ),
                ],
            ),
        )

    def get_non_retryable_errors(self) -> dict[str, str | None]:
        # 401/403 surface as a requests HTTPError when `_fetch_page` calls `raise_for_status()`.
        # No amount of retrying fixes a bad, revoked, or under-permissioned key, so stop the
        # sync. Match the stable status text and base host (one per region), not the
        # per-request path/query.
        return {
            "401 Client Error: Unauthorized for url: https://api.honeycomb.io": "Your Honeycomb API key is invalid, revoked, or for a different region. Create a configuration key in your Honeycomb environment settings, then reconnect.",
            "401 Client Error: Unauthorized for url: https://api.eu1.honeycomb.io": "Your Honeycomb API key is invalid, revoked, or for a different region. Create a configuration key in your Honeycomb environment settings, then reconnect.",
            "403 Client Error: Forbidden for url: https://api.honeycomb.io": "Your Honeycomb API key is missing a permission needed to sync this data. Grant the matching access (e.g. Manage SLOs, Manage Triggers) on the key, then reconnect.",
            "403 Client Error: Forbidden for url: https://api.eu1.honeycomb.io": "Your Honeycomb API key is missing a permission needed to sync this data. Grant the matching access (e.g. Manage SLOs, Manage Triggers) on the key, then reconnect.",
            "Honeycomb SLO counts history is unavailable": "Honeycomb SLO counts history needs the Enterprise plan, with the feature turned on for your team by Honeycomb. Ask your Honeycomb account team to turn it on, or stop syncing the slo_counts_history table.",
        }

    def get_canonical_descriptions(self) -> CanonicalDescriptions:
        from products.warehouse_sources.sources.honeycomb.canonical_descriptions import (
            CANONICAL_DESCRIPTIONS,  # noqa: PLC0415
        )

        return CANONICAL_DESCRIPTIONS

    def get_schemas(
        self,
        config: HoneycombSourceConfig,
        team_id: int,
        with_counts: bool = False,
        names: list[str] | None = None,
        force_refresh: bool = False,
        api_version: str | None = None,
    ) -> list[SourceSchema]:
        def _description(endpoint: str) -> str | None:
            endpoint_config = HONEYCOMB_ENDPOINTS[endpoint]
            if endpoint == "recipients":
                return (
                    "Credential-bearing recipient fields (integration keys, webhook URLs and secrets) "
                    "are redacted during sync."
                )
            if endpoint_config.scope is HoneycombScope.PER_SLO:
                return "One row per burn alert per dataset, fetched by walking every dataset's SLOs."
            if endpoint_config.scope is HoneycombScope.PER_SLO_TIME_WINDOW:
                return (
                    "Hourly good and bad event counts per SLO. Requires the Honeycomb Enterprise plan "
                    "with SLO counts history enabled for your team."
                )
            if endpoint_config.scope is HoneycombScope.ENVIRONMENT_PAGINATED:
                return "Anomaly Detection Signals. Requires the Manage Signals permission on the API key."
            if endpoint_config.scope is HoneycombScope.PER_SIGNAL_TIME_WINDOW:
                return (
                    "Resolved anomalies for every Anomaly Detection Signal. Requires the Manage Signals "
                    "permission on the API key."
                )
            if endpoint_config.include_environment_wide:
                return "Includes environment-wide rows under the __all__ dataset slug alongside per-dataset rows."
            return None

        def _build_schema(endpoint: str) -> SourceSchema:
            endpoint_config = HONEYCOMB_ENDPOINTS[endpoint]
            # Only endpoints with a server-side time filter advertise incremental fields; the
            # config endpoints have none, so a client-side cursor would still walk every row.
            # Append stays off: the latest SLO counts bucket is partial and must be merged.
            return SourceSchema(
                name=endpoint,
                supports_incremental=bool(endpoint_config.incremental_fields),
                supports_append=False,
                incremental_fields=INCREMENTAL_FIELDS.get(endpoint, []),
                should_sync_default=endpoint_config.should_sync_default,
                description=_description(endpoint),
            )

        schemas = [_build_schema(endpoint) for endpoint in ENDPOINTS]
        if names is not None:
            names_set = set(names)
            schemas = [s for s in schemas if s.name in names_set]
        return schemas

    def validate_credentials(
        self,
        config: HoneycombSourceConfig,
        team_id: int,
        schema_name: Optional[str] = None,
        api_version: str | None = None,
    ) -> tuple[bool, str | None]:
        return validate_honeycomb_credentials(config.api_key, config.region)

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

    def source_for_pipeline(
        self,
        config: HoneycombSourceConfig,
        resumable_source_manager: ResumableSourceManager[HoneycombResumeConfig],
        inputs: SourceInputs,
    ) -> SourceResponse:
        return honeycomb_source(
            api_key=config.api_key,
            region=config.region,
            endpoint=inputs.schema_name,
            logger=inputs.logger,
            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
            ),
        )