arcly_http_core/web/context.rs
1//! The single opaque request boundary. Handlers receive `RequestContext` --
2//! axum/tower primitives are private to this module.
3
4use std::sync::Arc;
5
6use axum::http::{HeaderMap, Method};
7use bytes::Bytes;
8use smallvec::SmallVec;
9use smol_str::SmolStr;
10
11use crate::core::engine::{FrozenDiContainer, RouteSpec};
12use crate::session::Session;
13use crate::web::tenant::TenantConfig;
14
15/// Opaque authenticated-principal claims.
16pub type Claims = serde_json::Map<String, serde_json::Value>;
17
18/// The one and only context passed to every handler.
19///
20/// Carries a full W3C distributed-tracing context:
21/// - `trace_id` (16 bytes) -- preserved across the entire distributed call chain.
22/// - `span_id` (8 bytes) -- this server hop's span; becomes `parent-id` downstream.
23/// - `parent_span_id` -- the upstream caller's span (all-zeros = root span).
24///
25/// Use [`traceparent`](Self::traceparent) to generate the header for outgoing calls.
26#[derive(Clone)]
27pub struct RequestContext {
28 method: Method,
29 raw_path: SmolStr,
30 query: SmolStr,
31 params: SmallVec<[(SmolStr, SmolStr); 4]>,
32 headers: HeaderMap,
33 body: Bytes,
34 claims: Option<Arc<Claims>>,
35 session: Option<Arc<Session>>,
36 tenant: Option<std::sync::Arc<TenantConfig>>,
37 trace_id: [u8; 16],
38 span_id: [u8; 8],
39 parent_span_id: [u8; 8],
40 container: Arc<FrozenDiContainer>,
41 /// Matched route pattern (e.g. `/users/:id`). Empty string for plugin routes.
42 /// Used for cardinality-safe metrics labels — never use raw `path` for labels.
43 route_pattern: &'static str,
44 /// `Some` for macro-registered routes; `None` for plugin-registered routes.
45 route_spec: Option<&'static RouteSpec>,
46 /// Per-request typed storage. Scoped DI without touching the frozen
47 /// container: interceptors / boundary filters deposit request-scoped
48 /// values here, handlers read them back. Dropped with the request.
49 extensions: axum::http::Extensions,
50}
51
52impl RequestContext {
53 #[inline]
54 pub fn method(&self) -> &Method {
55 &self.method
56 }
57 #[inline]
58 pub fn path(&self) -> &str {
59 &self.raw_path
60 }
61
62 #[inline]
63 pub fn query_string(&self) -> Option<&str> {
64 if self.query.is_empty() {
65 None
66 } else {
67 Some(&self.query)
68 }
69 }
70
71 #[inline]
72 pub fn body(&self) -> &Bytes {
73 &self.body
74 }
75 #[inline]
76 pub fn trace_id(&self) -> [u8; 16] {
77 self.trace_id
78 }
79
80 /// This server hop's span ID (64-bit, unique per request).
81 #[inline]
82 pub fn span_id(&self) -> [u8; 8] {
83 self.span_id
84 }
85
86 /// The incoming caller's span ID, or `None` for root (origin) spans.
87 #[inline]
88 pub fn parent_span_id(&self) -> Option<[u8; 8]> {
89 if self.parent_span_id == [0u8; 8] {
90 None
91 } else {
92 Some(self.parent_span_id)
93 }
94 }
95
96 #[inline]
97 pub fn claims(&self) -> Option<&Claims> {
98 self.claims.as_deref()
99 }
100
101 /// The server-side session loaded for this request, if any.
102 ///
103 /// `Some` only when `SessionManager` is provided in the DI container and
104 /// the session-ID cookie was present, valid, and found in the store.
105 #[inline]
106 pub fn session(&self) -> Option<&Arc<Session>> {
107 self.session.as_ref()
108 }
109
110 /// The tenant resolved for this request, if any.
111 ///
112 /// `Some` only when a `TenantRegistry` is provided in the DI container and
113 /// the configured strategy (header / subdomain) matched a known tenant
114 /// (or a fallback tenant is configured). Enforce presence + JWT-claim
115 /// consistency with `web::tenant::TENANT.check(&ctx)?`.
116 #[inline]
117 pub fn tenant(&self) -> Option<&TenantConfig> {
118 self.tenant.as_deref()
119 }
120
121 #[inline]
122 pub fn header(&self, key: &str) -> Option<&str> {
123 self.headers.get(key).and_then(|v| v.to_str().ok())
124 }
125
126 #[inline]
127 pub fn param(&self, name: &str) -> Option<&str> {
128 self.params
129 .iter()
130 .find(|(k, _)| k == name)
131 .map(|(_, v)| v.as_str())
132 }
133
134 /// Resolve a singleton service. O(1), no locks, no allocation.
135 /// The borrow is tied to this context; for an owned handle that can be
136 /// moved into a spawned task, use [`inject_arc`](Self::inject_arc).
137 /// Panics if `T` was not provided into the DI container.
138 #[inline]
139 pub fn inject<T: Send + Sync + 'static>(&self) -> &T {
140 self.container.get::<T>()
141 }
142
143 /// Resolve a singleton as an owned `Arc<T>` (one atomic refcount bump,
144 /// no lock, no allocation). Backs `Inject<T>` construction at request
145 /// entry. Panics if `T` was not provided into the DI container.
146 #[inline]
147 pub fn inject_arc<T: Send + Sync + 'static>(&self) -> std::sync::Arc<T> {
148 self.container.get_arc::<T>()
149 }
150
151 /// Non-panicking variant of [`Self::inject`]. Returns `None` when `T` is not
152 /// in the DI container. Used by optional guards and middleware.
153 #[inline]
154 pub fn try_inject<T: Send + Sync + 'static>(&self) -> Option<&T> {
155 self.container.try_get::<T>()
156 }
157
158 /// Matched route pattern (e.g. `/users/:id`). Use this — not `path()` — as a
159 /// metrics/trace label to prevent high-cardinality from path parameters.
160 #[inline]
161 pub fn route(&self) -> &'static str {
162 self.route_pattern
163 }
164
165 /// Static route metadata for the matched route, if any.
166 #[inline]
167 pub fn route_spec(&self) -> Option<&'static RouteSpec> {
168 self.route_spec
169 }
170
171 /// Generate the W3C `traceparent` header value suitable for forwarding to
172 /// downstream HTTP services. Uses this hop's `span_id` as the `parent-id`
173 /// field so the downstream span correctly chains to this one.
174 ///
175 /// Format: `00-{trace_id_hex}-{span_id_hex}-01`
176 pub fn traceparent(&self) -> String {
177 format!(
178 "00-{}-{}-01",
179 hex_encode_16(&self.trace_id),
180 hex_encode_8(&self.span_id)
181 )
182 }
183
184 /// The trace ID as a lowercase hex string — for log/audit correlation.
185 /// Replaces app-level calls to `lean_telemetry::hex_encode(&ctx.trace_id())`.
186 pub fn trace_id_hex(&self) -> String {
187 hex_encode_16(&self.trace_id)
188 }
189
190 /// Attach decoded JWT claims to a freshly constructed context.
191 #[doc(hidden)]
192 #[inline]
193 #[doc(hidden)]
194 pub fn __with_claims(mut self, claims: Option<Arc<Claims>>) -> Self {
195 self.claims = claims;
196 self
197 }
198
199 /// Attach a loaded server-side session to a freshly constructed context.
200 #[doc(hidden)]
201 #[inline]
202 #[doc(hidden)]
203 pub fn __with_session(mut self, session: Option<Arc<Session>>) -> Self {
204 self.session = session;
205 self
206 }
207
208 /// Attach the resolved tenant to a freshly constructed context.
209 #[doc(hidden)]
210 #[inline]
211 #[doc(hidden)]
212 pub fn __with_tenant(mut self, tenant: Option<std::sync::Arc<TenantConfig>>) -> Self {
213 self.tenant = tenant;
214 self
215 }
216
217 /// Boundary constructor. Not part of the public API.
218 #[doc(hidden)]
219 #[allow(clippy::too_many_arguments)]
220 pub fn __new(
221 method: Method,
222 raw_path: SmolStr,
223 query: SmolStr,
224 params: SmallVec<[(SmolStr, SmolStr); 4]>,
225 headers: HeaderMap,
226 body: Bytes,
227 trace_id: [u8; 16],
228 span_id: [u8; 8],
229 parent_span_id: [u8; 8],
230 container: Arc<FrozenDiContainer>,
231 route_pattern: &'static str,
232 route_spec: Option<&'static RouteSpec>,
233 ) -> Self {
234 Self {
235 method,
236 raw_path,
237 query,
238 params,
239 headers,
240 body,
241 claims: None,
242 session: None,
243 tenant: None,
244 trace_id,
245 span_id,
246 parent_span_id,
247 container,
248 route_pattern,
249 route_spec,
250 extensions: axum::http::Extensions::new(),
251 }
252 }
253
254 /// Per-request typed storage (request-scoped "DI"). Values live for this
255 /// request only; the frozen process-wide container is untouched.
256 #[inline]
257 pub fn extensions(&self) -> &axum::http::Extensions {
258 &self.extensions
259 }
260
261 /// Mutable access to per-request typed storage. Typical flow: an
262 /// interceptor inserts a value, the handler reads it via
263 /// [`extensions`](Self::extensions).
264 #[inline]
265 pub fn extensions_mut(&mut self) -> &mut axum::http::Extensions {
266 &mut self.extensions
267 }
268}
269
270#[inline]
271pub(crate) fn hex_encode_16(b: &[u8; 16]) -> String {
272 b.iter().map(|x| format!("{x:02x}")).collect()
273}
274
275#[inline]
276pub(crate) fn hex_encode_8(b: &[u8; 8]) -> String {
277 b.iter().map(|x| format!("{x:02x}")).collect()
278}