Skip to content

Commit 8d5b904

Browse files
committed
Adds long-running websocket stream consumer example
1 parent 606f91f commit 8d5b904

File tree

6 files changed

+405
-0
lines changed

6 files changed

+405
-0
lines changed
Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
# WebSocket Stream Consumer - Bluesky Firehose
2+
3+
This example demonstrates a long-running Durable Object that connects to the Bluesky firehose (via Jetstream) and filters for post events, with rate limiting to print at most 1 per second.
4+
5+
## How to Run
6+
7+
First ensure that `uv` is installed:
8+
https://docs.astral.sh/uv/getting-started/installation/#standalone-installer
9+
10+
Now, if you run `uv run pywrangler dev` within this directory, it should use the config
11+
in `wrangler.jsonc` to run the example.
12+
13+
You can also run `uv run pywrangler deploy` to deploy the example.
14+
15+
## Testing the Firehose Consumer
16+
17+
1. Start the worker: `uv run pywrangler dev`
18+
2. Make any request to initialize the DO: `curl "http://localhost:8787/status"`
19+
3. Watch the logs to see filtered Bluesky post events in real-time (rate limited to 1/sec)!
20+
21+
The Durable Object automatically connects to Jetstream when first accessed. It will maintain a persistent WebSocket connection and print out post events to the console, including the author DID, post text (truncated to 100 chars), and timestamp. Posts are rate limited to display at most 1 per second to avoid overwhelming the logs.
22+
23+
**Available endpoints:**
24+
- `/status` - Check connection status
25+
- `/reconnect` - Manually trigger reconnection if disconnected
Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
{
2+
"name": "python-websocket-stream-consumer",
3+
"version": "0.0.0",
4+
"private": true,
5+
"scripts": {
6+
"deploy": "uv run pywrangler deploy",
7+
"dev": "uv run pywrangler dev",
8+
"start": "uv run pywrangler dev"
9+
},
10+
"devDependencies": {
11+
"wrangler": "^4.46.0"
12+
}
13+
}
Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
[project]
2+
name = "python-websocket-stream-consumer"
3+
version = "0.1.0"
4+
description = "Python WebSocket stream consumer example"
5+
readme = "README.md"
6+
requires-python = ">=3.12"
7+
dependencies = [
8+
"webtypy>=0.1.7",
9+
]
10+
11+
[dependency-groups]
12+
dev = [
13+
"workers-py",
14+
"workers-runtime-sdk"
15+
]
Lines changed: 155 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,155 @@
1+
from workers import WorkerEntrypoint, Response, DurableObject
2+
import js
3+
import json
4+
import time
5+
from pyodide.ffi import create_proxy
6+
from urllib.parse import urlparse
7+
8+
9+
class BlueskyFirehoseConsumer(DurableObject):
10+
"""Durable Object that maintains a persistent WebSocket connection to Bluesky Jetstream."""
11+
12+
def __init__(self, state, env):
13+
super().__init__(state, env)
14+
self.websocket = None
15+
self.connected = False
16+
self.last_print_time = 0 # Track last time we printed a post
17+
18+
async def fetch(self, request):
19+
"""Handle incoming requests to the Durable Object."""
20+
# If we're not connected then make sure we start a connection.
21+
if not self.connected:
22+
await self._schedule_next_alarm()
23+
await self._connect_to_jetstream()
24+
25+
url = urlparse(request.url)
26+
path = url.path
27+
28+
if path == "/status":
29+
status = "connected" if self.connected else "disconnected"
30+
return Response(f"Firehose status: {status}")
31+
else:
32+
return Response("Available endpoints: /status")
33+
34+
async def alarm(self):
35+
"""Handle alarm events - used to ensure that the DO stays alive and connected"""
36+
print("Alarm triggered - making sure we are connected to jetstream...")
37+
if not self.connected:
38+
await self._connect_to_jetstream()
39+
else:
40+
print("Already connected, skipping reconnection")
41+
42+
# Schedule the next alarm to keep the DO alive
43+
await self._schedule_next_alarm()
44+
45+
async def _schedule_next_alarm(self):
46+
"""Schedule the next alarm to run in 1 minute to keep the DO alive."""
47+
# Schedule alarm for 1 minute from now, overwriting any existing alarms
48+
next_alarm_time = int(time.time() * 1000) + 60000
49+
return await self.ctx.storage.setAlarm(next_alarm_time)
50+
51+
async def _connect_to_jetstream(self):
52+
"""Connect to the Bluesky Jetstream WebSocket and start consuming events."""
53+
# Get the last event timestamp from storage to resume from the right position
54+
last_timestamp = self.ctx.storage.kv.get("last_event_timestamp")
55+
56+
# Jetstream endpoint - we'll filter for posts
57+
# Using wantedCollections parameter to only get post events
58+
jetstream_url = "wss://jetstream2.us-east.bsky.network/subscribe?wantedCollections=app.bsky.feed.post"
59+
60+
# If we have a last timestamp, add it to resume from that point
61+
if last_timestamp:
62+
jetstream_url += f"&cursor={last_timestamp}"
63+
print(
64+
f"Connecting to Bluesky Jetstream at {jetstream_url} (resuming from timestamp: {last_timestamp})"
65+
)
66+
else:
67+
print(
68+
f"Connecting to Bluesky Jetstream at {jetstream_url} (starting fresh)"
69+
)
70+
71+
# Create WebSocket using JS FFI
72+
ws = js.WebSocket.new(jetstream_url)
73+
self.websocket = ws
74+
75+
# Set up event handlers using JS FFI
76+
async def on_open(event):
77+
self.connected = True
78+
print("Connected to Bluesky Jetstream firehose!")
79+
print(
80+
"Filtering for: app.bsky.feed.post (post events, rate limited to 1/sec)"
81+
)
82+
# Ensure alarm is set when we connect
83+
await self._schedule_next_alarm()
84+
85+
def on_message(event):
86+
try:
87+
# Parse the JSON message
88+
data = json.loads(event.data)
89+
90+
# Store the timestamp for resumption on reconnect
91+
time_us = data.get("time_us")
92+
if time_us:
93+
# Store the timestamp asynchronously
94+
self.ctx.storage.kv.put("last_event_timestamp", time_us)
95+
96+
# Jetstream sends different event types
97+
# We're interested in 'commit' events which contain posts
98+
if data.get("kind") == "commit":
99+
commit = data.get("commit", {})
100+
collection = commit.get("collection")
101+
102+
# Filter for post events
103+
if collection == "app.bsky.feed.post":
104+
# Rate limiting: only print at most 1 per second
105+
current_time = time.time()
106+
if current_time - self.last_print_time >= 1.0:
107+
record = commit.get("record", {})
108+
print("Post record", record)
109+
110+
# Update last print time
111+
self.last_print_time = current_time
112+
113+
except Exception as e:
114+
print(f"Error processing message: {e}")
115+
116+
def on_error(event):
117+
print(f"WebSocket error: {event}")
118+
self.connected = False
119+
self.ctx.abort("WebSocket error occurred")
120+
121+
async def on_close(event):
122+
print(f"WebSocket closed: code={event.code}, reason={event.reason}")
123+
self.connected = False
124+
self.ctx.abort("WebSocket closed unexpectedly")
125+
126+
# Attach event handlers
127+
#
128+
# Note that ordinarily proxies need to be destroyed once they are no longer used.
129+
# However, in this Durable Object context, the WebSocket and its event listeners
130+
# persist for the lifetime of the Durable Object, so we don't explicitly destroy
131+
# the proxies here. When the websocket connection closes, the Durable Object
132+
# is restarted which destroys these proxies.
133+
#
134+
# In the future, we plan to provide support for native Python websocket APIs which
135+
# should eliminate the need for proxy wrappers.
136+
ws.addEventListener("open", create_proxy(on_open))
137+
ws.addEventListener("message", create_proxy(on_message))
138+
ws.addEventListener("error", create_proxy(on_error))
139+
ws.addEventListener("close", create_proxy(on_close))
140+
141+
142+
class Default(WorkerEntrypoint):
143+
"""Main worker entry point that routes requests to the Durable Object."""
144+
145+
async def fetch(self, request):
146+
# Get the Durable Object namespace from the environment
147+
namespace = self.env.BLUESKY_FIREHOSE
148+
149+
# Use a fixed ID so we always connect to the same Durable Object instance
150+
# This ensures we maintain a single persistent connection
151+
id = namespace.idFromName("bluesky-consumer")
152+
stub = namespace.get(id)
153+
154+
# Forward the request to the Durable Object
155+
return await stub.fetch(request)

14-websocket-stream-consumer/uv.lock

Lines changed: 168 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

0 commit comments

Comments
 (0)