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.

10.7 KB
Raw Blame
from typing import Optional, cast

from products.warehouse_sources.sources.gladly._config import GladlySourceConfig
from products.warehouse_sources.sources.gladly.gladly import (
    GladlyResumeConfig,
    gladly_source,
    validate_credentials as validate_gladly_credentials,
)
from products.warehouse_sources.sources.gladly.settings import (
    ENDPOINTS,
    EVENT_ENDPOINTS,
    INCREMENTAL_FIELDS,
    INCREMENTAL_LOOKBACK_SECONDS,
    REPORT_ENDPOINTS,
    SHOULD_SYNC_DEFAULT,
)
from products.warehouse_sources.sources.sdk import (
    CanonicalDescriptions,
    DataWarehouseSourceCategory,
    ExternalDataSourceType,
    FieldType,
    ReleaseStatus,
    ResumableSource,
    ResumableSourceManager,
    SourceConfig,
    SourceFieldInputConfig,
    SourceFieldInputConfigType,
    SourceFieldSelectConfig,
    SourceFieldSelectConfigOption,
    SourceInputs,
    SourceRegistry,
    SourceResponse,
    SourceSchema,
    build_endpoint_schemas,
    detect,
)


@SourceRegistry.register
class GladlySource(ResumableSource[GladlySourceConfig, GladlyResumeConfig]):
    codebase_detection = detect(env=("^GLADLY_",), script_hosts=("cdn.gladly.com", "chat-sdk.cdn.gladly.com"))

    supported_versions = ("v1",)
    default_version = "v1"
    api_docs_url = "https://developer.gladly.com"

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

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

    @property
    def connection_host_fields(self) -> list[str]:
        # `organization` and `domain` together determine the host the stored token is
        # sent to; retargeting either must re-require the token.
        return ["organization", "domain"]

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

        return CANONICAL_DESCRIPTIONS

    def get_non_retryable_errors(self) -> dict[str, str | None]:
        return {
            "401 Client Error: Unauthorized for url": "Gladly authentication failed. Please check your agent email and API token.",
            "403 Client Error: Forbidden for url": "Gladly denied access. Please check that the agent has the API User permission.",
            # Raised by `_report_rows` when a CSV report lacks a keyed column. The same window returns
            # the same header on a retry, so neither the sync nor the incremental-field picker can
            # fix it. The copy names Gladly first and PostHog support as the fallback for the
            # renamed-column case, where the report exists.
            "Gladly report is missing required columns": (
                "Gladly returned data that doesn't match the report this table needs, so there was "
                "no data to sync. This usually means Gladly could not build the report for your "
                "account. Ask Gladly support to check the report is available for your account. If "
                "Gladly confirms it is, contact PostHog support."
            ),
            "Gladly report unavailable for this account": (
                "Gladly returned an error every time PostHog asked for the report this table syncs "
                "from, and the table has never synced. Ask Gladly support to make the report "
                "available for your account, then re-enable this table. If Gladly confirms it is "
                "available, contact PostHog support."
            ),
        }

    def get_retryable_errors(self) -> set[str]:
        # `_report_rows` streams the report CSV while it yields rows (see gladly.py), so a stall in
        # Gladly's report generation past REQUEST_TIMEOUT_SECONDS raises the bare urllib3
        # read-timeout mid-stream, after `generate_report`'s own retry-on-`requests.ReadTimeout` has
        # already returned a response, so it isn't caught there either. Temporal's activity retry
        # regenerates the report and re-streams it; the resumable window state means only the
        # in-flight window is redone, deduped on merge, so this is self-recovering rather than a
        # tracked-exception-worthy failure.
        #
        # `GladlyRetryableError` (429/5xx from Gladly, raised by both `fetch` and `generate_report`)
        # is itself retried with backoff inside gladly.py before it can ever reach here; if that
        # budget still exhausts, Temporal's activity retry re-issues the same request or report
        # window, so the same self-recovering reasoning applies.
        return {"Read timed out", "Gladly returned no report", "Gladly API error (retryable)"}

    def get_retry_exhausted_errors(self) -> dict[str, str]:
        return {
            "Gladly returned no report": (
                "Gladly returned an error instead of the report this table syncs from, so this run "
                "did not finish. This is usually a short problem in Gladly's report generation. The "
                "sync will run again on its next schedule."
            ),
        }

    @property
    def get_source_config(self) -> SourceConfig:
        return SourceConfig(
            name=ExternalDataSourceType.GLADLY,
            category=DataWarehouseSourceCategory.CUSTOMER_SUPPORT,
            label="Gladly",
            caption="""Connect your Gladly account to pull your customer service data into the PostHog Data warehouse.

Your organization is the part of your Gladly URL before `.gladly.com`. For `myorg.gladly.com` enter `myorg`, and for `myorg.us-1.gladly.com` enter `myorg.us-1`. The API token must belong to an agent with the API User permission (Settings > API Tokens). Leave the domain on Production unless you are connecting a Gladly sandbox, which is served on `gladly.qa`. Data comes from Gladly's scheduled export jobs, which retain files for 14 days. History older than that requires asking Gladly support to regenerate exports. The voice transcripts table reads the calls and voicemails in those same exports and makes one request per call. The conversations and tasks tables are built from Gladly's Conversation Export and Task Export reports instead, so they are not limited to the 14-day export window. The conversation timestamps, contact timestamps, and work session events tables also come from Gladly's reports and reach back 90 days on their first sync. The teams, inboxes, and answers tables are read in full on every sync. Gladly keeps events for 24 hours only, so the events table needs to sync more often than once a day, for example every 12 hours, to keep a full history.""",
            iconPath="/static/services/gladly.png",
            docsUrl="https://posthog.com/docs/cdp/sources/gladly",
            releaseStatus=ReleaseStatus.GA,
            fields=cast(
                list[FieldType],
                [
                    SourceFieldInputConfig(
                        name="organization",
                        label="Organization",
                        type=SourceFieldInputConfigType.TEXT,
                        required=True,
                        placeholder="myorg",
                        secret=False,
                    ),
                    SourceFieldInputConfig(
                        name="agent_email",
                        label="Agent email",
                        type=SourceFieldInputConfigType.EMAIL,
                        required=True,
                        placeholder="[email protected]",
                        secret=False,
                    ),
                    SourceFieldInputConfig(
                        name="api_token",
                        label="API token",
                        type=SourceFieldInputConfigType.PASSWORD,
                        required=True,
                        placeholder="",
                        secret=True,
                    ),
                    SourceFieldSelectConfig(
                        name="domain",
                        label="Gladly domain",
                        required=True,
                        defaultValue="gladly.com",
                        options=[
                            SourceFieldSelectConfigOption(label="Production (gladly.com)", value="gladly.com"),
                            SourceFieldSelectConfigOption(label="Sandbox (gladly.qa)", value="gladly.qa"),
                        ],
                    ),
                ],
            ),
        )

    def get_schemas(
        self,
        config: GladlySourceConfig,
        team_id: int,
        with_counts: bool = False,
        names: list[str] | None = None,
        force_refresh: bool = False,
        api_version: str | None = None,
    ) -> list[SourceSchema]:
        # Report and event windows are re-read on resume and behind the
        # watermark, so appending would duplicate rows (merge_only). The
        # event-grain tables are high-volume, so they start opt-in
        # (should_sync_default).
        schemas = build_endpoint_schemas(
            ENDPOINTS,
            INCREMENTAL_FIELDS,
            names,
            merge_only=(*REPORT_ENDPOINTS, *EVENT_ENDPOINTS),
            should_sync_default=SHOULD_SYNC_DEFAULT,
        )
        # Conversation and work-session report rows restate in place as records
        # change, so their incremental runs re-read a trailing window to catch
        # the restatements.
        for schema in schemas:
            schema.default_incremental_lookback_seconds = INCREMENTAL_LOOKBACK_SECONDS.get(schema.name)
        return schemas

    def validate_credentials(
        self,
        config: GladlySourceConfig,
        team_id: int,
        schema_name: Optional[str] = None,
        api_version: str | None = None,
    ) -> tuple[bool, str | None]:
        return validate_gladly_credentials(config.organization, config.agent_email, config.api_token, config.domain)

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

    def source_for_pipeline(
        self,
        config: GladlySourceConfig,
        resumable_source_manager: ResumableSourceManager[GladlyResumeConfig],
        inputs: SourceInputs,
    ) -> SourceResponse:
        return gladly_source(
            organization=config.organization,
            agent_email=config.agent_email,
            api_token=config.api_token,
            endpoint=inputs.schema_name,
            logger=inputs.logger,
            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,
            domain=config.domain,
            schema_has_ever_synced=inputs.schema_has_ever_synced,
        )