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.

7.6 KB
Raw Blame
from typing import Optional, cast

from products.warehouse_sources.sources.gong._config import GongSourceConfig
from products.warehouse_sources.sources.gong.gong import (
    GONG_BASE_URL,
    GongResumeConfig,
    gong_source,
    validate_credentials as validate_gong_credentials,
)
from products.warehouse_sources.sources.gong.settings import GONG_ENDPOINTS
from products.warehouse_sources.sources.sdk import (
    CanonicalDescriptions,
    DataWarehouseSourceCategory,
    ExternalDataSourceType,
    FieldType,
    ReleaseStatus,
    ResumableSource,
    ResumableSourceManager,
    SourceConfig,
    SourceFieldInputConfig,
    SourceFieldInputConfigType,
    SourceInputs,
    SourceRegistry,
    SourceResponse,
    SourceSchema,
    detect,
)


@SourceRegistry.register
class GongSource(ResumableSource[GongSourceConfig, GongResumeConfig]):
    codebase_detection = detect(env=("^GONG_",))

    supported_versions = ("v2",)
    default_version = "v2"

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

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

    @property
    def get_source_config(self) -> SourceConfig:
        return SourceConfig(
            name=ExternalDataSourceType.GONG,
            category=DataWarehouseSourceCategory.SALES,
            label="Gong",
            releaseStatus=ReleaseStatus.GA,
            caption="""Enter your Gong API credentials to pull your Gong data into the PostHog Data warehouse.

Create an **Access Key** and **Access Key Secret** in Gong under **Company Settings > Ecosystem > API**.

Grant the following read scopes so the connected endpoints can sync:
- `api:calls:read:basic`
- `api:users:read`
- `api:settings:scorecards:read`
- `api:workspaces:read`

To also sync the `calls_extensive` table (call participants and CRM associations) and the `calls_content` table (Gong's Call Spotlight summaries), additionally grant:
- `api:calls:read:extensive`

To also sync the `transcripts` table (what was said on each call), additionally grant:
- `api:calls:read:transcript`

To also sync the `calls_media` table (audio and video download URLs for each call, which Gong keeps valid for 8 hours), additionally grant:
- `api:calls:read:extensive`
- `api:calls:read:media-url`

To also sync these tables, additionally grant the scope listed next to each:
- `trackers` (keyword tracker definitions): `api:settings:trackers:read`
- `answered_scorecards` (scorecard reviews of calls): `api:stats:scorecards`
- `interaction_stats` (daily talk ratio, patience, and other conversation metrics per user): `api:stats:interaction`
- `daily_activity` (calls each user hosted, attended, listened to, shared, and gave feedback on, per day): `api:stats:user-actions:detailed`
- `call_outcomes` (the call outcome values defined for your company): `api:call-outcomes:read`
- `library_folders` and `library_folder_calls` (public call library folders and the calls in them): `api:library:read`
- `flows` (Gong Engage flows): `api:flows:read`
""",
            iconPath="/static/services/gong.png",
            docsUrl="https://posthog.com/docs/cdp/sources/gong",
            fields=cast(
                list[FieldType],
                [
                    SourceFieldInputConfig(
                        name="access_key",
                        label="Access key",
                        type=SourceFieldInputConfigType.TEXT,
                        required=True,
                        placeholder="Your Gong access key",
                        secret=False,
                    ),
                    SourceFieldInputConfig(
                        name="access_key_secret",
                        label="Access key secret",
                        type=SourceFieldInputConfigType.PASSWORD,
                        required=True,
                        placeholder="Your Gong access key secret",
                        secret=True,
                    ),
                ],
            ),
        )

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

        return CANONICAL_DESCRIPTIONS

    def get_schemas(
        self,
        config: GongSourceConfig,
        team_id: int,
        with_counts: bool = False,
        names: list[str] | None = None,
        force_refresh: bool = False,
        api_version: str | None = None,
    ) -> list[SourceSchema]:
        schemas = [
            SourceSchema(
                name=endpoint,
                supports_incremental=endpoint_config.supports_incremental,
                supports_append=endpoint_config.supports_incremental,
                incremental_fields=endpoint_config.incremental_fields,
                default_incremental_lookback_seconds=endpoint_config.default_incremental_lookback_seconds,
                should_sync_default=endpoint_config.should_sync_default,
                description=(
                    "Only syncs the last 365 days on initial sync"
                    if endpoint_config.supports_incremental
                    else "Syncs the last 365 days on every sync"
                )
                if endpoint_config.uses_date_window
                else None,
            )
            for endpoint, endpoint_config in GONG_ENDPOINTS.items()
        ]
        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: GongSourceConfig, team_id: int, schema_name: Optional[str] = None, api_version: str | None = None
    ) -> tuple[bool, str | None]:
        return validate_gong_credentials(config.access_key, config.access_key_secret, schema_name)

    def get_non_retryable_errors(self) -> dict[str, str | None]:
        return {
            f"401 Client Error: Unauthorized for url: {GONG_BASE_URL}": "Your Gong access key or secret is invalid. Please generate new credentials and reconnect.",
            f"403 Client Error: Forbidden for url: {GONG_BASE_URL}": "Your Gong credentials do not have the required permissions. Please check the granted scopes and try again.",
            # Gong rejects this request outright (not the empty-window 404 the endpoint otherwise
            # expects) when the account's Call Library feature isn't enabled — every retry replays
            # the same unfiltered request and fails identically.
            f"400 Client Error: Bad Request for url: {GONG_BASE_URL}/v2/library/folders": "Your Gong account doesn't have the Call Library feature enabled, so library folders can't be listed. Disable the library_folders and library_folder_calls tables, or contact Gong to enable Call Library access, then try again.",
        }

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

    def source_for_pipeline(
        self,
        config: GongSourceConfig,
        resumable_source_manager: ResumableSourceManager[GongResumeConfig],
        inputs: SourceInputs,
    ) -> SourceResponse:
        return gong_source(
            access_key=config.access_key,
            access_key_secret=config.access_key_secret,
            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,
        )