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.

feat(data-warehouse): add Bluesky import source (#84321)

Tom Owers82c563ca0db7
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/bluesky/bluesky.py b/products/warehouse_sources/backend/temporal/data_imports/sources/bluesky/bluesky.py
new file mode 100644
index 000000000000..c24d3c0a9e8f
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/bluesky/bluesky.py
@@ -0,0 +1,135 @@
+from typing import Any, Optional
+
+from posthog.dataclasses import frozen
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.bluesky.settings import BASE_URL
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.http import make_tracked_session
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source import (
+ RESTAPIConfig,
+ rest_api_resource,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.paginators import (
+ JSONResponseCursorPaginator,
+ SinglePagePaginator,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.resource import Resource
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.typing import EndpointResource
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+
+
+@frozen
+class BlueskyResumeConfig:
+ cursor: str
+
+
+def _cursor_paginator() -> JSONResponseCursorPaginator:
+ # Bluesky returns the next cursor as a bare top-level `cursor` field (not nested, unlike the
+ # `cursors.next` shape the paginator defaults to), echoed back as the `cursor` query param.
+ return JSONResponseCursorPaginator(cursor_path="cursor", cursor_param="cursor")
+
+
+def get_resource(name: str, actor: str) -> EndpointResource:
+ resources: dict[str, EndpointResource] = {
+ "Profile": {
+ "name": "Profile",
+ "table_name": "profile",
+ "write_disposition": "replace",
+ "table_format": "delta",
+ "endpoint": {
+ "path": "/xrpc/app.bsky.actor.getProfile",
+ "params": {"actor": actor},
+ "data_selector": "$",
+ "paginator": SinglePagePaginator(),
+ },
+ },
+ "Posts": {
+ "name": "Posts",
+ "table_name": "posts",
+ "write_disposition": "replace",
+ "table_format": "delta",
+ "endpoint": {
+ "path": "/xrpc/app.bsky.feed.getAuthorFeed",
+ # `posts_no_replies` keeps this table to the author's own posts and reposts,
+ # matching what most brand/marketing tracking cares about (own content, not
+ # every reply the account has made).
+ "params": {"actor": actor, "limit": 100, "filter": "posts_no_replies"},
+ "data_selector": "feed[*].post",
+ "paginator": _cursor_paginator(),
+ },
+ },
+ "Followers": {
+ "name": "Followers",
+ "table_name": "followers",
+ "write_disposition": "replace",
+ "table_format": "delta",
+ "endpoint": {
+ "path": "/xrpc/app.bsky.graph.getFollowers",
+ "params": {"actor": actor, "limit": 100},
+ "data_selector": "followers",
+ "paginator": _cursor_paginator(),
+ },
+ },
+ "Follows": {
+ "name": "Follows",
+ "table_name": "follows",
+ "write_disposition": "replace",
+ "table_format": "delta",
+ "endpoint": {
+ "path": "/xrpc/app.bsky.graph.getFollows",
+ "params": {"actor": actor, "limit": 100},
+ "data_selector": "follows",
+ "paginator": _cursor_paginator(),
+ },
+ },
+ }
+ return resources[name]
+
+
+def bluesky_source(
+ actor: str,
+ endpoint: str,
+ team_id: int,
+ job_id: str,
+ resumable_source_manager: ResumableSourceManager[BlueskyResumeConfig],
+) -> Resource:
+ config: RESTAPIConfig = {
+ "client": {"base_url": BASE_URL},
+ "resources": [get_resource(endpoint, actor)],
+ }
+
+ initial_paginator_state: Optional[dict[str, Any]] = None
+ if resumable_source_manager.can_resume():
+ resume_config = resumable_source_manager.load_state()
+ if resume_config is not None:
+ initial_paginator_state = {"cursor": resume_config.cursor}
+
+ def save_checkpoint(state: Optional[dict[str, Any]]) -> None:
+ # Only persist when there's a next page to resume to; the Redis TTL handles cleanup on
+ # completion, and the single-page Profile endpoint never produces a cursor here.
+ if state and state.get("cursor"):
+ resumable_source_manager.save_state(BlueskyResumeConfig(cursor=str(state["cursor"])))
+
+ return rest_api_resource(
+ config,
+ team_id,
+ job_id,
+ db_incremental_field_last_value=None,
+ resume_hook=save_checkpoint,
+ initial_paginator_state=initial_paginator_state,
+ )
+
+
+def validate_credentials(actor: str) -> tuple[bool, str | None]:
+ session = make_tracked_session()
+ response = session.get(f"{BASE_URL}/xrpc/app.bsky.actor.getProfile", params={"actor": actor})
+ if response.status_code == 200:
+ return True, None
+
+ try:
+ message = response.json().get("message")
+ except ValueError:
+ message = None
+
+ if response.status_code == 400:
+ return False, message or "That handle or DID couldn't be found on Bluesky. Check the spelling and try again."
+ return False, message or f"Bluesky returned an unexpected error ({response.status_code})."
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/bluesky/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/bluesky/canonical_descriptions.py
new file mode 100644
index 000000000000..61dd90868754
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/bluesky/canonical_descriptions.py
@@ -0,0 +1,69 @@
+"""Canonical, documentation-sourced descriptions for Bluesky (AT Protocol) endpoints and columns.
+
+Sourced from the official Bluesky HTTP API reference (https://docs.bsky.app/docs/category/http-reference).
+Keyed by the resource names in `settings.py` `ENDPOINTS`, which match the `ExternalDataSchema.name`
+of a synced Bluesky table. Columns absent here fall back to LLM enrichment.
+"""
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (
+ CanonicalDescriptions,
+)
+
+CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
+ "Profile": {
+ "description": "The configured account's public Bluesky profile.",
+ "docs_url": "https://docs.bsky.app/docs/api/app-bsky-actor-get-profile",
+ "columns": {
+ "did": "The account's decentralized identifier, a stable, globally unique account id.",
+ "handle": "The account's current handle (e.g. jay.bsky.team).",
+ "displayName": "The account's display name.",
+ "description": "The account's bio text.",
+ "avatar": "URL of the account's avatar image.",
+ "banner": "URL of the account's profile banner image.",
+ "followersCount": "Number of accounts following this account.",
+ "followsCount": "Number of accounts this account follows.",
+ "postsCount": "Number of posts this account has made.",
+ "createdAt": "Time the account was created.",
+ "indexedAt": "Time the AppView last indexed this profile.",
+ },
+ },
+ "Posts": {
+ "description": "Posts and reposts from the configured account's feed, newest first.",
+ "docs_url": "https://docs.bsky.app/docs/api/app-bsky-feed-get-author-feed",
+ "columns": {
+ "uri": "The post's AT-URI, globally unique across the network.",
+ "cid": "The post record's content hash.",
+ "author": "The author's profile, embedded in the post.",
+ "record": "The raw post record, including its text and creation time.",
+ "replyCount": "Number of replies to the post.",
+ "repostCount": "Number of reposts of the post.",
+ "likeCount": "Number of likes on the post.",
+ "quoteCount": "Number of quote posts of the post.",
+ "indexedAt": "Time the AppView first indexed the post.",
+ },
+ },
+ "Followers": {
+ "description": "Accounts following the configured account.",
+ "docs_url": "https://docs.bsky.app/docs/api/app-bsky-graph-get-followers",
+ "columns": {
+ "did": "The follower's decentralized identifier.",
+ "handle": "The follower's current handle.",
+ "displayName": "The follower's display name.",
+ "description": "The follower's bio text.",
+ "createdAt": "Time the follower's account was created.",
+ "indexedAt": "Time the AppView last indexed the follower's profile.",
+ },
+ },
+ "Follows": {
+ "description": "Accounts the configured account follows.",
+ "docs_url": "https://docs.bsky.app/docs/api/app-bsky-graph-get-follows",
+ "columns": {
+ "did": "The followed account's decentralized identifier.",
+ "handle": "The followed account's current handle.",
+ "displayName": "The followed account's display name.",
+ "description": "The followed account's bio text.",
+ "createdAt": "Time the followed account was created.",
+ "indexedAt": "Time the AppView last indexed the followed account's profile.",
+ },
+ },
+}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/bluesky/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/bluesky/settings.py
new file mode 100644
index 000000000000..115b57230f3e
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/bluesky/settings.py
@@ -0,0 +1,17 @@
+from products.warehouse_sources.backend.types import IncrementalField
+
+# Bluesky's public AppView (see `bluesky.py`). No auth is required for any of the endpoints below.
+BASE_URL = "https://public.api.bsky.app"
+
+ENDPOINTS = (
+ "Profile",
+ "Posts",
+ "Followers",
+ "Follows",
+)
+
+# None of these endpoints expose a server-side timestamp filter (e.g. `since`/`updated_after`) --
+# they only support opaque cursor pagination -- so every table syncs as a full refresh. Per the
+# incremental sync guidance, a client-side "stop when we've seen this id before" cursor would still
+# walk every page on every run, so it isn't real incremental sync and isn't worth pretending here.
+INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/bluesky/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/bluesky/source.py
index b7e82a08dbc5..0c6c7e775eac 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/bluesky/source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/bluesky/source.py
@@ -1,32 +1,157 @@
-from typing import cast
+from typing import Optional, cast
from posthog.schema import (
DataWarehouseSourceCategory,
ExternalDataSourceType as SchemaExternalDataSourceType,
+ ReleaseStatus,
SourceConfig,
+ SourceFieldInputConfig,
+ SourceFieldInputConfigType,
)
-from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, SimpleSource
+from products.warehouse_sources.backend.temporal.data_imports.sources.bluesky.bluesky import (
+ BlueskyResumeConfig,
+ bluesky_source,
+ validate_credentials as validate_bluesky_credentials,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.bluesky.settings import (
+ ENDPOINTS,
+ INCREMENTAL_FIELDS,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, ResumableSource
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (
+ CanonicalDescriptions,
+)
from products.warehouse_sources.backend.temporal.data_imports.sources.common.registry import SourceRegistry
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.schema import (
+ SourceSchema,
+ build_endpoint_schemas,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceInputs, SourceResponse
from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.bluesky import (
BlueskySourceConfig,
)
from products.warehouse_sources.backend.types import ExternalDataSourceType
+# 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.
+PRIMARY_KEYS: dict[str, list[str]] = {
+ "Profile": ["did"],
+ "Posts": ["uri"],
+ "Followers": ["did"],
+ "Follows": ["did"],
+}
+
+# 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"],
+}
+
@SourceRegistry.register
-class BlueskySource(SimpleSource[BlueskySourceConfig]):
+class BlueskySource(ResumableSource[BlueskySourceConfig, BlueskyResumeConfig]):
+ 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.",
+ }
+
+ def get_canonical_descriptions(self) -> CanonicalDescriptions:
+ from products.warehouse_sources.backend.temporal.data_imports.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:
+ resource = bluesky_source(
+ actor=config.actor,
+ endpoint=inputs.schema_name,
+ team_id=inputs.team_id,
+ job_id=inputs.job_id,
+ resumable_source_manager=resumable_source_manager,
+ )
+ partition_keys = PARTITION_FIELDS.get(inputs.schema_name)
+ 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=SchemaExternalDataSourceType.BLUESKY,
category=DataWarehouseSourceCategory.MARKETING___EMAIL,
- label="Bluesky (AT Protocol)",
+ label="Bluesky",
+ caption=(
+ "Sync a Bluesky account's profile, posts, followers, and follows. 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",
- fields=cast(list[FieldType], []),
- unreleasedSource=True,
+ keywords=["social", "atproto", "at protocol"],
+ releaseStatus=ReleaseStatus.ALPHA,
+ 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.",
+ ),
+ ],
+ ),
)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/bluesky/tests/test_bluesky.py b/products/warehouse_sources/backend/temporal/data_imports/sources/bluesky/tests/test_bluesky.py
new file mode 100644
index 000000000000..4bcfdbb70bf8
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/bluesky/tests/test_bluesky.py
@@ -0,0 +1,257 @@
+import json
+from collections.abc import Iterable
+from typing import Any, cast
+
+import pytest
+from unittest.mock import MagicMock, patch
+
+from requests import Response
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.bluesky.bluesky import (
+ BlueskyResumeConfig,
+ bluesky_source,
+ get_resource,
+ validate_credentials,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+
+
+class TestGetResource:
+ @pytest.mark.parametrize(
+ ("name", "expected_path", "expected_selector"),
+ [
+ ("Profile", "/xrpc/app.bsky.actor.getProfile", "$"),
+ ("Posts", "/xrpc/app.bsky.feed.getAuthorFeed", "feed[*].post"),
+ ("Followers", "/xrpc/app.bsky.graph.getFollowers", "followers"),
+ ("Follows", "/xrpc/app.bsky.graph.getFollows", "follows"),
+ ],
+ )
+ def test_endpoint_shape(self, name: str, expected_path: str, expected_selector: str) -> None:
+ resource = get_resource(name, actor="jay.bsky.team")
+ endpoint = resource["endpoint"]
+ assert isinstance(endpoint, dict)
+
+ assert endpoint["path"] == expected_path
+ assert endpoint["data_selector"] == expected_selector
+
+ params = endpoint["params"]
+ assert isinstance(params, dict)
+ assert params["actor"] == "jay.bsky.team"
+
+ def test_unknown_endpoint_raises(self) -> None:
+ with pytest.raises(KeyError):
+ get_resource("Nope", actor="jay.bsky.team")
+
+ def test_posts_excludes_replies(self) -> None:
+ # Matches what most marketing/brand tracking cares about: the author's own content.
+ resource = get_resource("Posts", actor="jay.bsky.team")
+ endpoint = resource["endpoint"]
+ assert isinstance(endpoint, dict)
+ params = endpoint["params"]
+ assert isinstance(params, dict)
+ assert params["filter"] == "posts_no_replies"
+
+
+def _make_http_response(body: dict[str, Any], status_code: int = 200) -> Response:
+ resp = Response()
+ resp.status_code = status_code
+ resp._content = json.dumps(body).encode()
+ resp.headers["Content-Type"] = "application/json"
+ return resp
+
+
+class TestValidateCredentials:
+ _MAKE_SESSION = (
+ "products.warehouse_sources.backend.temporal.data_imports.sources.bluesky.bluesky.make_tracked_session"
+ )
+
+ @patch(_MAKE_SESSION)
+ def test_valid_actor(self, mock_make_session: MagicMock) -> None:
+ mock_session = mock_make_session.return_value
+ mock_session.get.return_value = _make_http_response({"did": "did:plc:abc"}, 200)
+
+ is_valid, message = validate_credentials("jay.bsky.team")
+
+ assert (is_valid, message) == (True, None)
+ mock_session.get.assert_called_once_with(
+ "https://public.api.bsky.app/xrpc/app.bsky.actor.getProfile",
+ params={"actor": "jay.bsky.team"},
+ )
+
+ @patch(_MAKE_SESSION)
+ def test_missing_actor_surfaces_api_message(self, mock_make_session: MagicMock) -> None:
+ mock_session = mock_make_session.return_value
+ mock_session.get.return_value = _make_http_response(
+ {"error": "InvalidRequest", "message": "Profile not found"}, 400
+ )
+
+ is_valid, message = validate_credentials("missing.bsky.social")
+
+ assert is_valid is False
+ assert message == "Profile not found"
+
+ @patch(_MAKE_SESSION)
+ def test_missing_actor_without_api_message_falls_back(self, mock_make_session: MagicMock) -> None:
+ mock_session = mock_make_session.return_value
+ mock_session.get.return_value = _make_http_response({}, 400)
+
+ is_valid, message = validate_credentials("missing.bsky.social")
+
+ assert is_valid is False
+ assert message == "That handle or DID couldn't be found on Bluesky. Check the spelling and try again."
+
+ @patch(_MAKE_SESSION)
+ def test_non_json_error_body_falls_back(self, mock_make_session: MagicMock) -> None:
+ mock_session = mock_make_session.return_value
+ resp = Response()
+ resp.status_code = 400
+ resp._content = b"<html>not json</html>"
+ mock_session.get.return_value = resp
+
+ is_valid, message = validate_credentials("missing.bsky.social")
+
+ assert is_valid is False
+ assert message == "That handle or DID couldn't be found on Bluesky. Check the spelling and try again."
+
+ @patch(_MAKE_SESSION)
+ def test_unexpected_status_falls_back_to_generic_message(self, mock_make_session: MagicMock) -> None:
+ mock_session = mock_make_session.return_value
+ mock_session.get.return_value = _make_http_response({}, 503)
+
+ is_valid, message = validate_credentials("jay.bsky.team")
+
+ assert is_valid is False
+ assert message == "Bluesky returned an unexpected error (503)."
+
+
+class TestBlueskySourceResumeBehavior:
+ """End-to-end resume behaviour of ``bluesky_source`` via ``rest_api_resource``."""
+
+ _MAKE_SESSION = (
+ "products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.rest_client"
+ ".make_tracked_session"
+ )
+
+ def _drive(
+ self, endpoint: str, manager: MagicMock, responses: list[Response]
+ ) -> tuple[MagicMock, list[dict[str, Any]]]:
+ """Drive ``bluesky_source`` with a mocked HTTP session.
+
+ Returns ``(mock_session, sent_params)`` where ``sent_params`` is a list of shallow copies
+ of ``request.params`` captured at send-time, since the underlying ``Request`` is mutated
+ in-place by the paginator between pages.
+ """
+ sent_params: list[dict[str, Any]] = []
+ response_iter = iter(responses)
+
+ def fake_send(request: Any, *_args: Any, **_kwargs: Any) -> Response:
+ sent_params.append(dict(request.params or {}))
+ return next(response_iter)
+
+ with patch(self._MAKE_SESSION) as mock_make_session:
+ mock_session = mock_make_session.return_value
+ mock_session.headers = {}
+ mock_session.prepare_request.side_effect = lambda req: req
+ mock_session.send.side_effect = fake_send
+
+ resource = bluesky_source(
+ actor="jay.bsky.team",
+ endpoint=endpoint,
+ team_id=123,
+ job_id="test_job",
+ resumable_source_manager=manager,
+ )
+ list(cast(Iterable[Any], resource))
+ return mock_session, sent_params
+
+ @pytest.mark.parametrize(
+ ("endpoint", "list_key", "item"),
+ [
+ ("Posts", "feed", {"post": {"uri": "at://x"}}),
+ ("Followers", "followers", {"did": "did:plc:1"}),
+ ("Follows", "follows", {"did": "did:plc:1"}),
+ ],
+ )
+ def test_fresh_run_saves_cursor_after_each_non_terminal_page(
+ self, endpoint: str, list_key: str, item: dict[str, Any]
+ ) -> None:
+ manager = MagicMock(spec=ResumableSourceManager)
+ manager.can_resume.return_value = False
+
+ responses = [
+ _make_http_response({list_key: [item], "cursor": "cursor-1"}),
+ _make_http_response({list_key: [item], "cursor": "cursor-2"}),
+ _make_http_response({list_key: [item]}),
+ ]
+ _, sent_params = self._drive(endpoint, manager, responses)
+
+ cursors_sent = [p.get("cursor") for p in sent_params]
+ assert cursors_sent == [None, "cursor-1", "cursor-2"]
+
+ saved = [call.args[0] for call in manager.save_state.call_args_list]
+ assert saved == [
+ BlueskyResumeConfig(cursor="cursor-1"),
+ BlueskyResumeConfig(cursor="cursor-2"),
+ ]
+
+ def test_resume_seeds_paginator_with_saved_cursor(self) -> None:
+ manager = MagicMock(spec=ResumableSourceManager)
+ manager.can_resume.return_value = True
+ manager.load_state.return_value = BlueskyResumeConfig(cursor="cursor-resumed")
+
+ responses = [_make_http_response({"followers": [{"did": "did:plc:1"}]})]
+ _, sent_params = self._drive("Followers", manager, responses)
+
+ assert [p.get("cursor") for p in sent_params] == ["cursor-resumed"]
+ manager.load_state.assert_called_once()
+
+ def test_terminal_single_page_does_not_save_state(self) -> None:
+ manager = MagicMock(spec=ResumableSourceManager)
+ manager.can_resume.return_value = False
+
+ responses = [_make_http_response({"followers": [{"did": "did:plc:1"}]})]
+ self._drive("Followers", manager, responses)
+
+ manager.save_state.assert_not_called()
+
+ def test_does_not_load_state_when_cannot_resume(self) -> None:
+ manager = MagicMock(spec=ResumableSourceManager)
+ manager.can_resume.return_value = False
+
+ responses = [_make_http_response({"followers": [{"did": "did:plc:1"}]})]
+ self._drive("Followers", manager, responses)
+
+ manager.load_state.assert_not_called()
+
+ def test_profile_endpoint_is_a_single_page_and_never_saves_state(self) -> None:
+ manager = MagicMock(spec=ResumableSourceManager)
+ manager.can_resume.return_value = False
+
+ responses = [_make_http_response({"did": "did:plc:1", "handle": "jay.bsky.team"})]
+ _, sent_params = self._drive("Profile", manager, responses)
+
+ assert len(sent_params) == 1
+ manager.save_state.assert_not_called()
+
+ def test_posts_yields_flattened_post_objects(self) -> None:
+ manager = MagicMock(spec=ResumableSourceManager)
+ manager.can_resume.return_value = False
+
+ responses = [_make_http_response({"feed": [{"post": {"uri": "at://x", "indexedAt": "2026-01-01T00:00:00Z"}}]})]
+ with patch(self._MAKE_SESSION) as mock_make_session:
+ mock_session = mock_make_session.return_value
+ mock_session.headers = {}
+ response_iter = iter(responses)
+ mock_session.prepare_request.side_effect = lambda req: req
+ mock_session.send.side_effect = lambda *args, **kwargs: next(response_iter)
+
+ resource = bluesky_source(
+ actor="jay.bsky.team",
+ endpoint="Posts",
+ team_id=123,
+ job_id="test_job",
+ resumable_source_manager=manager,
+ )
+ pages = list(cast(Iterable[Any], resource))
+
+ assert pages == [[{"uri": "at://x", "indexedAt": "2026-01-01T00:00:00Z"}]]
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/bluesky/tests/test_bluesky_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/bluesky/tests/test_bluesky_source.py
new file mode 100644
index 000000000000..6a10ba49883f
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/bluesky/tests/test_bluesky_source.py
@@ -0,0 +1,173 @@
+import pytest
+from unittest import mock
+
+from posthog.schema import ReleaseStatus, SourceFieldInputConfig, SourceFieldInputConfigType
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.bluesky.bluesky import BlueskyResumeConfig
+from products.warehouse_sources.backend.temporal.data_imports.sources.bluesky.settings import ENDPOINTS
+from products.warehouse_sources.backend.temporal.data_imports.sources.bluesky.source import (
+ PARTITION_FIELDS,
+ PRIMARY_KEYS,
+ BlueskySource,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.bluesky import (
+ BlueskySourceConfig,
+)
+from products.warehouse_sources.backend.types import ExternalDataSourceType
+
+
+class TestBlueskySource:
+ def setup_method(self):
+ self.source = BlueskySource()
+ self.team_id = 123
+ self.config = BlueskySourceConfig(actor="jay.bsky.team")
+
+ def test_source_type(self):
+ assert self.source.source_type == ExternalDataSourceType.BLUESKY
+
+ def test_get_source_config(self):
+ config = self.source.get_source_config
+
+ assert config.name.value == "Bluesky"
+ assert config.label == "Bluesky"
+ assert config.releaseStatus == ReleaseStatus.ALPHA
+ assert config.unreleasedSource is None
+ assert config.iconPath == "/static/services/bluesky.png"
+ assert config.docsUrl == "https://posthog.com/docs/cdp/sources/bluesky"
+
+ field_names = [f.name for f in config.fields if isinstance(f, SourceFieldInputConfig)]
+ assert field_names == ["actor"]
+
+ def test_actor_field_is_required_and_not_secret(self):
+ config = self.source.get_source_config
+ actor_field = next(f for f in config.fields if isinstance(f, SourceFieldInputConfig) and f.name == "actor")
+ assert actor_field.type == SourceFieldInputConfigType.TEXT
+ assert actor_field.required is True
+ assert actor_field.secret is False
+
+ def test_lists_tables_without_credentials_publishes_catalog(self):
+ # Static endpoint catalog (no I/O) — the public docs table list should render.
+ assert self.source.lists_tables_without_credentials is True
+ documented = self.source.get_documented_tables()
+ assert {table["name"] for table in documented} == set(ENDPOINTS)
+
+ def test_canonical_descriptions_cover_every_endpoint(self):
+ canonical = self.source.get_canonical_descriptions()
+ assert set(canonical) == set(ENDPOINTS)
+
+ def test_get_schemas_are_full_refresh_only(self):
+ # None of Bluesky's list endpoints expose a server-side timestamp filter.
+ schemas = {schema.name: schema for schema in self.source.get_schemas(self.config, self.team_id)}
+
+ assert set(schemas) == set(ENDPOINTS)
+ for schema in schemas.values():
+ assert schema.supports_incremental is False
+ assert schema.supports_append is False
+ assert schema.incremental_fields == []
+
+ def test_get_schemas_filtered_by_names(self):
+ schemas = self.source.get_schemas(self.config, self.team_id, names=["Posts"])
+ assert len(schemas) == 1
+ assert schemas[0].name == "Posts"
+
+ def test_get_schemas_filtered_unknown_name_returns_empty(self):
+ assert self.source.get_schemas(self.config, self.team_id, names=["nope"]) == []
+
+ @pytest.mark.parametrize(
+ "observed_error",
+ [
+ "400 Client Error: Bad Request for url: https://public.api.bsky.app/xrpc/app.bsky.actor.getProfile?actor=missing.bsky.social",
+ ],
+ )
+ def test_non_retryable_errors_match_missing_actor(self, observed_error):
+ non_retryable_errors = self.source.get_non_retryable_errors()
+ assert any(key in observed_error for key in non_retryable_errors)
+
+ @pytest.mark.parametrize(
+ "other_error",
+ [
+ "429 Client Error: Too Many Requests for url: https://public.api.bsky.app/xrpc/app.bsky.feed.getAuthorFeed",
+ "500 Server Error: Internal Server Error for url: https://public.api.bsky.app/xrpc/app.bsky.actor.getProfile",
+ "HTTPSConnectionPool(host='public.api.bsky.app', port=443): Read timed out.",
+ ],
+ )
+ def test_non_retryable_errors_do_not_match_transient(self, other_error):
+ non_retryable_errors = self.source.get_non_retryable_errors()
+ assert not any(key in other_error for key in non_retryable_errors)
+
+ @mock.patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.bluesky.source.validate_bluesky_credentials"
+ )
+ def test_validate_credentials_delegates_to_transport(self, mock_validate):
+ mock_validate.return_value = (True, None)
+
+ is_valid, error_message = self.source.validate_credentials(self.config, self.team_id)
+
+ assert (is_valid, error_message) == (True, None)
+ mock_validate.assert_called_once_with("jay.bsky.team")
+
+ @mock.patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.bluesky.source.validate_bluesky_credentials"
+ )
+ def test_validate_credentials_surfaces_failure(self, mock_validate):
+ mock_validate.return_value = (False, "That doesn't look like a valid Bluesky handle or DID.")
+
+ is_valid, error_message = self.source.validate_credentials(self.config, self.team_id)
+
+ assert is_valid is False
+ assert error_message == "That doesn't look like a valid Bluesky handle or DID."
+
+ def test_get_resumable_source_manager_bound_to_resume_config(self):
+ inputs = mock.MagicMock()
+ manager = self.source.get_resumable_source_manager(inputs)
+ assert manager._data_class is BlueskyResumeConfig
+
+ @mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.bluesky.source.bluesky_source")
+ def test_source_for_pipeline_plumbs_arguments(self, mock_bluesky_source):
+ inputs = mock.MagicMock()
+ inputs.schema_name = "Posts"
+ inputs.team_id = self.team_id
+ inputs.job_id = "job-1"
+ manager = mock.MagicMock()
+
+ self.source.source_for_pipeline(self.config, manager, inputs)
+
+ mock_bluesky_source.assert_called_once_with(
+ actor="jay.bsky.team",
+ endpoint="Posts",
+ team_id=self.team_id,
+ job_id="job-1",
+ resumable_source_manager=manager,
+ )
+
+ @pytest.mark.parametrize(
+ ("schema_name", "expected_partition_keys"),
+ [
+ ("Profile", None),
+ ("Posts", ["indexedAt"]),
+ ("Followers", ["createdAt"]),
+ ("Follows", ["createdAt"]),
+ ],
+ )
+ @mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.bluesky.source.bluesky_source")
+ def test_source_for_pipeline_sets_partitioning_per_endpoint(
+ self, mock_bluesky_source, schema_name, expected_partition_keys
+ ):
+ mock_bluesky_source.return_value.name = schema_name
+ mock_bluesky_source.return_value.column_hints = None
+ inputs = mock.MagicMock()
+ inputs.schema_name = schema_name
+
+ response = self.source.source_for_pipeline(self.config, mock.MagicMock(), inputs)
+
+ assert response.primary_keys == PRIMARY_KEYS[schema_name]
+ assert response.partition_keys == expected_partition_keys
+ assert response.partition_mode == ("datetime" if expected_partition_keys else None)
+
+ def test_every_endpoint_has_primary_keys_declared(self):
+ assert set(PRIMARY_KEYS) == set(ENDPOINTS)
+
+ def test_partition_fields_only_cover_multi_row_endpoints(self):
+ # Profile is a single row per sync; partitioning it isn't meaningful.
+ assert "Profile" not in PARTITION_FIELDS
+ assert set(PARTITION_FIELDS) == set(ENDPOINTS) - {"Profile"}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/bluesky.py b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/bluesky.py
index 2cafe837f79b..49d90bdb2a3a 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/bluesky.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/bluesky.py
@@ -6,4 +6,4 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common imp
@config.config
class BlueskySourceConfig(config.Config):
- pass
+ actor: str