Skip to content

Commit

Permalink
fix: subscription close before disconnect
Browse files Browse the repository at this point in the history
  • Loading branch information
motorina0 committed Oct 31, 2023
1 parent fb1df37 commit 09d42f1
Show file tree
Hide file tree
Showing 4 changed files with 14 additions and 10 deletions.
2 changes: 1 addition & 1 deletion nostr/client/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ def reconnect(self, relays):

def close(self):
try:
self.relay_manager.close_subscriptions()
self.relay_manager.close_all_subscriptions()
self.relay_manager.close_connections()

self.running = False
Expand Down
9 changes: 6 additions & 3 deletions nostr/relay_manager.py
Original file line number Diff line number Diff line change
Expand Up @@ -81,11 +81,14 @@ def close_subscription(self, id: str):
except Exception as e:
logger.debug(e)

def close_subscriptions(self):
all_subscriptions = list(self._cached_subscriptions.keys())
for id in all_subscriptions:
def close_subscriptions(self, subscriptions: List[str]):
for id in subscriptions:
self.close_subscription(id)

def close_all_subscriptions(self):
all_subscriptions = list(self._cached_subscriptions.keys())
self.close_subscriptions(all_subscriptions)

def check_and_restart_relays(self):
stopped_relays = [r for r in self.relays.values() if r.shutdown]
for relay in stopped_relays:
Expand Down
9 changes: 5 additions & 4 deletions router.py
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ def start(self):
self.tasks.append(asyncio.create_task(self._client_to_nostr()))
self.tasks.append(asyncio.create_task(self._nostr_to_client()))

def stop(self):
async def stop(self):
nostr_client.relay_manager.close_subscriptions(self.subscriptions)
self.connected = False

Expand All @@ -42,7 +42,7 @@ def stop(self):
pass

try:
self.websocket.close()
await self.websocket.close()
except Exception as _:
pass

Expand All @@ -53,8 +53,9 @@ async def _client_to_nostr(self):
while self.connected:
try:
json_str = await self.websocket.receive_text()
except WebSocketDisconnect:
self.stop()
except WebSocketDisconnect as e:
logger.debug(e)
await self.stop()
break

try:
Expand Down
4 changes: 2 additions & 2 deletions views_api.py
Original file line number Diff line number Diff line change
Expand Up @@ -117,7 +117,7 @@ async def api_test_endpoint(data: TestMessage) -> TestMessageResponse:
async def api_stop():
for router in all_routers:
try:
router.stop()
await router.stop()
all_routers.remove(router)
except Exception as e:
logger.error(e)
Expand Down Expand Up @@ -146,6 +146,6 @@ async def ws_relay(websocket: WebSocket) -> None:
while router.connected:
await asyncio.sleep(10)

router.stop()
await router.stop()
all_routers.remove(router)

0 comments on commit 09d42f1

Please sign in to comment.