77 PostgresLifespanStateKeys ,
88 postgres_lifespan ,
99)
10+ from servicelib .fastapi .prometheus_instrumentation import (
11+ initialize_prometheus_instrumentation ,
12+ lifespan_prometheus_instrumentation ,
13+ )
14+ from servicelib .fastapi .tracing import initialize_tracing
1015
11- from .._meta import APP_FINISHED_BANNER_MSG , APP_STARTED_BANNER_MSG
16+ from .._meta import APP_FINISHED_BANNER_MSG , APP_NAME , APP_STARTED_BANNER_MSG
1217from ..db .events import setup_database
1318from ..services .director import setup_director
1419from ..services .function_services import setup_function_services
@@ -33,18 +38,34 @@ async def _setup_app(app: FastAPI) -> AsyncIterator[State]:
3338
3439 settings : ApplicationSettings = app .state .settings
3540
41+ if settings .CATALOG_TRACING :
42+ initialize_tracing (app , settings .CATALOG_TRACING , APP_NAME )
43+
3644 yield {
3745 PostgresLifespanStateKeys .POSTGRES_SETTINGS : settings .CATALOG_POSTGRES ,
46+ "prometheus_instrumentation_enabled" : settings .CATALOG_PROMETHEUS_INSTRUMENTATION_ENABLED ,
3847 }
3948
4049 flush_finished_banner ()
4150
4251
52+ async def _setup_prometheus_instrumentation_adapter (
53+ app : FastAPI , state : State
54+ ) -> AsyncIterator [State ]:
55+ enabled = state .get ("prometheus_instrumentation_enabled" , False )
56+ if enabled :
57+ initialize_prometheus_instrumentation (app )
58+ async for _state in lifespan_prometheus_instrumentation (app ):
59+ yield _state
60+
61+
4362def create_app_lifespan ():
4463 # app lifespan
4564 app_lifespan = LifespanManager ()
4665 app_lifespan .add (_setup_app )
4766
67+ # WARNING: order matters
68+
4869 # - postgres lifespan
4970 postgres_lifespan .add (setup_database )
5071 app_lifespan .include (postgres_lifespan )
@@ -61,4 +82,7 @@ def create_app_lifespan():
6182 # - background task lifespan
6283 app_lifespan .add (setup_background_task )
6384
85+ # - prometheus instrumentation lifespan
86+ app_lifespan .add (_setup_prometheus_instrumentation_adapter )
87+
6488 return app_lifespan
0 commit comments