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.

7.1 KB
Raw Blame
from typing import Optional, cast

from products.warehouse_sources.sources.bluesky._config import BlueskySourceConfig
from products.warehouse_sources.sources.bluesky.bluesky import (
    BlueskyResumeConfig,
    bluesky_source,
    normalize_actor,
    post_fanout_rows,
    validate_credentials as validate_bluesky_credentials,
)
from products.warehouse_sources.sources.bluesky.settings import ENDPOINTS, INCREMENTAL_FIELDS, POST_FANOUT_ENDPOINTS
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,
)

# Every table is keyed on the id the AT Protocol guarantees is globally unique: post AT-URIs are
# scoped by the author's own DID, and account DIDs are unique across the whole network. Post
# fan-out tables also carry the parent post's URI, since one account can like many posts.
PRIMARY_KEYS: dict[str, list[str]] = {
    "Profile": ["did"],
    "Posts": ["uri"],
    "Followers": ["did"],
    "Follows": ["did"],
    "Likes": ["post_uri", "actor_did"],
    "Quotes": ["quoted_post_uri", "uri"],
}

# Stable, top-level datetime fields only (see partition-key-stability guidance): `indexedAt` is
# set once when the AppView first indexes a post and isn't documented to change after that, and
# an account's own `createdAt` never changes. Nested fields (e.g. the post record's own
# `createdAt`) are avoided here since this source doesn't rely on the pipeline's nested-column
# flattening convention. Profile is a single row per sync, so it isn't partitioned.
PARTITION_FIELDS: dict[str, list[str]] = {
    "Posts": ["indexedAt"],
    "Followers": ["createdAt"],
    "Follows": ["createdAt"],
    "Likes": ["indexedAt"],
    "Quotes": ["indexedAt"],
}


@SourceRegistry.register
class BlueskySource(ResumableSource[BlueskySourceConfig, BlueskyResumeConfig]):
    codebase_detection = detect(
        env=("^BLUESKY_",),
        script_hosts=("embed.bsky.app",),
        npm=("@atproto/api",),
        pypi=("atproto",),
        cargo=("atrium-api", "bsky-sdk"),
        go=("github.com/bluesky-social/indigo",),
        pub=("bluesky", "bluesky_cli", "bluesky_text", "bluesky_text_flutter"),
    )

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

    # The AT Protocol's XRPC methods aren't versioned (no path segment, header, or query param
    # pins a release), so there's nothing to declare beyond the docs link.
    api_docs_url = "https://docs.bsky.app/docs/category/http-reference"

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

    def get_non_retryable_errors(self) -> dict[str, str | None]:
        return {
            "400 Client Error": "Bluesky couldn't find that handle or DID. Check the spelling and reconnect.",
            # Bluesky's public, unauthenticated AppView returns 403 when the account has hidden
            # its posts from logged-out viewers, and this source only ever calls that API.
            "403 Client Error": (
                "This account has hidden its posts from logged-out viewers on Bluesky. Ask the account "
                "owner to allow logged-out access in their Bluesky privacy settings, then reconnect."
            ),
        }

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

        return CANONICAL_DESCRIPTIONS

    def get_schemas(
        self,
        config: BlueskySourceConfig,
        team_id: int,
        with_counts: bool = False,
        names: list[str] | None = None,
        force_refresh: bool = False,
        api_version: str | None = None,
    ) -> list[SourceSchema]:
        return build_endpoint_schemas(ENDPOINTS, INCREMENTAL_FIELDS, names)

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

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

    def source_for_pipeline(
        self,
        config: BlueskySourceConfig,
        resumable_source_manager: ResumableSourceManager[BlueskyResumeConfig],
        inputs: SourceInputs,
    ) -> SourceResponse:
        actor = normalize_actor(config.actor)
        partition_keys = PARTITION_FIELDS.get(inputs.schema_name)
        if inputs.schema_name in POST_FANOUT_ENDPOINTS:
            return SourceResponse(
                name=inputs.schema_name,
                items=lambda: post_fanout_rows(actor, inputs.schema_name, resumable_source_manager),
                primary_keys=PRIMARY_KEYS[inputs.schema_name],
                partition_mode="datetime",
                partition_keys=partition_keys,
            )

        resource = bluesky_source(
            actor=actor,
            endpoint=inputs.schema_name,
            team_id=inputs.team_id,
            job_id=inputs.job_id,
            resumable_source_manager=resumable_source_manager,
        )
        return SourceResponse(
            name=resource.name,
            items=lambda: resource,
            primary_keys=PRIMARY_KEYS[inputs.schema_name],
            column_hints=resource.column_hints,
            partition_mode="datetime" if partition_keys else None,
            partition_keys=partition_keys,
        )

    @property
    def get_source_config(self) -> SourceConfig:
        return SourceConfig(
            name=ExternalDataSourceType.BLUESKY,
            category=DataWarehouseSourceCategory.MARKETING___EMAIL,
            label="Bluesky",
            caption=(
                "Sync a Bluesky account's profile, posts, followers, follows, and the likes and quotes "
                "on its posts. Uses Bluesky's "
                "public AppView API, so you only need the handle or DID you want to track, not an "
                "account password or app password."
            ),
            docsUrl="https://posthog.com/docs/cdp/sources/bluesky",
            iconPath="/static/services/bluesky.png",
            keywords=["social", "atproto", "at protocol"],
            releaseStatus=ReleaseStatus.GA,
            fields=cast(
                list[FieldType],
                [
                    SourceFieldInputConfig(
                        name="actor",
                        label="Handle or DID",
                        type=SourceFieldInputConfigType.TEXT,
                        required=True,
                        placeholder="jay.bsky.team",
                        secret=False,
                        caption="The Bluesky handle (e.g. `jay.bsky.team`) or DID of the account to sync.",
                    ),
                ],
            ),
        )