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.buildkite._config import BuildkiteSourceConfig
from products.warehouse_sources.sources.buildkite.buildkite import (
    BuildkiteResumeConfig,
    buildkite_source,
    validate_credentials as validate_buildkite_credentials,
)
from products.warehouse_sources.sources.buildkite.canonical_descriptions import CANONICAL_DESCRIPTIONS
from products.warehouse_sources.sources.buildkite.settings import (
    DESCRIPTIONS,
    ENDPOINTS,
    INCREMENTAL_FIELDS,
    MERGE_ONLY,
    SHOULD_SYNC_DEFAULT,
)
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 BuildkiteSource(ResumableSource[BuildkiteSourceConfig, BuildkiteResumeConfig]):
    codebase_detection = detect(
        env=("^BUILDKITE_",),
        npm=("@buildkite/buildkite-sdk",),
        go=(
            "github.com/buildkite/go-buildkite",
            "github.com/buildkite/buildkite-agent-metrics",
            "github.com/buildkite/buildkite-agent-scaler",
            "github.com/buildkite/buildkite-gha",
            "github.com/buildkite/buildkite-logs",
            "github.com/buildkite/buildkite-mcp-server",
            "github.com/buildkite/git-credential-helper-buildkite-oidc",
        ),
    )

    lists_tables_without_credentials = True  # static endpoint catalog — safe for public docs
    supported_versions = ("v2",)
    default_version = "v2"
    api_docs_url = "https://buildkite.com/docs/apis/rest-api"

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

    @property
    def connection_host_fields(self) -> list[str]:
        # The token is sent to api.buildkite.com against <organization>, so retargeting the
        # organization must force re-entry of the token.
        return ["organization"]

    @property
    def get_source_config(self) -> SourceConfig:
        return SourceConfig(
            name=ExternalDataSourceType.BUILDKITE,
            category=DataWarehouseSourceCategory.ENGINEERING___MONITORING,
            label="Buildkite",
            releaseStatus=ReleaseStatus.GA,
            docsUrl="https://posthog.com/docs/cdp/sources/buildkite",
            caption="""Enter your Buildkite API access token and organization slug to sync your CI/CD data into the PostHog Data warehouse.

You can create an API access token in your [Buildkite account settings](https://buildkite.com/user/api-access-tokens).

Make sure to grant the following read scopes:
- `read_organizations`
- `read_pipelines`
- `read_builds`
- `read_artifacts`
- `read_agents`
- `read_clusters`
- `read_teams`
- `read_suites`
""",
            iconPath="/static/services/buildkite.png",
            fields=cast(
                list[FieldType],
                [
                    SourceFieldInputConfig(
                        name="api_access_token",
                        label="API access token",
                        type=SourceFieldInputConfigType.PASSWORD,
                        required=True,
                        placeholder="bkua_...",
                        secret=True,
                    ),
                    SourceFieldInputConfig(
                        name="organization",
                        label="Organization slug",
                        type=SourceFieldInputConfigType.TEXT,
                        required=True,
                        placeholder="my-organization",
                        secret=False,
                    ),
                ],
            ),
        )

    def get_non_retryable_errors(self) -> dict[str, str | None]:
        return {
            # An invalid or revoked token surfaces as a requests HTTPError when the REST client
            # calls `raise_for_status()`. Retrying can't satisfy a credential problem, so stop the sync.
            "401 Client Error: Unauthorized for url: https://api.buildkite.com": "Your Buildkite API access token is invalid or has been revoked. Create a new token in your Buildkite account settings, then reconnect.",
            "403 Client Error: Forbidden for url: https://api.buildkite.com": "Your Buildkite API access token is missing the read scope needed to sync this data. Grant the required read scopes in your Buildkite account settings, then reconnect.",
        }

    def get_canonical_descriptions(self) -> CanonicalDescriptions:
        return CANONICAL_DESCRIPTIONS

    def get_schemas(
        self,
        config: BuildkiteSourceConfig,
        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,
            merge_only=MERGE_ONLY,
            descriptions=DESCRIPTIONS,
            should_sync_default=SHOULD_SYNC_DEFAULT,
        )

    def validate_credentials(
        self,
        config: BuildkiteSourceConfig,
        team_id: int,
        schema_name: Optional[str] = None,
        api_version: str | None = None,
    ) -> tuple[bool, str | None]:
        return validate_buildkite_credentials(config.api_access_token, config.organization, schema_name)

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

    def source_for_pipeline(
        self,
        config: BuildkiteSourceConfig,
        resumable_source_manager: ResumableSourceManager[BuildkiteResumeConfig],
        inputs: SourceInputs,
    ) -> SourceResponse:
        return buildkite_source(
            api_access_token=config.api_access_token,
            organization=config.organization,
            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,
        )