Repository navigation
[examples] Bluesky/ATProto sample integration (input stream, rules) #236
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Changes from 1 commit
469219b
2c7edba
1f6a8de
b28092f
c2c0746
7cccb4b
232c449
0c8f462
260e462
6bf2841
74ae20d
b650d94
58d1bcf
853aa74
2cdb462
a591e1c
bd44b1d
ff18575
fbee1a8
f5b23ff
c959238
36b0e7c
7ceba0c
b6ef2c4
22103e9
4356412
bef1703
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,29 @@ | ||
| # Override that swaps the synthetic Kafka producer for the live Bluesky JetStream | ||
| # firehose, via the example_atproto_plugins package. Stack on top of the main | ||
| # compose file: | ||
| # | ||
| # docker compose -f docker-compose.yaml -f docker-compose.atproto.yaml up | ||
| # | ||
| # Or use the convenience wrapper: ./run-atproto.sh | ||
| services: | ||
| osprey-worker: | ||
| environment: | ||
| OSPREY_INPUT_STREAM_SOURCE: plugin | ||
| OSPREY_RULES_PATH: ./example_atproto_rules | ||
| ports: !reset [] | ||
| volumes: | ||
| - ./example_atproto_rules:/osprey/example_atproto_rules | ||
| - ./example_atproto_plugins:/osprey/example_atproto_plugins | ||
|
|
||
| osprey-ui-api: | ||
| environment: | ||
| OSPREY_RULES_PATH: /osprey/example_atproto_rules | ||
| volumes: | ||
| - ./example_atproto_rules:/osprey/example_atproto_rules | ||
|
|
||
| # Avoid host-port conflicts with supervisord-managed services in | ||
| # the Discord monorepo dev environment (which often holds :9000 and :8082). | ||
| # Worker -> minio uses the internal docker network, so dropping the | ||
| # host bindings doesn't affect the sample. | ||
|
haileyok marked this conversation as resolved.
Resolved
|
||
| minio: | ||
| ports: !reset [] | ||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,51 @@ | ||
| # example_atproto_plugins | ||
|
|
||
| A sample Osprey plugin that consumes Bluesky's [JetStream](https://docs.bsky.app/blog/jetstream) — the public ATProto firehose — as the input event source. | ||
|
|
||
| This is the missing companion to `example_plugins/`: it shows how a real-world adopter wires Osprey up to their own platform's events. Out of the box it gives you: | ||
|
|
||
| - a `register_input_stream` hook implementation that subscribes to JetStream over WebSocket and yields Osprey `Action`s for ATProto commits (posts, likes, reposts, follows by default), | ||
| - realistic per-second event volume from the live Bluesky network — useful for load and soak testing changes that the synthetic 1-event/second producer doesn't exercise, | ||
| - a companion `example_atproto_rules/` tree showing how to write rules against ATProto event shapes. | ||
|
|
||
| ## Running | ||
|
|
||
| From the repo root: | ||
|
|
||
| ```sh | ||
| ./run-atproto.sh | ||
| ``` | ||
|
|
||
| Under the hood this stacks `docker-compose.atproto.yaml` on top of the main compose file, swapping the worker's input source from Kafka to the JetStream plugin and pointing it at `example_atproto_rules` instead of `example_rules`. | ||
|
|
||
| ## Configuration | ||
|
|
||
| | Env var | Default | Description | | ||
| | --- | --- | --- | | ||
| | `OSPREY_INPUT_STREAM_SOURCE` | (must be) `plugin` | Selects the plugin-provided stream. | | ||
| | `OSPREY_JETSTREAM_ENDPOINT` | `wss://jetstream2.us-west.bsky.network/subscribe` | JetStream WebSocket URL. | | ||
| | `OSPREY_JETSTREAM_WANTED_COLLECTIONS` | `app.bsky.feed.post,app.bsky.feed.like,app.bsky.feed.repost,app.bsky.graph.follow` | Comma-separated collections to subscribe to (server-side filter). | | ||
|
|
||
| ## Action shape | ||
|
|
||
| Each commit is mapped to an `Action` with: | ||
|
|
||
| ``` | ||
| data = { | ||
| 'did': '<actor DID>', | ||
| 'collection': 'app.bsky.feed.post', | ||
| 'operation': 'create' | 'update' | 'delete', | ||
| 'rkey': '<record key>', | ||
| 'rev': '<commit rev>', | ||
| 'cid': '<record CID>', | ||
| 'event_type': 'create_post', # <operation>_<short_collection> | ||
| 'record': { ... raw ATProto record ... }, | ||
| } | ||
| ``` | ||
|
|
||
| Identity and account events are skipped — this sample is concerned with content events. | ||
|
|
||
| ## Caveats | ||
|
|
||
| - **Not production-ready.** No durable cursor / resume on restart, no zstd compression, no DID-level filtering. Good for sample / load-testing purposes; not a drop-in for a Bluesky deployment. | ||
| - **Schema drift.** Bluesky has not committed to JetStream as a stable long-term API. Treat this as illustrative. |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,18 @@ | ||
| [project] | ||
| name = "example_atproto_plugins" | ||
| version = "0.1.0" | ||
| description = "Example Osprey plugin that consumes Bluesky's ATProto JetStream firehose" | ||
| requires-python = ">=3.11" | ||
| dependencies = [ | ||
| "pluggy==1.5.0", | ||
| "websocket-client==1.8.0", | ||
| ] | ||
|
Comment on lines
+6
to
+9
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 🔒 Security & Privacy | 🟡 Minor | ⚡ Quick win 🧩 Analysis chain🏁 Script executed: #!/bin/bash
# Verify websocket-client license and check for known CVEs
gh api graphql -f query='
{
securityVulnerabilities(first: 10, ecosystem: PIP, package: "websocket-client") {
nodes {
advisory { summary severity publishedAt }
vulnerableVersionRange
firstPatchedVersion { identifier }
}
}
}'Repository: roostorg/osprey Length of output: 202 🏁 Script executed: #!/bin/bash
set -euo pipefail
# Inspect the relevant pyproject files and find all websocket-client mentions.
git ls-files '**/pyproject.toml' | sort
printf '\n--- root pyproject excerpt ---\n'
sed -n '1,120p' pyproject.toml
printf '\n--- package pyproject excerpt ---\n'
sed -n '1,120p' example_atproto_plugins/pyproject.toml
printf '\n--- websocket-client references ---\n'
rg -n --hidden --glob '!*node_modules*' --glob '!*dist*' --glob '!*build*' 'websocket-client' .Repository: roostorg/osprey Length of output: 4819 Require approval for 🤖 Prompt for AI AgentsSource: Path instructions |
||
|
|
||
| [tool.setuptools] | ||
| package-dir = {"" = "src"} | ||
|
|
||
| [tool.setuptools.packages.find] | ||
| where = ["src"] | ||
|
|
||
| [project.entry-points.osprey_plugin] | ||
| atproto_plugins = "atproto_plugin.register_plugins" | ||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,122 @@ | ||
| import json | ||
| import time | ||
| from datetime import datetime, timezone | ||
| from typing import Any, Dict, Iterator, List, Optional | ||
| from urllib.parse import urlencode | ||
|
|
||
| import sentry_sdk | ||
| import websocket | ||
| from osprey.engine.executor.execution_context import Action | ||
| from osprey.worker.lib.instruments import metrics | ||
| from osprey.worker.lib.osprey_shared.logging import get_logger | ||
| from osprey.worker.sinks.sink.input_stream import BaseInputStream | ||
| from osprey.worker.sinks.utils.acking_contexts import BaseAckingContext, NoopAckingContext | ||
|
|
||
| logger = get_logger() | ||
|
|
||
|
|
||
| DEFAULT_ENDPOINT = 'wss://jetstream2.us-west.bsky.network/subscribe' | ||
| DEFAULT_COLLECTIONS = ( | ||
| 'app.bsky.feed.post', | ||
| 'app.bsky.feed.like', | ||
| 'app.bsky.feed.repost', | ||
| 'app.bsky.graph.follow', | ||
| ) | ||
|
haileyok marked this conversation as resolved.
Resolved
|
||
|
|
||
|
|
||
| class JetStreamInputStream(BaseInputStream[BaseAckingContext[Action]]): | ||
|
Member
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. this is the main thing i'd love to get eyes on if anyone has python websocket experience...it doesn't need to be production stable since its really a testing/example guy (not to mention jetstream shouldn't be used for real-world moderation tasks anyway) but it should be at least mostly stable...
Member
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. i did want to opt for a non-kafka option in here, because doing this helps break the misconception that osprey can only be used with kafka |
||
| """Subscribes to Bluesky's ATProto JetStream WebSocket and yields Osprey Actions. | ||
|
|
||
| JetStream is Bluesky's public real-time firehose for ATProto network activity emitted as | ||
| plain JSON (no CBOR/CAR), making it a convenient high-volume source for exercising Osprey | ||
| against real production traffic. See https://docs.bsky.app/blog/jetstream. | ||
|
|
||
| Each ATProto commit is mapped to an Osprey :class:`Action` whose data dictionary exposes | ||
| the actor DID, collection, operation, and the raw record. Identity and account events are | ||
| skipped — the sample is concerned with content events. | ||
| """ | ||
|
|
||
| def __init__( | ||
| self, | ||
| endpoint: Optional[str] = None, | ||
| wanted_collections: Optional[List[str]] = None, | ||
| reconnect_seconds: float = 2.0, | ||
| ): | ||
| super().__init__() | ||
| self._endpoint = endpoint or DEFAULT_ENDPOINT | ||
| self._wanted_collections = list(wanted_collections) if wanted_collections else list(DEFAULT_COLLECTIONS) | ||
| self._reconnect_seconds = reconnect_seconds | ||
|
|
||
| def _build_url(self) -> str: | ||
| params = [('wantedCollections', c) for c in self._wanted_collections] | ||
| return f'{self._endpoint}?{urlencode(params)}' | ||
|
|
||
| def _gen(self) -> Iterator[BaseAckingContext[Action]]: | ||
| url = self._build_url() | ||
| while True: | ||
|
Comment on lines
+69
to
+70
Member
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. We should provably want to add a backoff. If JetStream is down or rate-limiting, you reconnect every 2 seconds in a tight loop and trigger escalating errors, potential higher rate limits and sentry capture on every event. We can start with a simple |
||
| ws: Optional[websocket.WebSocket] = None | ||
| try: | ||
| logger.info(f'Connecting to JetStream at {url}') | ||
| ws = websocket.create_connection(url) | ||
| logger.info('JetStream connection established') | ||
| while True: | ||
| raw = ws.recv() | ||
| if not raw: | ||
| continue | ||
| try: | ||
| event = json.loads(raw) | ||
| except json.JSONDecodeError: | ||
| logger.warning(f'Failed to parse JetStream event: {raw[:200]!r}') | ||
| continue | ||
|
|
||
| action = _event_to_action(event) | ||
| if action is None: | ||
| continue | ||
| metrics.increment('jetstream_input_stream.events', tags=[f'action_name:{action.action_name}']) | ||
| yield NoopAckingContext(action) | ||
| except Exception as e: | ||
| logger.exception(f'JetStream stream error; reconnecting in {self._reconnect_seconds}s: {e}') | ||
| sentry_sdk.capture_exception(e) | ||
| finally: | ||
| if ws is not None: | ||
| try: | ||
| ws.close() | ||
| except Exception: | ||
|
github-code-quality[bot] marked this conversation as resolved.
Fixed
|
||
| pass | ||
| time.sleep(self._reconnect_seconds) | ||
|
|
||
|
|
||
| def _event_to_action(event: Dict[str, Any]) -> Optional[Action]: | ||
| """Map a JetStream event dict into an Osprey :class:`Action`, or return ``None`` to skip it.""" | ||
| if event.get('kind') != 'commit': | ||
| return None | ||
| commit = event.get('commit') or {} | ||
| operation = commit.get('operation') | ||
| collection = commit.get('collection', '') or '' | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. I guess this wasn't intentional, as there's a default return value here so the or is redundant. |
||
| did = event.get('did', '') or '' | ||
| time_us = event.get('time_us') | ||
| if not time_us: | ||
| return None | ||
|
haileyok marked this conversation as resolved.
Resolved
coderabbitai[bot] marked this conversation as resolved.
Resolved
|
||
|
|
||
| short = collection.rsplit('.', 1)[-1] if collection else 'unknown' | ||
| action_name = f'{operation}_{short}' if operation else short | ||
|
|
||
| record = commit.get('record') or {} | ||
|
|
||
| data: Dict[str, Any] = { | ||
| 'did': did, | ||
| 'collection': collection, | ||
| 'operation': operation, | ||
| 'rkey': commit.get('rkey'), | ||
| 'rev': commit.get('rev'), | ||
| 'cid': commit.get('cid'), | ||
| 'event_type': action_name, | ||
| 'record': record, | ||
| } | ||
|
|
||
| return Action( | ||
| action_id=int(time_us), | ||
|
haileyok marked this conversation as resolved.
Resolved
|
||
| action_name=action_name, | ||
| data=data, | ||
| timestamp=datetime.fromtimestamp(time_us / 1_000_000, tz=timezone.utc), | ||
| ) | ||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,14 @@ | ||
| from atproto_plugin.jetstream_input_stream import JetStreamInputStream | ||
| from osprey.engine.executor.execution_context import Action | ||
| from osprey.worker.adaptor.plugin_manager import hookimpl_osprey | ||
| from osprey.worker.lib.config import Config | ||
| from osprey.worker.sinks.sink.input_stream import BaseInputStream | ||
| from osprey.worker.sinks.utils.acking_contexts import BaseAckingContext | ||
|
|
||
|
|
||
| @hookimpl_osprey | ||
| def register_input_stream(config: Config) -> BaseInputStream[BaseAckingContext[Action]]: | ||
| endpoint = config.get_optional_str('OSPREY_JETSTREAM_ENDPOINT') | ||
| raw_collections = config.get_optional_str('OSPREY_JETSTREAM_WANTED_COLLECTIONS') | ||
| wanted = [c.strip() for c in raw_collections.split(',') if c.strip()] if raw_collections else None | ||
| return JetStreamInputStream(endpoint=endpoint, wanted_collections=wanted) |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,5 @@ | ||
| labels: | ||
| test_poster: | ||
| valid_for: [Did] | ||
| connotation: neutral | ||
| description: ATProto user who posted a record containing the word 'test' |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,3 @@ | ||
| Import(rules=['models/base.sml']) | ||
|
|
||
| Require(rule='rules/post_contains_test.sml') |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,25 @@ | ||
| Did: Entity[str] = EntityJson( | ||
| type='Did', | ||
| path='$.did', | ||
| coerce_type=True | ||
| ) | ||
|
|
||
| Collection: Entity[str] = EntityJson( | ||
| type='Collection', | ||
| path='$.collection', | ||
| coerce_type=True | ||
| ) | ||
|
|
||
| EventType: Entity[str] = EntityJson( | ||
| type='EventType', | ||
| path='$.event_type', | ||
| coerce_type=True | ||
| ) | ||
|
|
||
| PostText: Entity[str] = EntityJson( | ||
| type='PostText', | ||
| path='$.record.text', | ||
| coerce_type=True | ||
| ) | ||
|
|
||
| ActionName=GetActionName() |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,20 @@ | ||
| Import( | ||
| rules=[ | ||
| 'models/base.sml', | ||
| ] | ||
| ) | ||
|
|
||
| PostContainsTest = Rule( | ||
| when_all=[ | ||
| EventType == 'create_post', | ||
| TextContains(text=PostText, phrase='test') | ||
| ], | ||
| description='ATProto post contains the word "test"', | ||
| ) | ||
|
|
||
| WhenRules( | ||
| rules_any=[PostContainsTest], | ||
| then=[ | ||
| LabelAdd(entity=Did, label='test_poster'), | ||
| ], | ||
| ) |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,5 @@ | ||
| #!/bin/bash | ||
| # Run Osprey against the live Bluesky JetStream firehose by stacking | ||
| # docker-compose.atproto.yaml on top of the main compose file. | ||
| set -e | ||
| exec docker compose -f docker-compose.yaml -f docker-compose.atproto.yaml "${@:-up}" |
Uh oh!
There was an error while loading. Please reload this page.