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(