Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
Show all changes
27 commits
Select commit Hold shift + click to select a range
469219b
Add example_atproto_plugins: live JetStream sample
haileyok Apr 30, 2026
2c7edba
Address PR review: align with atproto-ruleset structure
haileyok Apr 30, 2026
1f6a8de
Fix mypy: split per-connection streaming into helper
haileyok Apr 30, 2026
b28092f
Use JetStream-native paths in sample rules and Action shape
haileyok Apr 30, 2026
c2c0746
Address review feedback on JetStream sample
haileyok May 6, 2026
7cccb4b
Fix _stream_one_connection test: catch close exception, use _item attr
haileyok May 6, 2026
232c449
Tighten _event_to_action time_us check to int only
haileyok May 6, 2026
0c8f462
Re-lock uv.lock at revision 3 to match main and fix Docker build
haileyok May 6, 2026
260e462
Merge remote-tracking branch 'origin/main' into hailey/atproto-jetstr…
haileyok May 7, 2026
6bf2841
Per-collection+operation action_names; UI default features per event
haileyok May 7, 2026
74ae20d
Mint action_ids in plugin to fix UI duplication
haileyok May 7, 2026
b650d94
Unify FollowSubject + LikeSubjectUri into one Subject feature
haileyok May 7, 2026
58d1bcf
wording tweaks
haileyok May 7, 2026
853aa74
fix
haileyok May 7, 2026
2cdb462
add a changelog
haileyok May 8, 2026
a591e1c
Switch to WebSocketApp.run_forever for keepalive
haileyok May 8, 2026
bd44b1d
Exponential reconnect backoff in JetStream input stream
haileyok May 8, 2026
ff18575
Drop Sentry usage and split JSON-decode error handling
haileyok May 8, 2026
fbee1a8
Use osprey.worker.lib.backoff.Backoff instead of hand-rolled state
haileyok May 8, 2026
f5b23ff
Merge branch 'main' into hailey/atproto-jetstream-sample
cassidyjames May 15, 2026
c959238
Merge branch 'main' into hailey/atproto-jetstream-sample
julietshen Jul 13, 2026
36b0e7c
test: run example_atproto_plugins tests in CI
julietshen Jul 13, 2026
7ceba0c
Merge branch 'main' into hailey/atproto-jetstream-sample
julietshen Jul 13, 2026
b6ef2c4
docs(atproto): note the sample relies on example_plugins
julietshen Jul 13, 2026
22103e9
ci: ignore first-party example_atproto_plugins in the Python license …
julietshen Jul 13, 2026
4356412
fix(atproto): add py.typed and reformat for main's ruff/mypy
julietshen Jul 13, 2026
bef1703
fix(atproto): address CodeRabbit review on JetStream input stream
julietshen Jul 13, 2026
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 3 additions & 1 deletion AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -12,14 +12,16 @@ Top-level modules:
- `osprey_coordinator/` — Rust gRPC coordinator (tokio, tonic, etcd, rdkafka). Rust code belongs here.
- `proto/osprey/rpc/` — protobuf source of truth for `osprey_rpc` and `osprey_coordinator` types.
- `example_plugins/` — reference plugins (UDFs, output sinks, labels service) using the pluggy-based plugin system. Do not add production code here.
- `example_atproto_plugins/` — reference plugin demonstrating a custom input stream that consumes Bluesky's ATProto JetStream firehose. Stack `docker-compose.atproto.yaml` on top of the main compose file (or use `./run-atproto.sh`) to run Osprey against live ATProto traffic. Do not add production code here.
Comment thread
haileyok marked this conversation as resolved.
Resolved
- `example_rules/` — sample SML rules and YAML config.
- `example_atproto_rules/` — sample SML rules paired with `example_atproto_plugins/`.

Reference files: `docs/DEVELOPMENT.md` (setup), `example_plugins/src/register_plugins.py` (plugin patterns), `example_plugins/src/services/labels_service.py` (labels service example).

## Design

- API: gRPC between `osprey_coordinator` and workers; HTTP/Flask for `osprey-ui-api` (port 5004); protobuf definitions under `proto/osprey/rpc/` are authoritative.
- Rules: SML (Osprey's rule language) with user-defined functions registered via pluggy hooks (`@hookimpl_osprey`): `register_udfs`, `register_output_sinks`, `register_labels_service_or_provider`.
- Rules: SML (Osprey's rule language) with user-defined functions registered via pluggy hooks (`@hookimpl_osprey`): `register_udfs`, `register_output_sinks`, `register_labels_service_or_provider`, `register_input_stream` (custom event source; see `example_atproto_plugins/`).
- Data model conventions: Pydantic for models, SQLAlchemy for persistence (versions pinned in `pyproject.toml`).

## Build and run
Expand Down
29 changes: 29 additions & 0 deletions docker-compose.atproto.yaml
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.
Comment thread
haileyok marked this conversation as resolved.
Resolved
minio:
ports: !reset []
51 changes: 51 additions & 0 deletions example_atproto_plugins/README.md
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.
Empty file.
18 changes: 18 additions & 0 deletions example_atproto_plugins/pyproject.toml
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

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The 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 websocket-client==1.8.0 before merge. It’s a new dependency and needs license/CVE review; pluggy==1.5.0 is already covered by the shared deps.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@example_atproto_plugins/pyproject.toml` around lines 6 - 9, Update the
dependencies list to flag websocket-client==1.8.0 for required approval before
merge, ensuring the new dependency undergoes license and CVE review while
leaving the already-covered pluggy==1.5.0 entry unchanged.

Source: Path instructions


[tool.setuptools]
package-dir = {"" = "src"}

[tool.setuptools.packages.find]
where = ["src"]

[project.entry-points.osprey_plugin]
atproto_plugins = "atproto_plugin.register_plugins"
Empty file.
122 changes: 122 additions & 0 deletions example_atproto_plugins/src/atproto_plugin/jetstream_input_stream.py
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',
)
Comment thread
haileyok marked this conversation as resolved.
Resolved


class JetStreamInputStream(BaseInputStream[BaseAckingContext[Action]]):

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The 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...

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The 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

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The 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

backoff = self._reconnect_seconds

while True:
.....
    backoff = min(backoff * 2, 60.0)

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:
Comment thread
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 ''

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The 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
Comment thread
haileyok marked this conversation as resolved.
Resolved
Comment thread
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),
Comment thread
haileyok marked this conversation as resolved.
Resolved
action_name=action_name,
data=data,
timestamp=datetime.fromtimestamp(time_us / 1_000_000, tz=timezone.utc),
)
14 changes: 14 additions & 0 deletions example_atproto_plugins/src/atproto_plugin/register_plugins.py
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)
5 changes: 5 additions & 0 deletions example_atproto_rules/config/labels.yaml
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'
3 changes: 3 additions & 0 deletions example_atproto_rules/main.sml
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')
25 changes: 25 additions & 0 deletions example_atproto_rules/models/base.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()
20 changes: 20 additions & 0 deletions example_atproto_rules/rules/post_contains_test.sml
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'),
],
)
7 changes: 5 additions & 2 deletions osprey_worker/Dockerfile
Original file line number Diff line number Diff line change
Expand Up @@ -35,10 +35,11 @@ ADD LICENSE.md /osprey/LICENSE.md
ADD osprey_rpc/pyproject.toml /osprey/osprey_rpc/pyproject.toml
ADD osprey_worker/pyproject.toml /osprey/osprey_worker/pyproject.toml
ADD example_plugins/pyproject.toml /osprey/example_plugins/pyproject.toml
ADD example_atproto_plugins/pyproject.toml /osprey/example_atproto_plugins/pyproject.toml

# Create minimal package structure required by uv
RUN mkdir -p /osprey/osprey_worker /osprey/osprey_rpc /osprey/example_plugins/src && \
touch /osprey/osprey_worker/__init__.py /osprey/osprey_rpc/__init__.py /osprey/example_plugins/src/__init__.py
RUN mkdir -p /osprey/osprey_worker /osprey/osprey_rpc /osprey/example_plugins/src /osprey/example_atproto_plugins/src/atproto_plugin && \
touch /osprey/osprey_worker/__init__.py /osprey/osprey_rpc/__init__.py /osprey/example_plugins/src/__init__.py /osprey/example_atproto_plugins/src/atproto_plugin/__init__.py

# Install dependencies first (this layer will be cached when only source code changes)
RUN pip install --upgrade pip uv && \
Expand All @@ -50,9 +51,11 @@ RUN . .venv/bin/activate && update-tld-names

# Add source code after dependencies are installed
ADD example_rules /osprey/example_rules
ADD example_atproto_rules /osprey/example_atproto_rules
ADD osprey_worker /osprey/osprey_worker
ADD osprey_rpc /osprey/osprey_rpc
ADD example_plugins /osprey/example_plugins
ADD example_atproto_plugins /osprey/example_atproto_plugins

COPY entrypoint.sh /osprey/entrypoint.sh

Expand Down
7 changes: 5 additions & 2 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -133,12 +133,14 @@ nostril = { url = "https://github.com/casics/nostril/archive/v1.2.0.tar.gz" }
osprey_rpc = { workspace = true }
osprey_worker = { workspace = true }
example_plugins = { workspace = true }
example_atproto_plugins = { workspace = true }

[tool.uv.workspace]
members = [
"osprey_rpc",
"osprey_worker",
"example_plugins",
"example_atproto_plugins",
]


Expand Down Expand Up @@ -171,10 +173,10 @@ ignore = [
]

[tool.ruff.lint.isort]
known-first-party = ["osprey_worker", "osprey_rpc", "example_plugins"]
known-first-party = ["osprey_worker", "osprey_rpc", "example_plugins", "example_atproto_plugins"]

[tool.fawltydeps]
code = ["osprey_worker/src", "osprey_rpc/src", "example_plugins/src"]
code = ["osprey_worker/src", "osprey_rpc/src", "example_plugins/src", "example_atproto_plugins/src"]
deps = ["pyproject.toml"]
ignore_unused = [
# Type stubs: used by mypy, never imported directly
Expand Down Expand Up @@ -239,6 +241,7 @@ mypy_path = [
"osprey_rpc/src",
"osprey_worker/src",
"example_plugins/src",
"example_atproto_plugins/src",
]

# Strict mode includes the following flags. When these are all True, they can be replaced with strict mode.
Expand Down
5 changes: 5 additions & 0 deletions run-atproto.sh
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}"
Loading
Loading