feat: add reconnect to nostrclient

This commit is contained in:
Vlad Stan 2023-04-11 19:03:41 +03:00
parent 929d45bed8
commit e05b54468a
5 changed files with 52 additions and 3 deletions

View file

@ -18,6 +18,11 @@ class NostrClient:
self.send_req_queue: Queue = Queue()
self.ws: WebSocketApp = None
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()
async def connect_to_nostrclient_ws(
self, on_open: Callable, on_message: Callable
) -> WebSocketApp:
@ -39,7 +44,10 @@ class NostrClient:
return ws
async def get_event(self):
return await self.recieve_event_queue.get()
value = await self.recieve_event_queue.get()
if isinstance(value, ValueError):
raise value
return value
async def run_forever(self):
def on_open(_):
@ -48,7 +56,9 @@ class NostrClient:
def on_message(_, message):
self.recieve_event_queue.put_nowait(message)
while True:
running = True
while running:
try:
req = None
if not self.ws:
@ -56,7 +66,11 @@ class NostrClient:
# be sure the connection is open
await asyncio.sleep(3)
req = await self.send_req_queue.get()
self.ws.send(json.dumps(req))
if isinstance(req, ValueError):
running = False
logger.warning("Nostr Client stopping")
else:
self.ws.send(json.dumps(req))
except Exception as ex:
logger.warning(ex)
if req: