From 28f4ca4050e0dcd33e20ef307ab7f910cfbd11ba Mon Sep 17 00:00:00 2001 From: Sheena Artrip Date: Tue, 15 Nov 2022 16:05:44 -0800 Subject: [PATCH] Add no-op asgi-lifespan handling Super simple hook that checks for lifespan and immediately responds type.complete, essentially making startup/shutdown lifespan events no-ops for the prometheus ASGI app. Fixes #855 ``` from hypercorn.middleware import DispatcherMiddleware from prometheus_client import make_asgi_app import asyncio async def main(): from hypercorn.asyncio import serve from hypercorn.config import Config app = DispatcherMiddleware({ "/metrics": make_asgi_app(), }) config = Config() config.bind = ["localhost:8080"] await serve(app, config) ``` Before: ``` assert scope.get("type") == "http" AssertionError ``` After: ``` [2022-11-15 16:05:20 -0800] [59048] [INFO] Running on http://127.0.0.1:8080 (CTRL + C to quit) INFO:hypercorn.error:Running on http://127.0.0.1:8080 (CTRL + C to quit) ``` Signed-off-by: Sheena Artrip --- prometheus_client/asgi.py | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/prometheus_client/asgi.py b/prometheus_client/asgi.py index 6f72838b..e2ac2be3 100644 --- a/prometheus_client/asgi.py +++ b/prometheus_client/asgi.py @@ -9,6 +9,10 @@ def make_asgi_app(registry: CollectorRegistry = REGISTRY, disable_compression: b """Create a ASGI app which serves the metrics from a registry.""" async def prometheus_app(scope, receive, send): + if scope.get("type") == "lifespan": + payload = await receive() + await send({'type': payload['type'] + ".complete"}) + return assert scope.get("type") == "http" # Prepare parameters params = parse_qs(scope.get('query_string', b''))