@@ -105,7 +105,7 @@ def __init__(
105105 self .recv_task = None
106106
107107 self .is_started = asyncio .Event ()
108- self .restart_event = asyncio .Event ()
108+ self ._restart_lock = asyncio .Lock ()
109109
110110 async def start (self ):
111111 while True :
@@ -192,7 +192,8 @@ async def stop(self):
192192
193193 self .ping_task_event .clear ()
194194
195- await self .connection .close ()
195+ if self .connection :
196+ await self .connection .close ()
196197
197198 if self .recv_task :
198199 try :
@@ -205,10 +206,20 @@ async def stop(self):
205206 log .info ("Session stopped" )
206207
207208 async def restart (self ):
208- self .restart_event .set ()
209- await self .stop ()
210- await self .start ()
211- self .restart_event .clear ()
209+ async with self ._restart_lock :
210+ if self .is_started .is_set ():
211+ log .info ("A restart was requested, stopping session..." )
212+ try :
213+ await self .stop ()
214+ except Exception as e :
215+ log .error ("An error occurred during session stop: %s" , e )
216+
217+ log .info ("Restarting session..." )
218+ try :
219+ await self .start ()
220+ log .info ("Session restarted successfully." )
221+ except Exception as e :
222+ log .error ("An error occurred during session start: %s" , e )
212223
213224 async def handle_packet (self , packet ):
214225 try :
@@ -333,6 +344,10 @@ async def recv_worker(self):
333344 packet = await asyncio .wait_for (self .connection .recv (), timeout = 1 )
334345 except asyncio .TimeoutError :
335346 continue
347+ except ConnectionError :
348+ if self .is_started .is_set ():
349+ self .client .loop .create_task (self .restart ())
350+ break
336351
337352 if packet is None or len (packet ) == 4 :
338353 if packet :
@@ -446,21 +461,10 @@ async def invoke(
446461 raise e from None
447462
448463 (log .warning if retries < 2 else log .info )(
449- '[%s] Retrying "%s" due to: %s' ,
464+ '[%s] Retrying "%s" due to: %s. Performing a restart. ' ,
450465 Session .MAX_RETRIES - retries + 1 ,
451466 query_name , str (e ) or repr (e )
452467 )
453468
454- # restart was never being called after Exception block
455- if not self .restart_event .is_set ():
456- self .client .loop .create_task (self .restart ())
457- else :
458- # multiple Exceptions can be raised in a row, so we need to wait for the restart to finish
459- try :
460- await asyncio .wait_for (self .restart_event .wait (), self .WAIT_TIMEOUT )
461- except asyncio .TimeoutError :
462- pass
463-
464- await asyncio .sleep (0.5 )
465-
466- return await self .invoke (query , retries - 1 , timeout )
469+ await self .restart ()
470+ retries -= 1
0 commit comments