fix: stopping background task properly on shutdown
This commit is contained in:
parent
2106dadf94
commit
4acbaeb29c
1 changed files with 18 additions and 4 deletions
22
router.py
22
router.py
|
|
@ -4123,6 +4123,16 @@ async def startup_event() -> None:
|
||||||
@app.on_event("shutdown")
|
@app.on_event("shutdown")
|
||||||
async def shutdown_event() -> None:
|
async def shutdown_event() -> None:
|
||||||
await close_all_sse_queues()
|
await close_all_sse_queues()
|
||||||
|
|
||||||
|
# Stop background tasks first so they stop touching the DB before we close it.
|
||||||
|
for t in (token_worker_task, flush_task):
|
||||||
|
if t is not None:
|
||||||
|
t.cancel()
|
||||||
|
try:
|
||||||
|
await t
|
||||||
|
except (asyncio.CancelledError, Exception):
|
||||||
|
pass
|
||||||
|
|
||||||
await flush_remaining_buffers()
|
await flush_remaining_buffers()
|
||||||
await app_state["session"].close()
|
await app_state["session"].close()
|
||||||
|
|
||||||
|
|
@ -4142,7 +4152,11 @@ async def shutdown_event() -> None:
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
print(f"[shutdown] Error closing httpx client {ep}: {e}")
|
print(f"[shutdown] Error closing httpx client {ep}: {e}")
|
||||||
|
|
||||||
if token_worker_task is not None:
|
# Close the aiosqlite connection last — its worker thread is non-daemon
|
||||||
token_worker_task.cancel()
|
# and would otherwise keep the interpreter alive after lifespan completes.
|
||||||
if flush_task is not None:
|
if db is not None:
|
||||||
flush_task.cancel()
|
try:
|
||||||
|
await db.close()
|
||||||
|
print("[shutdown] Closed token DB connection.")
|
||||||
|
except Exception as e:
|
||||||
|
print(f"[shutdown] Error closing DB: {e}")
|
||||||
|
|
|
||||||
Loading…
Add table
Add a link
Reference in a new issue