]> git.ipfire.org Git - dbl.git/commitdiff
api: Add a middleware that ads timing information about the request
authorMichael Tremer <michael.tremer@ipfire.org>
Tue, 3 Mar 2026 15:49:59 +0000 (15:49 +0000)
committerMichael Tremer <michael.tremer@ipfire.org>
Tue, 3 Mar 2026 15:49:59 +0000 (15:49 +0000)
Signed-off-by: Michael Tremer <michael.tremer@ipfire.org>
src/dbl/api/__init__.py
src/dbl/api/middlewares.py

index b92329fe354b118773bab01df6e9329755c3f410..ced0273688b71ab21136972748b7b9573f0e15fa 100644 (file)
@@ -41,6 +41,7 @@ app = fastapi.FastAPI(
        debug = True,
 )
 app.add_middleware(middlewares.DatabaseSessionMiddleware)
+app.add_middleware(middlewares.ProcessingTimeMiddleware)
 
 # Initialize the backend
 backend = app.state.backend = Backend(
index 36e249fd0f437e818d3427841e30732f4d1fce30..666acee091f36c59c2a7740794d6afe3bd6899c9 100644 (file)
@@ -19,6 +19,7 @@
 ###############################################################################
 
 import fastapi
+import time
 
 class DatabaseSessionMiddleware(fastapi.applications.BaseHTTPMiddleware):
        async def dispatch(self, request: fastapi.Request, call_next):
@@ -27,3 +28,24 @@ class DatabaseSessionMiddleware(fastapi.applications.BaseHTTPMiddleware):
                # Acquire a new database session and process the request
                async with await backend.db.session() as session:
                        return await call_next(request)
+
+
+class ProcessingTimeMiddleware(fastapi.applications.BaseHTTPMiddleware):
+       """
+               Adds a new header X-Process-Time that shows
+               how long the API needed to process the request.
+       """
+       async def dispatch(self, request: fastapi.Request, call_next):
+               # Store the start time
+               t_start = time.perf_counter()
+
+               # Continue to run the request...
+               response = await call_next(request)
+
+               # Store the end time
+               t_end = time.perf_counter()
+
+               # Set the process time in the header in milliseconds
+               response.headers["X-Process-Time"] = "%.2fms" % ((t_end - t_start) * 1000.0)
+
+               return response