Skip to content

Commit

Permalink
fix: better handling of WS close
Browse files Browse the repository at this point in the history
  • Loading branch information
motorina0 committed Nov 1, 2023
1 parent 986d1d7 commit 4edfc28
Showing 1 changed file with 21 additions and 5 deletions.
26 changes: 21 additions & 5 deletions nostr/nostr_client.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,12 +25,20 @@ async def connect_to_nostrclient_ws(
) -> WebSocketApp:
def on_error(_, error):
logger.warning(error)
self.send_req_queue.put_nowait(ValueError("Websocket error."))
self.recieve_event_queue.put_nowait(ValueError("Websocket error."))

def on_close(_, status_code, message):
logger.warning(f"Websocket closed: '{status_code}' '{message}'")
self.send_req_queue.put_nowait(ValueError("Websocket close."))
self.recieve_event_queue.put_nowait(ValueError("Websocket close."))

logger.debug(f"Subscribing to websockets for nostrclient extension")
ws = WebSocketApp(
f"ws://localhost:{settings.port}/nostrclient/api/v1/relay",
on_message=on_message,
on_open=on_open,
on_close=on_close,
on_error=on_error,
)

Expand All @@ -53,6 +61,7 @@ def on_open(_):
def on_message(_, message):
self.recieve_event_queue.put_nowait(message)

self._safe_ws_stop()
running = True

while running:
Expand All @@ -73,7 +82,7 @@ def on_message(_, message):
logger.warning(ex)
if req:
await self.send_req_queue.put(req)
self.ws = None # todo close
self._safe_ws_stop()
await asyncio.sleep(5)

async def publish_nostr_event(self, e: NostrEvent):
Expand Down Expand Up @@ -172,6 +181,15 @@ def _filters_for_user_profile(self, public_keys: List[str], since: int) -> List:

return [profile_filter]

def _safe_ws_stop(self):
if not self.ws:
return
try:
self.ws.close()
except:
pass
self.ws = None

async def restart(self):
await self.unsubscribe_merchants()
# Give some time for the CLOSE events to propagate before restarting
Expand All @@ -181,16 +199,14 @@ async def restart(self):
await self.send_req_queue.put(ValueError("Restarting NostrClient..."))
await self.recieve_event_queue.put(ValueError("Restarting NostrClient..."))

self.ws.close()
self.ws = None
self._safe_ws_stop()

async def stop(self):
await self.unsubscribe_merchants()

# Give some time for the CLOSE events to propagate before closing the connection
await asyncio.sleep(10)
self.ws.close()
self.ws = None
self._safe_ws_stop()

async def unsubscribe_merchants(self):
await self.send_req_queue.put(["CLOSE", self.subscription_id])
Expand Down

0 comments on commit 4edfc28

Please sign in to comment.