33from websockets .client import connect as connect_async
44from lighter .configuration import Configuration
55from lighter .endpoint_profiles import join_url
6+ import logging
7+ logger = logging .getLogger (__name__ )
68
79class WsClient :
810 def __init__ (
@@ -14,6 +16,8 @@ def __init__(
1416 on_order_book_update = print ,
1517 on_account_update = print ,
1618 ws_url = None ,
19+ on_shutdown = None ,
20+ on_unhandled_message = None ,
1721 ):
1822 if ws_url is not None :
1923 self .base_url = ws_url .rstrip ("/" )
@@ -35,6 +39,8 @@ def __init__(
3539
3640 self .on_order_book_update = on_order_book_update
3741 self .on_account_update = on_account_update
42+ self .on_shutdown = on_shutdown
43+ self .on_unhandled_message = on_unhandled_message
3844
3945 self .ws = None
4046
@@ -57,6 +63,8 @@ def on_message(self, ws, message):
5763 elif message_type == "ping" :
5864 # Respond to ping with pong
5965 ws .send (json .dumps ({"type" : "pong" }))
66+ elif message_type == "shutdown" :
67+ self .handle_shutdown (message )
6068 else :
6169 self .handle_unhandled_message (message )
6270
@@ -149,7 +157,17 @@ def handle_update_account(self, message):
149157 self .on_account_update (account_id , self .account_states [account_id ])
150158
151159 def handle_unhandled_message (self , message ):
152- raise Exception (f"Unhandled message: { message } " )
160+ if self .on_unhandled_message :
161+ self .on_unhandled_message (message )
162+ else :
163+ logger .warning ("Unhandled message type %r: %s" , message .get ("type" ), message )
164+
165+ def handle_shutdown (self , message ):
166+ close_in_ms = message .get ("close_in_ms" , 0 )
167+ if self .on_shutdown :
168+ self .on_shutdown (close_in_ms )
169+ else :
170+ print (f"Server shutting down, connection closes in { close_in_ms } ms" )
153171
154172 def on_error (self , ws , error ):
155173 raise Exception (f"Error: { error } " )
0 commit comments