Coverage for middleware/trace_middleware.py: 89.02%

70 statements  

« prev     ^ index     » next       coverage.py v7.10.6, created at 2026-11-30 15:10 +0000

1""" 

2Trace Middleware - Request Tracing for Distributed Logging 

3 

4Extracts session_id and request_id from HTTP headers and binds them 

5to structlog context for all subsequent logging in the request. 

6 

7Headers: 

8- X-Session-ID: Frontend session identifier (mt-sess-{uuid}) 

9- X-Request-ID: Per-request identifier (mt-req-{uuid}) 

10 

11If headers are not provided, generates new identifiers. 

12 

13It also writes the access log: one JSON line per request, levelled by 

14status (5xx ERROR, 4xx WARNING), with an unhandled exception folded into 

15that same line. It is pure ASGI rather than BaseHTTPMiddleware so the trace 

16IDs stay bound while the response is sent and while the exception 

17propagates - BaseHTTPMiddleware unbinds them before either (SB-1283). 

18""" 

19 

20import logging 

21import re 

22import time 

23import uuid 

24from contextvars import ContextVar 

25 

26import structlog 

27from starlette.datastructures import Headers, MutableHeaders 

28from starlette.types import ASGIApp, Message, Receive, Scope, Send 

29 

30from services.invite_service import invite_code_ref 

31 

32access_logger = structlog.get_logger("access") 

33 

34# Probe and scrape traffic: logged at DEBUG when it succeeds, so the 

35# kubelet's every-5s health checks do not bury real requests. 

36QUIET_PATHS = frozenset({"/health", "/metrics"}) 

37 

38# Context variables for trace IDs - accessible throughout the request lifecycle 

39_session_id: ContextVar[str | None] = ContextVar("session_id", default=None) 

40_request_id: ContextVar[str | None] = ContextVar("request_id", default=None) 

41 

42 

43def generate_request_id() -> str: 

44 """Generate a new request ID (8 hex chars for easy copy/paste).""" 

45 return f"mt-req-{uuid.uuid4().hex[:8]}" 

46 

47 

48def generate_session_id() -> str: 

49 """Generate a new session ID (8 hex chars, used when frontend doesn't provide one).""" 

50 return f"mt-sess-{uuid.uuid4().hex[:8]}" 

51 

52 

53def get_trace_context() -> tuple[str | None, str | None]: 

54 """ 

55 Get current trace context (session_id, request_id). 

56 

57 Returns: 

58 Tuple of (session_id, request_id) from current context 

59 """ 

60 return _session_id.get(), _request_id.get() 

61 

62 

63def get_session_id() -> str | None: 

64 """Get current session ID from context.""" 

65 return _session_id.get() 

66 

67 

68def get_request_id() -> str | None: 

69 """Get current request ID from context.""" 

70 return _request_id.get() 

71 

72 

73# The one public route whose path carries a credential: an invite code is a 

74# bearer token for signing up, so it never reaches the access log (SB-1768). 

75_INVITE_CODE_IN_PATH = re.compile(r"(/api/invites/validate/)([^/]+)") 

76 

77 

78def loggable_path(scope: Scope) -> str: 

79 """The path to write to the access log. 

80 

81 The matched route's template (`/api/invites/validate/{invite_code}`) when 

82 there is one, so no path parameter is logged. An unmatched request falls 

83 back to the raw path, with any invite code replaced by its log-safe ref. 

84 """ 

85 route_path = getattr(scope.get("route"), "path", None) 

86 if isinstance(route_path, str): 

87 return route_path 

88 return _INVITE_CODE_IN_PATH.sub(lambda m: m.group(1) + invite_code_ref(m.group(2)), scope["path"]) 

89 

90 

91def access_log_level(status: int, path: str = "") -> int: 

92 """Log level for a finished request: 5xx ERROR, 4xx WARNING, else INFO. 

93 

94 Successful probe/scrape requests (QUIET_PATHS) drop to DEBUG. 

95 """ 

96 if status >= 500: 

97 return logging.ERROR 

98 if status >= 400: 

99 return logging.WARNING 

100 if path in QUIET_PATHS: 100 ↛ 101line 100 didn't jump to line 101 because the condition on line 100 was never true

101 return logging.DEBUG 

102 return logging.INFO 

103 

104 

105class TraceMiddleware: 

106 """ 

107 Binds session_id/request_id to the structlog context for the whole 

108 request - including response send and exception propagation - and 

109 writes the access log line. 

110 """ 

111 

112 def __init__(self, app: ASGIApp) -> None: 

113 self.app = app 

114 

115 async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None: 

116 if scope["type"] != "http": 

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

118 return 

119 

120 headers = Headers(scope=scope) 

121 session_id = headers.get("x-session-id") or generate_session_id() 

122 request_id = headers.get("x-request-id") or generate_request_id() 

123 

124 session_token = _session_id.set(session_id) 

125 request_token = _request_id.set(request_id) 

126 structlog.contextvars.bind_contextvars(session_id=session_id, request_id=request_id) 

127 

128 status: int | None = None 

129 started = time.perf_counter() 

130 

131 async def send_with_trace(message: Message) -> None: 

132 nonlocal status 

133 if message["type"] == "http.response.start": 

134 status = message["status"] 

135 MutableHeaders(scope=message)["X-Request-ID"] = request_id 

136 await send(message) 

137 

138 exc: BaseException | None = None 

139 try: 

140 await self.app(scope, receive, send_with_trace) 

141 except Exception as e: 

142 exc = e 

143 # ServerErrorMiddleware (outside us) turns this into the 500. 

144 # Mark it so uvicorn's own "Exception in ASGI application" 

145 # record is dropped instead of repeating the traceback. 

146 e._mt_logged = True # type: ignore[attr-defined] 

147 raise 

148 finally: 

149 final_status = 500 if exc is not None and status is None else status or 0 

150 client = scope.get("client") 

151 access_logger.log( 

152 access_log_level(final_status, scope["path"]), 

153 "http_request", 

154 method=scope["method"], 

155 path=loggable_path(scope), 

156 status=final_status, 

157 duration_ms=round((time.perf_counter() - started) * 1000, 1), 

158 client_ip=client[0] if client else None, 

159 exc_info=exc, 

160 ) 

161 _session_id.reset(session_token) 

162 _request_id.reset(request_token) 

163 structlog.contextvars.unbind_contextvars("session_id", "request_id")