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.

4.9 KB
Raw Blame
from typing import Optional, cast

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,
)
from products.warehouse_sources.sources.tmdb._config import TMDbSourceConfig
from products.warehouse_sources.sources.tmdb.settings import ENDPOINTS, INCREMENTAL_FIELDS, SHOULD_SYNC_DEFAULT
from products.warehouse_sources.sources.tmdb.tmdb import (
    TMDbResumeConfig,
    endpoint_supports_resume,
    tmdb_source,
    validate_credentials as validate_tmdb_credentials,
)


@SourceRegistry.register
class TMDbSource(ResumableSource[TMDbSourceConfig, TMDbResumeConfig]):
    codebase_detection = detect(env=("^(TM_DB|TMDB)_",))

    supported_versions = ("3",)
    default_version = "3"
    api_docs_url = "https://developer.themoviedb.org/reference/intro/getting-started"

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

    @property
    def credential_kind(self) -> str | None:
        return "tmdb"

    def resume_covers_run(
        self,
        *,
        incremental_or_append: bool,
        schema_name: str | None = None,
    ) -> bool:
        # An endpoint that cannot checkpoint restarts from the first title on every attempt, so the
        # larger resumable retry budget would only repeat the whole fan-out.
        return schema_name is None or schema_name not in ENDPOINTS or endpoint_supports_resume(schema_name)

    @property
    def get_source_config(self) -> SourceConfig:
        return SourceConfig(
            name=ExternalDataSourceType.TMDB,
            category=DataWarehouseSourceCategory.ANALYTICS,
            label="TMDb",
            caption="""Enter your TMDB API key to pull movie, TV, and people catalog data into the PostHog Data warehouse.

Create a free API key (v3 auth) in your [TMDB account settings](https://www.themoviedb.org/settings/api). Commercial use requires a separate license from TMDB.""",
            iconPath="/static/services/tmdb.png",
            docsUrl="https://posthog.com/docs/cdp/sources/tmdb",
            releaseStatus=ReleaseStatus.GA,
            fields=cast(
                list[FieldType],
                [
                    SourceFieldInputConfig(
                        name="api_key",
                        label="API key",
                        type=SourceFieldInputConfigType.PASSWORD,
                        required=True,
                        placeholder="",
                        secret=True,
                    ),
                ],
            ),
        )

    def get_non_retryable_errors(self) -> dict[str, str | None]:
        return {
            # An invalid or revoked TMDB API key surfaces as a 401 whose HTTPError message the client
            # scrubs the api_key from but keeps this host prefix. Retrying can't fix a credential
            # problem, so stop the sync.
            "401 Client Error: Unauthorized for url: https://api.themoviedb.org": "Your TMDB API key is invalid or has been revoked. Create a new key in your TMDB account settings, then reconnect.",
        }

    def get_schemas(
        self,
        config: TMDbSourceConfig,
        team_id: int,
        with_counts: bool = False,
        names: list[str] | None = None,
        force_refresh: bool = False,
        api_version: str | None = None,
    ) -> list[SourceSchema]:
        # TMDB v3 list endpoints expose no server-side updated-after filter, so every endpoint has
        # empty incremental fields and is full refresh only.
        return build_endpoint_schemas(ENDPOINTS, INCREMENTAL_FIELDS, names, should_sync_default=SHOULD_SYNC_DEFAULT)

    def validate_credentials(
        self, config: TMDbSourceConfig, team_id: int, schema_name: Optional[str] = None, api_version: str | None = None
    ) -> tuple[bool, str | None]:
        return validate_tmdb_credentials(config.api_key)

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

        return CANONICAL_DESCRIPTIONS

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

    def source_for_pipeline(
        self,
        config: TMDbSourceConfig,
        resumable_source_manager: ResumableSourceManager[TMDbResumeConfig],
        inputs: SourceInputs,
    ) -> SourceResponse:
        return tmdb_source(
            api_key=config.api_key,
            endpoint=inputs.schema_name,
            team_id=inputs.team_id,
            job_id=inputs.job_id,
            resumable_source_manager=resumable_source_manager,
        )