Resource Management — Aquilia Documentation
Comprehensive guide and documentation for Resource Management in the Aquilia framework. View API reference, examples, and implementation patterns.
SSE SYSTEM / RESOURCE MANAGEMENT Resource & Disconnect Management Prevent connection and file handle leaks in long-lived SSE streams. Manage client disconnects and clean up resources safely. Client Disconnect Mechanics Because Server-Sent Events can stream indefinitely, clients frequently close their connections abruptly (e.g. by closing the browser tab, navigating away, or experiencing a network dropout). When a connection is severed, the ASGI server fails to write the next byte chunk and terminates the handler task. In Python's asyncio, this triggers a task cancellation, raising an asyncio.CancelledError inside the active generator function. Failure to handle this cancellation will cause leased databases, connection pools, or file descriptors to remain open, leading to leakages. Safe Generator Pattern To guarantee cleanup operations execute, always wrap your streaming loop inside a try...finally statement. When the task is cancelled, control flows automatically into the finally block: import asyncio from aquilia.controller import Controller, GET, RequestCtx from aquilia.sse import SSEResponse, SSEEvent class SafeController(Controller): @GET("/sse/safe-metrics") async def get_metrics(self, ctx: RequestCtx): return SSEResponse(self._stream_safely()) async def _stream_safely(self): # 1. Acquire connection or lock db_connection = await self.db_pool.acquire() try: while True: data = await db_connection.fetch_row("SELECT * FROM metrics ORDER BY id DESC LIMIT 1") yield SSEEvent(data=str(data)) await asyncio.sleep(2.0) except asyncio.CancelledError: # Caught automatically when browser closes connection print("Stream cancelled: Client disconnected.") raise finally: # 2. Guarantee releasing connection back to pool await self.db_pool.release(db_connection) print("Successfully released DB connection.") Configuring Stream Timeouts Allowing streams to run indefinitely is a security risk and can lead to resources drying up. You can configure a maximum lifetime for your streams by passing the timeout parameter to SSEResponse (measured in seconds). Once the timeout is reached, the response completes, and the client receives a finished connection. The browser will then trigger automatic reconnection according to spec. OpenAI Streaming Built-in Effects )
Go to Homepage