From 4e338f7bac06b5ed42b736e9df8e4accb1814d65 Mon Sep 17 00:00:00 2001 From: callebtc <93376500+callebtc@users.noreply.github.com> Date: Sun, 17 Nov 2024 17:39:11 +0100 Subject: [PATCH] catch websocket disconenct errors --- cashu/mint/events/client.py | 5 ++++- cashu/mint/router.py | 10 ++++++++-- 2 files changed, 12 insertions(+), 3 deletions(-) diff --git a/cashu/mint/events/client.py b/cashu/mint/events/client.py index e54c0736..06959fc0 100644 --- a/cashu/mint/events/client.py +++ b/cashu/mint/events/client.py @@ -2,7 +2,7 @@ import json from typing import List, Union -from fastapi import WebSocket +from fastapi import WebSocket, WebSocketDisconnect from loguru import logger from ...core.base import MeltQuote, MintQuote, ProofState @@ -122,6 +122,9 @@ async def start(self): resp = await self._handle_request(req) # Send the response await self._send_msg(resp) + except WebSocketDisconnect as e: + logger.debug(f"Websocket disconnected: {e}") + raise e except Exception as e: err = JSONRPCErrorResponse( error=JSONRPCError( diff --git a/cashu/mint/router.py b/cashu/mint/router.py index 5e7f23c7..abce4c69 100644 --- a/cashu/mint/router.py +++ b/cashu/mint/router.py @@ -1,7 +1,7 @@ import asyncio import time -from fastapi import APIRouter, Request, WebSocket +from fastapi import APIRouter, Request, WebSocket, WebSocketDisconnect from loguru import logger from ..core.errors import KeysetNotFoundError @@ -204,6 +204,7 @@ async def get_mint_quote(request: Request, quote: str) -> PostMintQuoteResponse: @router.websocket("/v1/ws", name="Websocket endpoint for subscriptions") async def websocket_endpoint(websocket: WebSocket): limit_websocket(websocket) + disconnected = False try: client = ledger.events.add_client(websocket, ledger.db, ledger.crud) except Exception as e: @@ -214,11 +215,16 @@ async def websocket_endpoint(websocket: WebSocket): try: # this will block until the session is closed await client.start() + except WebSocketDisconnect as e: + logger.debug(f"Websocket disconnected: {e}") + disconnected = True + return except Exception as e: logger.debug(f"Exception: {e}") ledger.events.remove_client(client) finally: - await asyncio.wait_for(websocket.close(), timeout=1) + if not disconnected: + await asyncio.wait_for(websocket.close(), timeout=1) @router.post(