1"""HTTP middleware that manages the per-request database connection lifecycle."""
2
3from functools import partial
4
5from plain.http import HttpMiddleware, Response
6from plain.http.request import Request
7
8from .db import get_connection, return_database_connection
9
10
11class DatabaseConnectionMiddleware(HttpMiddleware):
12 """Returns the per-request DB connection to the pool at request end.
13
14 Every response gets a closer that returns the request's connection
15 wrapper when the response is closed. The wrapper is created here if
16 the request never touched the database: it is lazy (no pool checkout
17 until first use, and returning an unused one is a no-op), and creating
18 it now, on the request context, means every task or thread that later
19 runs from a copy of that context shares the one wrapper the closer
20 knows about. The response is closed inside the request context once
21 its body is sent, but the closer is still handed the wrapper
22 explicitly, so returning it doesn't depend on which context a close
23 runs in.
24
25 A non-streaming response also returns the connection right now:
26 the view is done with it. A streaming response keeps it until the
27 body is drained — otherwise a generator that lazily queries (e.g.
28 `Model.query.iterator()` inside a `StreamingResponse`) would see its
29 cursor invalidated when the pool rolls back the returned connection.
30 A websocket accept is not streaming — no view code has run when this
31 sees it — so its handshake connection goes back to the pool before the
32 socket starts, the wrapper re-acquires on the first query inside the
33 socket if there is one, and the closer returns that when the socket
34 ends. A viewer holding a socket open for an hour holds no database
35 connection with it.
36 """
37
38 def after_response(self, request: Request, response: Response) -> Response:
39 conn = get_connection()
40 response._resource_closers.append(partial(return_database_connection, conn))
41 if not response.streaming:
42 return_database_connection(conn)
43 return response