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.

5.9 KB
Raw Blame
from typing import Optional, cast

from products.warehouse_sources.sources.front._config import FrontSourceConfig
from products.warehouse_sources.sources.front.front import (
    FrontResumeConfig,
    front_source,
    validate_credentials as validate_front_credentials,
)
from products.warehouse_sources.sources.front.settings import ENDPOINTS, FRONT_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 FrontSource(ResumableSource[FrontSourceConfig, FrontResumeConfig]):
    codebase_detection = detect(
        env=("^FRONTAPP_", "^FRONT_API_"),
        script_hosts=("chat-assets.frontapp.com",),
        npm=("front-chat-sdk", "@frontapp/plugin-sdk"),
    )

    api_docs_url = "https://dev.frontapp.com"

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

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

    @property
    def get_source_config(self) -> SourceConfig:
        return SourceConfig(
            name=ExternalDataSourceType.FRONT,
            category=DataWarehouseSourceCategory.CUSTOMER_SUPPORT,
            label="Front",
            releaseStatus=ReleaseStatus.GA,
            caption="""Enter your Front API token to sync your Front data into the PostHog Data warehouse.

You can create an API token in your [Front settings](https://app.frontapp.com/settings/tools/api) under **Developers > API tokens**.

Grant read scopes for the resources you want to sync (e.g. `shared_resources:read`, `contacts:read`, `tags:read`).""",
            iconPath="/static/services/front.png",
            docsUrl="https://posthog.com/docs/cdp/sources/front",
            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.front.canonical_descriptions import CANONICAL_DESCRIPTIONS

        return CANONICAL_DESCRIPTIONS

    def get_non_retryable_errors(self) -> dict[str, str | None]:
        return {
            "401 Client Error": "Invalid Front API token. Please reconnect with a valid token.",
            "403 Client Error": "Your Front API token does not have the required scope for this resource.",
        }

    def get_schemas(
        self,
        config: FrontSourceConfig,
        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,
            descriptions={
                "events": "Only syncs the last 365 days on initial sync",
                "conversation_messages": "Fetched one conversation at a time, so a sync takes longer the more conversations you have",
                "conversation_comments": "Fetched one conversation at a time, so a sync takes longer the more conversations you have",
                "conversation_followers": "Fetched one conversation at a time, so a sync takes longer the more conversations you have",
                "contact_list_contacts": "Fetched one contact list at a time, so a sync takes longer the more contact lists you have",
            },
        )

    def validate_credentials(
        self, config: FrontSourceConfig, team_id: int, schema_name: Optional[str] = None, api_version: str | None = None
    ) -> tuple[bool, str | None]:
        if schema_name is None:
            # Source-create probe: any non-401 response means the token is genuine. Accept 403 here
            # so a scope-limited token still connects (the user grants scopes per resource).
            return validate_front_credentials(config.api_token, "/teammates", require_scope=False)

        endpoint_config = FRONT_ENDPOINTS.get(schema_name)
        if endpoint_config is None:
            path = "/teammates"
        elif endpoint_config.fanout is not None:
            # A fan-out path needs a parent id we don't have here, so probe the parent listing.
            path = FRONT_ENDPOINTS[endpoint_config.fanout.parent_name].path
        else:
            path = endpoint_config.path
        return validate_front_credentials(config.api_token, path, require_scope=True)

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

    def source_for_pipeline(
        self,
        config: FrontSourceConfig,
        resumable_source_manager: ResumableSourceManager[FrontResumeConfig],
        inputs: SourceInputs,
    ) -> SourceResponse:
        return front_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,
            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,
        )