Skip to content

Commit

Permalink
catch websocket disconenct errors
Browse files Browse the repository at this point in the history
  • Loading branch information
callebtc committed Nov 17, 2024
1 parent 901b167 commit 4e338f7
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 3 deletions.
5 changes: 4 additions & 1 deletion cashu/mint/events/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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(
Expand Down
10 changes: 8 additions & 2 deletions cashu/mint/router.py
Original file line number Diff line number Diff line change
@@ -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
Expand Down Expand Up @@ -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:
Expand All @@ -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(
Expand Down

0 comments on commit 4e338f7

Please sign in to comment.