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.convex._config import ConvexSourceConfig
from products.warehouse_sources.sources.convex.convex import (
    ConvexDataSyncCursor,
    ConvexResumeConfig,
    convex_source,
    get_json_schemas,
    iter_component_tables,
    qualified_table_name,
    validate_credentials as validate_convex_credentials,
    validate_deploy_url,
)
from products.warehouse_sources.sources.sdk import (
    CursorSource,
    DataWarehouseSourceCategory,
    ExternalDataSourceType,
    FieldType,
    IncrementalField,
    IncrementalFieldType,
    ReleaseStatus,
    ResumableSource,
    ResumableSourceManager,
    SourceConfig,
    SourceFieldInputConfig,
    SourceFieldInputConfigType,
    SourceInputs,
    SourceRegistry,
    SourceResponse,
    SourceSchema,
    detect,
)


@SourceRegistry.register
class ConvexSource(ResumableSource[ConvexSourceConfig, ConvexResumeConfig], CursorSource[ConvexDataSyncCursor]):
    codebase_detection = detect(
        env=("^CONVEX_", "^NEXT_PUBLIC_CONVEX_URL$", "^VITE_CONVEX_URL$"),
        npm=("convex",),
        pypi=("convex",),
        cargo=("convex", "convex_sync_types"),
        maven=("dev.convex:android-convexmobile", "dev.convex:android-convex-auth0"),
        swiftpm=("github.com/get-convex/convex-swift", "github.com/get-convex/convex-swift-auth0"),
    )

    api_docs_url = "https://docs.convex.dev/"

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

    @property
    def get_source_config(self) -> SourceConfig:
        return SourceConfig(
            name=ExternalDataSourceType.CONVEX,
            category=DataWarehouseSourceCategory.DATABASES,
            label="Convex",
            releaseStatus=ReleaseStatus.GA,
            caption="""Enter your Convex deployment URL and deploy key to sync your Convex tables into PostHog.

You can find your deployment URL and deploy key in your [Convex Dashboard](https://dashboard.convex.dev/) under **Settings** > **URL & Deploy Key**.

**Note:** This integration requires the [Convex Professional plan](https://www.convex.dev/plans) for streaming export access.
""",
            iconPath="/static/services/convex.png",
            fields=cast(
                list[FieldType],
                [
                    SourceFieldInputConfig(
                        name="deploy_url",
                        label="Deployment URL",
                        type=SourceFieldInputConfigType.TEXT,
                        required=True,
                        placeholder="https://your-deployment-123.convex.cloud",
                        secret=False,
                    ),
                    SourceFieldInputConfig(
                        name="deploy_key",
                        label="Deploy key",
                        type=SourceFieldInputConfigType.PASSWORD,
                        required=True,
                        placeholder="prod:...",
                        secret=True,
                    ),
                ],
            ),
        )

    def get_schemas(
        self,
        config: ConvexSourceConfig,
        team_id: int,
        with_counts: bool = False,
        names: list[str] | None = None,
        force_refresh: bool = False,
        api_version: str | None = None,
    ) -> list[SourceSchema]:
        clean_url = validate_deploy_url(config.deploy_url)
        schemas_response = get_json_schemas(clean_url, config.deploy_key)

        tables: list[str] = [
            qualified_table_name(component_path, table_name)
            for component_path, table_name in iter_component_tables(schemas_response)
        ]

        incremental_field: list[IncrementalField] = [
            IncrementalField(
                label="_ts",
                type=IncrementalFieldType.Integer,
                field="_ts",
                field_type=IncrementalFieldType.Integer,
            )
        ]

        if names is not None:
            names_set = set(names)
            tables = [t for t in tables if t in names_set]

        return [
            SourceSchema(
                name=table_name,
                supports_incremental=True,
                supports_append=True,
                incremental_fields=incremental_field,
            )
            for table_name in tables
        ]

    def get_non_retryable_errors(self) -> dict[str, str | None]:
        return {
            "401 Client Error": "Authentication failed. Check your Convex deploy key.",
            "403 Client Error": "Access denied. Check your Convex deploy key.",
            # Convex answers a read with a 404 when the table discovery listed is gone at read time
            # (deleted on the source, or a component table streaming export doesn't serve). The next
            # run reissues the identical request, so every retry replays the same 404. Cloudflare
            # surfaces transient edge problems as the 52x/530 family instead (retried in
            # `_CONVEX_RETRY`), so a 404 is never a transient blip that this could disable a sync over.
            "404 Client Error": (
                "PostHog couldn't find this table in your Convex deployment. It was likely deleted, so "
                "turn off syncing for this table, then re-enable the sync."
            ),
            "StreamingExportNotEnabled": "Streaming export requires the Convex Professional plan. See https://www.convex.dev/plans to upgrade.",
            # get_json_schemas fetches every table's schema in one call, so a single table whose
            # schema has a union of object types fails discovery for the whole deployment, not
            # just that table. Convex's export API doesn't support this shape at all, so every
            # retry resubmits the same deployment schema and fails identically - only a schema
            # change on the Convex side can clear it.
            "UnsupportedSchemaForExport": (
                "A table in this Convex deployment has a schema Convex can't export (a union of "
                "object types). Change that field's type in your Convex schema, then retry."
            ),
            # A deploy key that cannot be encoded into an Authorization header is rejected before
            # any request leaves PostHog, so every retry rebuilds the same unsendable request. The
            # user has to re-enter the key, which makes this a credential error rather than a blip.
            "contains characters PostHog can't send to Convex": (
                "PostHog can't send your Convex deploy key. Copy the key again from your Convex "
                "dashboard, then update this source's credentials."
            ),
            # Convex treats a `list_snapshot` cursor conflict as deterministic rather than transient. It
            # surfaces when a data import or backup restore invalidates the cursor's position, so every
            # retry replays the same request against the same now-invalid cursor.
            "409 Client Error": (
                "PostHog's sync position for this table no longer matches your Convex deployment. "
                "This can happen after a data import or backup restore. Trigger a full resync of "
                "this source to continue syncing."
            ),
        }

    def get_retryable_errors(self) -> set[str]:
        # `_CONVEX_RETRY` (convex.py) already retries 429/5xx, including the Cloudflare 52x/530
        # family Convex deployments can surface, at the urllib3 layer before this can even raise.
        # A response that still exhausts that budget is a transient Convex/edge blip, not a bug,
        # so Temporal's activity retry recovers once it clears rather than surfacing it as tracked
        # exception noise. `requests.Response.raise_for_status` derives these prefixes from the
        # status code alone, not the vendor's reason text, so they're stable to match on.
        # A read timeout or dropped connection retries the same way, at both the urllib3 adapter
        # (POST is in `_CONVEX_RETRY.allowed_methods`) and the `_convex_get`/`_convex_post` tenacity
        # decorator. The deployment host is customer-specific, so match urllib3's stable wrapper
        # text instead of a fixed host (see adjust/app_store_connect for the fixed-host equivalent).
        return {"Server Error", "429 Client Error", "Convex full resync requested", "Max retries exceeded with url:"}

    def validate_credentials(
        self,
        config: ConvexSourceConfig,
        team_id: int,
        schema_name: Optional[str] = None,
        api_version: str | None = None,
    ) -> tuple[bool, str | None]:
        return validate_convex_credentials(config.deploy_url, config.deploy_key)

    def cursor_class(self) -> type[ConvexDataSyncCursor]:
        return ConvexDataSyncCursor

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

    def source_for_pipeline(
        self,
        config: ConvexSourceConfig,
        resumable_source_manager: ResumableSourceManager[ConvexResumeConfig],
        inputs: SourceInputs,
    ) -> SourceResponse:
        return convex_source(
            deploy_url=config.deploy_url,
            deploy_key=config.deploy_key,
            inputs=inputs,
            cursor_manager=self.get_cursor_manager(inputs),
            resumable_source_manager=resumable_source_manager,
        )