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.6 KB
Raw Blame
from typing import Optional, cast

from products.warehouse_sources.sources.notion._config import NotionSourceConfig
from products.warehouse_sources.sources.notion.notion import (
    ADMIN_TOKEN_FORBIDDEN_ERROR,
    ADMIN_TOKEN_INVALID_ERROR,
    ADMIN_TOKEN_MISSING_ERROR,
    NOTION_VERSION_2025_09_03,
    NOTION_VERSION_2026_03_11,
    NotionResumeConfig,
    check_permission_groups_access,
    notion_source,
    validate_credentials as validate_notion_credentials,
)
from products.warehouse_sources.sources.notion.settings import ENDPOINTS, INCREMENTAL_FIELDS
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 NotionSource(ResumableSource[NotionSourceConfig, NotionResumeConfig]):
    codebase_detection = detect(
        env=("^NOTION_", "^NOTION_TOKEN$"),
        npm=(
            "@notionhq/client",
            "@notionhq/notion-mcp-server",
            "@notionhq/workers",
            "@notionhq/apps",
            "@notionhq/custom-blocks",
            "@notionhq/custom-blocks-host",
            "@notionhq/custom-blocks-dev-shell",
            "@notionhq/lore",
            "ntn",
            "notion-to-md",
            "react-notion-x",
            "notion-client",
            "@tryfabric/martian",
        ),
        pypi=("notion-client", "notion"),
        cargo=("notion-client", "notion"),
        cocoapods=("NotionSwift",),
        composer=("fiveam-code/laravel-notion-api", "mariosimao/notion-sdk-php"),
        go=("github.com/jomei/notionapi", "github.com/dstotijn/go-notion"),
        maven=("com.github.seratch:notion-sdk-jvm-core",),
        pub=("notion_api",),
        rubygems=("notion-ruby-client",),
        swiftpm=("github.com/chojnac/notionswift",),
    )

    supported_versions = (NOTION_VERSION_2025_09_03, NOTION_VERSION_2026_03_11)
    default_version = NOTION_VERSION_2026_03_11
    api_docs_url = "https://developers.notion.com/page/changelog"

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

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

    def get_non_retryable_errors(self) -> dict[str, str | None]:
        # The Admin API entries come first: they share the api.notion.com prefix, and the first match wins.
        return {
            "Notion permission_groups table requires an organization bot token": ADMIN_TOKEN_MISSING_ERROR,
            "401 Client Error: Unauthorized for url: https://api.notion.com/admin": ADMIN_TOKEN_INVALID_ERROR,
            "403 Client Error: Forbidden for url: https://api.notion.com/admin": ADMIN_TOKEN_FORBIDDEN_ERROR,
            "401 Client Error: Unauthorized for url: https://api.notion.com": "Your Notion integration token is invalid or expired. Please generate a new token and reconnect.",
            "403 Client Error: Forbidden for url: https://api.notion.com": "Your Notion integration is missing the required capabilities, or the pages/databases you want to sync have not been shared with it.",
        }

    def get_retryable_errors(self) -> set[str]:
        # A 5xx or a 429 is already retried internally with backoff (see notion.py's
        # tenacity-wrapped _request, which honors Notion's Retry-After on 429s); if those retries
        # still exhaust, the failure is transient and self-recovering, so let Temporal retry the
        # activity without surfacing it as tracked exception noise.
        return {
            "Notion API error (retryable)",
            "Notion rate limited",
            # A 2xx whose body is empty or non-JSON is a truncated/garbled response, retried in-process
            # by `_request`. If those retries exhaust, the condition is transient and self-recovering,
            # so let Temporal retry the activity instead of surfacing it as tracked exception noise.
            "Notion returned a non-JSON response",
            # `_request`'s tenacity retry also covers `requests.ConnectionError` (which
            # `requests.exceptions.SSLError` subclasses) and `requests.ReadTimeout`. urllib3
            # wraps both as "... Max retries exceeded with url: ..." regardless of the underlying
            # cause (TLS EOF, refused connection, timeout), so match that stable prefix rather
            # than the per-request URL or nested error id.
            "Max retries exceeded with url",
            # Defensive fallback for the mid-TLS-handshake drop: the same self-recovering condition
            # ClickHouse already classifies this way. These stable OpenSSL SSLEOFError strings sit
            # inside the MaxRetryError message above, so match them too and the SSL EOF case stays
            # recognized even if that outer wrapper ever changes.
            "UNEXPECTED_EOF_WHILE_READING",
            "EOF occurred in violation of protocol",
        }

    @property
    def get_source_config(self) -> SourceConfig:
        return SourceConfig(
            name=ExternalDataSourceType.NOTION,
            category=DataWarehouseSourceCategory.PRODUCTIVITY,
            label="Notion",
            releaseStatus=ReleaseStatus.GA,
            caption="""Enter your Notion internal integration token to pull your Notion data into the PostHog Data warehouse.

Create an internal integration at [notion.so/my-integrations](https://www.notion.so/my-integrations) and copy its token (starts with `ntn_` or `secret_`).

Then **share** each page or database you want to sync with the integration (via the page's `•••` menu → Connections), otherwise it will not be visible to the sync.

To sync the `permission_groups` table, also enter an organization bot token with the `permission-group:read` scope. Organization owners create these tokens in the Notion organization console. This needs a Notion Enterprise plan.
""",
            iconPath="/static/services/notion.png",
            docsUrl="https://posthog.com/docs/cdp/sources/notion",
            fields=cast(
                list[FieldType],
                [
                    SourceFieldInputConfig(
                        name="api_key",
                        label="API key",
                        type=SourceFieldInputConfigType.PASSWORD,
                        required=True,
                        placeholder="ntn_...",
                        secret=True,
                    ),
                    SourceFieldInputConfig(
                        name="admin_api_key",
                        label="Organization bot token (optional)",
                        type=SourceFieldInputConfigType.PASSWORD,
                        required=False,
                        placeholder="",
                        secret=True,
                    ),
                ],
            ),
        )

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

        return CANONICAL_DESCRIPTIONS

    def get_schemas(
        self,
        config: NotionSourceConfig,
        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=False,
                supports_append=False,
                incremental_fields=INCREMENTAL_FIELDS.get(endpoint, []),
            )
            for endpoint in list(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: NotionSourceConfig,
        team_id: int,
        schema_name: Optional[str] = None,
        api_version: str | None = None,
    ) -> tuple[bool, str | None]:
        # Pre-creation calls pass no pin and resolve to default_version (what new rows are
        # stamped with); a pinned source revalidates under its own `Notion-Version` header.
        return validate_notion_credentials(config.api_key, self.resolve_api_version(api_version))

    def get_endpoint_permissions(
        self,
        config: NotionSourceConfig,
        team_id: int,
        endpoints: list[str],
        api_version: str | None = None,
    ) -> dict[str, str | None]:
        permissions: dict[str, str | None] = dict.fromkeys(endpoints)
        if "permission_groups" in permissions:
            permissions["permission_groups"] = check_permission_groups_access(
                config.api_key, config.admin_api_key, self.resolve_api_version(api_version)
            )
        return permissions

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

    def source_for_pipeline(
        self,
        config: NotionSourceConfig,
        resumable_source_manager: ResumableSourceManager[NotionResumeConfig],
        inputs: SourceInputs,
    ) -> SourceResponse:
        return notion_source(
            token=config.api_key,
            endpoint=inputs.schema_name,
            logger=inputs.logger,
            resumable_source_manager=resumable_source_manager,
            api_version=self.resolve_api_version(inputs.api_version),
            admin_token=config.admin_api_key,
        )