@@ -163,14 +163,18 @@ async def session(self) -> aiohttp.ClientSession:
163
163
self ._session = aiohttp .ClientSession ()
164
164
return self ._session
165
165
166
- def close_session (self ):
166
+ def close_session (self , using_new_loop : bool = False ):
167
167
"""
168
168
Closes the internal `aiohttp <https://github.com/aio-libs/aiohttp>`_ client session synchronously.
169
169
170
170
This method ensures the proper closure and cleanup of the aiohttp client session, releasing any
171
171
resources like open connections and internal buffers. It is crucial for preventing resource leakage
172
172
and should be called when the dendrite instance is no longer in use, especially in synchronous contexts.
173
173
174
+ Arguments:
175
+ using_new_loop: A flag to determine whether this has been called with a new event loop rather than
176
+ the default. This will indicate whether to close this event loop at the end of this call.
177
+
174
178
Note:
175
179
This method utilizes asyncio's event loop to close the session asynchronously from a synchronous context.
176
180
It is advisable to use this method only when asynchronous context management is not feasible.
@@ -188,6 +192,8 @@ def close_session(self):
188
192
if self ._session :
189
193
loop = asyncio .get_event_loop ()
190
194
loop .run_until_complete (self ._session .close ())
195
+ if using_new_loop :
196
+ loop .close ()
191
197
self ._session = None
192
198
193
199
async def aclose_session (self ):
@@ -374,16 +380,20 @@ def query(
374
380
category = DeprecationWarning ,
375
381
)
376
382
result = None
383
+ use_new_loop = False
377
384
try :
378
385
loop = asyncio .get_event_loop ()
379
386
result = loop .run_until_complete (self .forward (* args , ** kwargs ))
380
- except Exception :
387
+ except Exception as e :
388
+ logging .debug (
389
+ f"Exception encountered while running Dendrite.query initially: { e } "
390
+ )
381
391
new_loop = asyncio .new_event_loop ()
382
392
asyncio .set_event_loop (new_loop )
383
393
result = new_loop .run_until_complete (self .forward (* args , ** kwargs ))
384
- new_loop . close ()
394
+ use_new_loop = True
385
395
finally :
386
- self .close_session ()
396
+ self .close_session (using_new_loop = use_new_loop )
387
397
return result # type: ignore
388
398
389
399
async def forward (
0 commit comments