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.

6.7 KB
Raw Blame
from typing import Optional, cast

from products.warehouse_sources.sources.luma._config import LumaSourceConfig
from products.warehouse_sources.sources.luma.luma import (
    LumaResumeConfig,
    check_access,
    luma_source,
    validate_credentials,
)
from products.warehouse_sources.sources.luma.settings import ENDPOINTS, LUMA_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 LumaSource(ResumableSource[LumaSourceConfig, LumaResumeConfig]):
    codebase_detection = detect(env=("^LUMA_",), script_hosts=("embed.lu.ma",))

    lists_tables_without_credentials = True  # static endpoint catalog — safe for public docs
    supported_versions = ("v1",)
    default_version = "v1"
    api_docs_url = "https://docs.luma.com/reference"

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

    @property
    def get_source_config(self) -> SourceConfig:
        return SourceConfig(
            name=ExternalDataSourceType.LUMA,
            category=DataWarehouseSourceCategory.PRODUCTIVITY,
            label="Luma",
            releaseStatus=ReleaseStatus.GA,
            caption="""Enter your Luma API key to pull your events, guests, and people into the PostHog Data warehouse.

You can create an API key under **Settings → Developer** in [Luma](https://luma.com) — API access requires a Luma Plus subscription. Calendar API keys are scoped to a single calendar; use an organization API key to import across calendars.
""",
            iconPath="/static/services/luma.png",
            docsUrl="https://posthog.com/docs/cdp/sources/luma",
            fields=cast(
                list[FieldType],
                [
                    SourceFieldInputConfig(
                        name="api_key",
                        label="API key",
                        type=SourceFieldInputConfigType.PASSWORD,
                        required=True,
                        placeholder="",
                        secret=True,
                    ),
                ],
            ),
        )

    def get_canonical_descriptions(self) -> CanonicalDescriptions:
        from products.warehouse_sources.sources.luma.canonical_descriptions import (
            CANONICAL_DESCRIPTIONS,  # noqa: PLC0415
        )

        return CANONICAL_DESCRIPTIONS

    def get_retry_exhausted_errors(self) -> dict[str, str]:
        return {
            "Luma API error (retryable): status=429": (
                "Luma's API rate limit ran out before this sync finished. "
                "Set this table to sync less often, such as every 6 hours, so each run stays within the limit."
            ),
        }

    def get_non_retryable_errors(self) -> dict[str, str | None]:
        return {
            "401 Client Error: Unauthorized for url: https://public-api.luma.com": "Your Luma API key is invalid or has been revoked. Generate a new key under Settings → Developer in Luma, then reconnect.",
            "403 Client Error: Forbidden for url: https://public-api.luma.com": "Your Luma API key does not have access to this data. Check the key's calendar or organization scope, then reconnect.",
        }

    def get_retryable_errors(self) -> set[str]:
        # 429/5xx are already retried in-process by `_fetch_page`'s tenacity backoff (see luma.py);
        # if that budget still exhausts, Temporal's activity retry picks it back up, so this is
        # self-recovering rather than a tracked-exception-worthy failure.
        return {"Luma API error (retryable): status=429", "Luma API error (retryable): status=5"}

    def get_schemas(
        self,
        config: LumaSourceConfig,
        team_id: int,
        with_counts: bool = False,
        names: list[str] | None = None,
        force_refresh: bool = False,
        api_version: str | None = None,
    ) -> list[SourceSchema]:
        # Every endpoint is full refresh only — Luma's cursor pagination has no server-side
        # updated-since filter (list-events only bounds on event start time), so there is no
        # reliable timestamp cursor to advance an incremental sync.
        schemas = [
            SourceSchema(
                name=endpoint,
                supports_incremental=False,
                supports_append=False,
                incremental_fields=[],
            )
            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: LumaSourceConfig, team_id: int, schema_name: Optional[str] = None, api_version: str | None = None
    ) -> tuple[bool, str | None]:
        # The API key grants read access to every endpoint on its calendar/organization, so a
        # single probe validates access to every schema.
        return validate_credentials(config.api_key)

    def get_endpoint_permissions(
        self, config: LumaSourceConfig, team_id: int, endpoints: list[str], api_version: str | None = None
    ) -> dict[str, str | None]:
        permissions: dict[str, str | None] = {}
        for endpoint in endpoints:
            endpoint_config = LUMA_ENDPOINTS.get(endpoint)
            if endpoint_config is None or not endpoint_config.requires_organization_key:
                permissions[endpoint] = None
                continue
            status, _ = check_access(config.api_key, endpoint_config.path)
            permissions[endpoint] = (
                "Requires a Luma organization API key. Calendar API keys can't list organization calendars."
                if status in (400, 401, 403)
                else None
            )
        return permissions

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

    def source_for_pipeline(
        self,
        config: LumaSourceConfig,
        resumable_source_manager: ResumableSourceManager[LumaResumeConfig],
        inputs: SourceInputs,
    ) -> SourceResponse:
        if inputs.schema_name not in LUMA_ENDPOINTS:
            raise ValueError(f"Unknown Luma schema '{inputs.schema_name}'")

        return luma_source(
            api_key=config.api_key,
            endpoint=inputs.schema_name,
            logger=inputs.logger,
            resumable_source_manager=resumable_source_manager,
        )