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.

9.3 KB
Raw Blame
from typing import Optional, cast

from products.warehouse_sources.sources.mux._config import MuxSourceConfig
from products.warehouse_sources.sources.mux.mux import (
    DEFAULT_VALIDATION_PATH,
    MuxResumeConfig,
    get_validation_status,
    mux_source,
)
from products.warehouse_sources.sources.mux.settings import ENDPOINTS, INCREMENTAL_FIELDS, MUX_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 MuxSource(ResumableSource[MuxSourceConfig, MuxResumeConfig]):
    codebase_detection = detect(
        env=("^MUX_",),
        script_hosts=("src.litix.io",),
        npm=("@mux/mux-node", "@mux/mux-player", "@mux/mux-player-react", "@mux/upchunk", "mux-embed"),
        pypi=("mux-python",),
        cocoapods=("Mux-Stats-AVPlayer",),
        composer=("muxinc/mux-php",),
        go=("github.com/muxinc/mux-go",),
        hex=("mux",),
        maven=("com.mux:mux-sdk-java",),
        rubygems=("mux_ruby",),
        swiftpm=("github.com/muxinc/mux-stats-sdk-avplayer",),
    )

    api_docs_url = "https://www.mux.com/docs/api-reference"
    # `get_schemas` iterates a static endpoint catalog with no I/O, so the table list is safe to
    # render in the public docs without credentials.
    lists_tables_without_credentials = True

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

    @property
    def get_source_config(self) -> SourceConfig:
        return SourceConfig(
            name=ExternalDataSourceType.MUX,
            category=DataWarehouseSourceCategory.ANALYTICS,
            label="Mux",
            releaseStatus=ReleaseStatus.GA,
            caption="""Enter your Mux Access Token ID and Secret Key to pull your Mux Video and Mux Data into the PostHog Data warehouse.

Create an access token under [Settings → Access Tokens](https://dashboard.mux.com/settings/access-tokens) in your Mux dashboard. Tokens are scoped to a single Mux environment.

Grant the following read permissions:
- **Mux Video** (read) — required for assets, live streams, uploads, playback restrictions and transcription vocabularies
- **Mux Data** (read) — required for video views, errors, aggregate metrics (watch time, plays, viewer experience), metric timeseries and breakdowns, and dimensions
- **Mux System** (read) — required for signing keys
""",
            iconPath="/static/services/mux.png",
            docsUrl="https://posthog.com/docs/cdp/sources/mux",
            fields=cast(
                list[FieldType],
                [
                    SourceFieldInputConfig(
                        name="access_token_id",
                        label="Access Token ID",
                        type=SourceFieldInputConfigType.TEXT,
                        required=True,
                        placeholder="",
                        secret=False,
                    ),
                    SourceFieldInputConfig(
                        name="secret_key",
                        label="Secret Key",
                        type=SourceFieldInputConfigType.PASSWORD,
                        required=True,
                        placeholder="",
                        secret=True,
                    ),
                ],
            ),
        )

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

        return CANONICAL_DESCRIPTIONS

    def get_non_retryable_errors(self) -> dict[str, str | None]:
        return {
            # A bad/revoked token surfaces as a 401 when `_fetch_page` calls `raise_for_status()`;
            # a token missing the required read scope surfaces as a 403 at sync time. Neither can be
            # fixed by retrying. Match the stable status text and base host, not the per-request path.
            "401 Client Error: Unauthorized for url: https://api.mux.com": "Your Mux access token is invalid or has been revoked. Create a new access token in your Mux dashboard, then reconnect.",
            "403 Client Error: Forbidden for url: https://api.mux.com": "Your Mux access token is missing the read permissions needed to sync this data. Grant Mux Video, Mux Data and Mux System read access, then reconnect.",
            # A Mux Data endpoint returns a 400 with `type: invalid_timeframe` when the requested
            # `timeframe[]` window reaches past the history the account keeps. Mux Data retention
            # depends on the plan, so the same window can succeed for one account and be rejected by
            # another; the request never becomes valid on retry. The REST engine appends the Mux error
            # `type` to the message as `code=invalid_timeframe`, so match that.
            "code=invalid_timeframe": (
                "Mux rejected the time range this sync requested as invalid. This usually means the range "
                "reaches further back than your Mux plan keeps. Check your Mux Data retention window, or "
                "contact PostHog support if this keeps happening."
            ),
            # Some Mux Data accounts reject `max_request_latency` timeseries queries with a 400 and
            # the generic `code=bad_request` (no specific sub-code), regardless of the timeframe —
            # every request/credential/scope here is otherwise valid, so retrying replays the same
            # rejection. Matched on the path plus the query prefix (not just `code=bad_request`,
            # which Mux also returns for genuinely malformed requests on other endpoints) so a 5xx/
            # timeout for this same URL — whose message carries no query string — stays retryable.
            "metrics/max_request_latency/timeseries?timeframe": (
                "Mux rejected the request-latency metric sync for this account. This can happen when "
                "the account's Mux Data plan doesn't include request-latency metrics. Contact PostHog "
                "support if this keeps happening."
            ),
        }

    def get_schemas(
        self,
        config: MuxSourceConfig,
        team_id: int,
        with_counts: bool = False,
        names: list[str] | None = None,
        force_refresh: bool = False,
        api_version: str | None = None,
    ) -> list[SourceSchema]:
        # Only video views expose a server-side timestamp filter (`view_end`), so it can sync
        # incrementally; every other endpoint is full refresh. Append is never offered — the
        # incremental overlap re-fetches boundary rows, which only a merge (not append) can dedupe.
        def _build_schema(endpoint: str) -> SourceSchema:
            endpoint_config = MUX_ENDPOINTS[endpoint]
            return SourceSchema(
                name=endpoint,
                supports_incremental=endpoint_config.supports_incremental,
                supports_append=False,
                incremental_fields=INCREMENTAL_FIELDS.get(endpoint, []),
                should_sync_default=endpoint_config.should_sync_default,
            )

        schemas = [_build_schema(endpoint) for endpoint in ENDPOINTS]
        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: MuxSourceConfig, team_id: int, schema_name: Optional[str] = None, api_version: str | None = None
    ) -> tuple[bool, str | None]:
        path = MUX_ENDPOINTS[schema_name].path if schema_name in MUX_ENDPOINTS else DEFAULT_VALIDATION_PATH
        status = get_validation_status(config.access_token_id, config.secret_key, path)

        if status == 200:
            return True, None

        # 401 means the token itself is bad. A 403 means the token is genuine but lacks the scope for
        # this endpoint — accept it at source-create (schema_name is None) since users may only grant
        # scopes for the streams they want; re-raise it only when validating a specific schema.
        if status == 403 and schema_name is None:
            return True, None

        if status == 403:
            return False, "Your Mux access token does not have permission to read this data."

        return False, "Invalid Mux access token. Check the Access Token ID and Secret Key."

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

    def source_for_pipeline(
        self,
        config: MuxSourceConfig,
        resumable_source_manager: ResumableSourceManager[MuxResumeConfig],
        inputs: SourceInputs,
    ) -> SourceResponse:
        return mux_source(
            access_token_id=config.access_token_id,
            secret_key=config.secret_key,
            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,
        )