11from workers import WorkerEntrypoint , Response , DurableObject
2- import js
2+ from wasmsockets . client import connect as ws_connect
33import json
44import time
5- from pyodide . ffi import create_proxy
5+ import asyncio
66from urllib .parse import urlparse
77
8-
98class BlueskyFirehoseConsumer (DurableObject ):
109 """Durable Object that maintains a persistent WebSocket connection to Bluesky Jetstream."""
1110
@@ -14,6 +13,7 @@ def __init__(self, state, env):
1413 self .websocket = None
1514 self .connected = False
1615 self .last_print_time = 0 # Track last time we printed a post
16+ self .consumer_task = None # Track the message consumer task
1717
1818 async def fetch (self , request ):
1919 """Handle incoming requests to the Durable Object."""
@@ -68,24 +68,36 @@ async def _connect_to_jetstream(self):
6868 f"Connecting to Bluesky Jetstream at { jetstream_url } (starting fresh)"
6969 )
7070
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 ):
71+ try :
72+ # Connect using wasmsockets - provides a websockets-like interface
73+ self .websocket = await ws_connect (jetstream_url )
7774 self .connected = True
75+
7876 print ("Connected to Bluesky Jetstream firehose!" )
7977 print (
8078 "Filtering for: app.bsky.feed.post (post events, rate limited to 1/sec)"
8179 )
80+
8281 # Ensure alarm is set when we connect
8382 await self ._schedule_next_alarm ()
8483
85- def on_message (event ):
84+ # Start consuming messages in the background
85+ self .consumer_task = asyncio .create_task (self ._consume_messages ())
86+
87+ except Exception as e :
88+ print (f"Failed to connect to Jetstream: { e } " )
89+ self .connected = False
90+ self .ctx .abort (f"WebSocket connection failed: { e } " )
91+
92+ async def _consume_messages (self ):
93+ """Consume messages from the WebSocket connection."""
94+ while self .connected and self .websocket :
95+ # Receive message from WebSocket
8696 try :
97+ message = await self .websocket .recv ()
98+
8799 # Parse the JSON message
88- data = json .loads (event . data )
100+ data = json .loads (message )
89101
90102 # Store the timestamp for resumption on reconnect
91103 time_us = data .get ("time_us" )
@@ -110,33 +122,13 @@ def on_message(event):
110122 # Update last print time
111123 self .last_print_time = current_time
112124
125+ except json .JSONDecodeError as e :
126+ print (f"Error parsing message JSON: { e } " )
113127 except Exception as e :
114128 print (f"Error processing message: { e } " )
129+ self .connected = False
130+ self .ctx .abort (f"WebSocket message processing failed: { e } " )
115131
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 ))
140132
141133
142134class Default (WorkerEntrypoint ):
0 commit comments