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.4 KB
Raw Blame
from typing import Optional, cast

from products.warehouse_sources.sources.fleetio._config import FleetioSourceConfig
from products.warehouse_sources.sources.fleetio.fleetio import (
    DEFAULT_VERSION,
    FLEETIO_LEGACY_VERSION,
    SUPPORTED_VERSIONS,
    FleetioResumeConfig,
    fleetio_source,
    validate_credentials as validate_fleetio_credentials,
)
from products.warehouse_sources.sources.fleetio.settings import ENDPOINTS, INCREMENTAL_FIELDS
from products.warehouse_sources.sources.sdk import (
    CanonicalDescriptions,
    DataWarehouseSourceCategory,
    ExternalDataSourceType,
    FieldType,
    ReleaseStatus,
    ResumableSource,
    ResumableSourceManager,
    SourceConfig,
    SourceFieldInputConfig,
    SourceFieldInputConfigType,
    SourceInputs,
    SourceRegistry,
    SourceResponse,
    SourceSchema,
    VersionDeprecation,
    build_endpoint_schemas,
    detect,
)


@SourceRegistry.register
class FleetioSource(ResumableSource[FleetioSourceConfig, FleetioResumeConfig]):
    codebase_detection = detect(env=("^FLEETIO_",))

    supported_versions = SUPPORTED_VERSIONS
    default_version = DEFAULT_VERSION
    # Fleetio deprecated path-segment endpoint versions (`/api/v1`, `/api/v2`), which the "v1" pin
    # still reads, but still serves them and has announced no sunset date.
    deprecated_versions = (VersionDeprecation(version=FLEETIO_LEGACY_VERSION, sunset_at=None),)
    api_docs_url = "https://developer.fleetio.com/docs/overview/versioning"

    lists_tables_without_credentials = True  # static endpoint catalog — safe for public docs

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

    @property
    def connection_host_fields(self) -> list[str]:
        # `account_token` selects which Fleetio account the stored API key is sent to. Editing it on
        # an existing source must force the key to be re-entered — otherwise an editor could retarget
        # the preserved key at another Fleetio account, exposing it across a tenant boundary the user
        # never approved.
        return ["account_token"]

    @property
    def get_source_config(self) -> SourceConfig:
        return SourceConfig(
            name=ExternalDataSourceType.FLEETIO,
            category=DataWarehouseSourceCategory.PRODUCTIVITY,
            label="Fleetio",
            releaseStatus=ReleaseStatus.BETA,
            caption="""Enter your Fleetio API key and account token to pull your Fleetio fleet data into the PostHog Data warehouse.

Create an API key under **Account Menu → Account Settings → API Keys** in Fleetio. Your account token is shown on the same page (it identifies your Fleetio account).""",
            iconPath="/static/services/fleetio.png",
            docsUrl="https://posthog.com/docs/cdp/sources/fleetio",
            fields=cast(
                list[FieldType],
                [
                    SourceFieldInputConfig(
                        name="api_key",
                        label="API key",
                        type=SourceFieldInputConfigType.PASSWORD,
                        required=True,
                        placeholder="",
                        secret=True,
                    ),
                    SourceFieldInputConfig(
                        name="account_token",
                        label="Account token",
                        type=SourceFieldInputConfigType.TEXT,
                        required=True,
                        placeholder="",
                        secret=False,
                    ),
                ],
            ),
        )

    def get_canonical_descriptions(self) -> CanonicalDescriptions:
        from products.warehouse_sources.sources.fleetio.canonical_descriptions import CANONICAL_DESCRIPTIONS

        return CANONICAL_DESCRIPTIONS

    def get_non_retryable_errors(self) -> dict[str, str | None]:
        return {
            # 401/403 surface as a requests HTTPError when `_fetch_page` calls `raise_for_status()`.
            # Retrying can never satisfy a credential problem. Match the stable status text and base
            # host, not the per-request path/query.
            "401 Client Error: Unauthorized for url: https://secure.fleetio.com": "Your Fleetio API key or account token is invalid or has been revoked. Generate a new API key in your Fleetio account settings, then reconnect.",
            "403 Client Error: Forbidden for url: https://secure.fleetio.com": "Your Fleetio API key does not have permission to read this data. Check the key's permissions in your Fleetio account settings, then reconnect.",
        }

    def get_schemas(
        self,
        config: FleetioSourceConfig,
        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: FleetioSourceConfig,
        team_id: int,
        schema_name: Optional[str] = None,
        api_version: str | None = None,
    ) -> tuple[bool, str | None]:
        if validate_fleetio_credentials(config.api_key, config.account_token, self.resolve_api_version(api_version)):
            return True, None

        return False, "Invalid Fleetio API key or account token"

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

    def source_for_pipeline(
        self,
        config: FleetioSourceConfig,
        resumable_source_manager: ResumableSourceManager[FleetioResumeConfig],
        inputs: SourceInputs,
    ) -> SourceResponse:
        return fleetio_source(
            api_key=config.api_key,
            account_token=config.account_token,
            endpoint=inputs.schema_name,
            team_id=inputs.team_id,
            job_id=inputs.job_id,
            api_version=self.resolve_api_version(inputs.api_version),
            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,
        )