Coverage for app / middleware / core_context.py: 100%

17 statements  

« prev     ^ index     » next       coverage.py v7.13.4, created at 2026-10-31 11:23 +0000

1"""Reads what svc-core says about a request's work — the workspace it is done 

2in (``X-Workspace``), the invocation it is part of (``X-Invocation-Id``), the 

3most its model calls may spend (``X-Spend-Limit``) and the web sources its 

4tools may use (``X-Web-Policy``) — into ``app.common``, for the trace rows the 

5request writes, the meter's check and the web tools' domain policy. 

6 

7A pure ASGI middleware, not ``BaseHTTPMiddleware``: the values are set in the 

8request's own task, so the endpoint, a streamed response's generator, its 

9background tasks and ``LLMUsageMiddleware``'s leftover trace — all run inside 

10this call — read them. Registered outside ``LLMUsageMiddleware`` for that last 

11reason. 

12""" 

13 

14from typing import Any 

15 

16from app.common import invocation, spend_limit, web_policy, workspace 

17 

18#: Each value svc-core forwards: its header, and the module that holds it for 

19#: the request (``set_current`` / ``reset``). Adding one is one entry. 

20_FORWARDED = (workspace, invocation, spend_limit, web_policy) 

21_HEADERS = tuple((module.HEADER.lower().encode(), module) for module in _FORWARDED) 

22 

23 

24class CoreContextMiddleware: 

25 def __init__(self, app: Any) -> None: 

26 self.app = app 

27 

28 async def __call__(self, scope: dict, receive: Any, send: Any) -> None: 

29 if scope.get("type") not in ("http", "websocket"): 

30 await self.app(scope, receive, send) 

31 return 

32 headers = { 

33 name.lower(): value.decode("latin-1") 

34 for name, value in scope.get("headers") or [] 

35 } 

36 tokens = [ 

37 (module, module.set_current(headers.get(header))) 

38 for header, module in _HEADERS 

39 ] 

40 try: 

41 await self.app(scope, receive, send) 

42 finally: 

43 for module, token in reversed(tokens): 

44 module.reset(token)