Skip to content

Commit 0c9e87b

Browse files
committed
update best effort async client cleanup strategy
1 parent f916469 commit 0c9e87b

1 file changed

Lines changed: 17 additions & 9 deletions

File tree

src/bubble_data_api_client/pool.py

Lines changed: 17 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -73,23 +73,31 @@ def _atexit_cleanup() -> None:
7373
if not clients_to_close:
7474
return
7575

76-
# check if there's already a running loop
76+
# detect loop state to choose cleanup strategy
7777
try:
7878
running_loop = asyncio.get_running_loop()
7979
except RuntimeError:
8080
running_loop = None
8181

8282
try:
83-
if running_loop is not None:
84-
# loop still running at atexit, schedule cleanup tasks
83+
if running_loop is not None and running_loop.is_running():
84+
# edge case: event loop still running, schedule cleanup with timeout
8585
for client in clients_to_close:
86-
running_loop.create_task(client.aclose())
86+
future = asyncio.run_coroutine_threadsafe(client.aclose(), running_loop)
87+
try:
88+
future.result(timeout=5.0)
89+
except Exception:
90+
pass
8791
else:
88-
# no running loop, create one for cleanup
89-
loop = asyncio.new_event_loop()
90-
for client in clients_to_close:
91-
loop.run_until_complete(client.aclose())
92-
loop.close()
92+
# no running loop, create one and close all clients
93+
async def _close_all() -> None:
94+
for client in clients_to_close:
95+
await client.aclose()
96+
97+
try:
98+
asyncio.run(_close_all())
99+
except Exception:
100+
pass
93101
except Exception:
94102
pass
95103

0 commit comments

Comments
 (0)