krab_core 0.6.0

Shared runtime for the Krab framework: config, HTTP, database, telemetry, resilience, signals, and protocol governance
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
use std::sync::atomic::Ordering;
use std::time::Instant;

use axum::body::Body;
use axum::extract::State;
use axum::http::{HeaderValue, Request};
use axum::middleware::Next;
use axum::response::Response;
use tracing::{debug, info};

use crate::http_protocol::{
    operation_label, protocol_label, protocol_metric_index, resolved_protocol,
    response_metric_slot, response_status_class_index, selection_source_label,
};
use crate::http_runtime::HasRuntimeState;

/// Longest inbound `x-request-id` accepted as-is.
const MAX_INBOUND_REQUEST_ID_LEN: usize = 128;

/// Whether an inbound request id is safe to propagate.
///
/// The value is echoed in the response, copied into every log line of the
/// request and into error envelopes, and forwarded downstream. An unbounded,
/// arbitrary-byte value let any client inflate every log line it caused, or
/// inject characters that confuse log parsers. Accepted ids are 1–128 bytes of
/// `[A-Za-z0-9._:-]`, which covers UUIDs, ULIDs and W3C trace ids; anything
/// else is replaced with a fresh id.
fn is_acceptable_request_id(value: &HeaderValue) -> bool {
    let bytes = value.as_bytes();
    !bytes.is_empty()
        && bytes.len() <= MAX_INBOUND_REQUEST_ID_LEN
        && bytes
            .iter()
            .all(|b| b.is_ascii_alphanumeric() || matches!(b, b'-' | b'_' | b'.' | b':'))
}

pub(crate) fn request_id_value_from_headers(
    headers: &axum::http::HeaderMap,
) -> (HeaderValue, &'static str) {
    match headers.get("x-request-id") {
        Some(existing) if is_acceptable_request_id(existing) => (existing.clone(), "inbound"),
        rejected => {
            let generated = uuid::Uuid::new_v4().to_string();
            let value = HeaderValue::from_str(&generated)
                .unwrap_or_else(|_| HeaderValue::from_static("request-id-invalid"));
            let strategy = if rejected.is_some() {
                "uuid_v4_replaced_invalid_inbound"
            } else {
                "uuid_v4"
            };
            (value, strategy)
        }
    }
}

#[cfg(test)]
mod request_id_tests {
    use super::request_id_value_from_headers;
    use axum::http::{HeaderMap, HeaderValue};

    fn with(value: &str) -> HeaderMap {
        let mut headers = HeaderMap::new();
        headers.insert("x-request-id", HeaderValue::from_str(value).unwrap());
        headers
    }

    #[test]
    fn well_formed_inbound_ids_are_kept() {
        for id in [
            "4bf92f3577b34da6a3ce929d0e0e4736",
            "01HZX3Y5Q1ABCDEF",
            "req-1.2:3_4",
        ] {
            let (value, strategy) = request_id_value_from_headers(&with(id));
            assert_eq!(value.to_str().unwrap(), id);
            assert_eq!(strategy, "inbound");
        }
    }

    #[test]
    fn oversized_or_unsafe_inbound_ids_are_replaced() {
        for id in [
            "x".repeat(129),
            "has space".to_string(),
            "a\"b".to_string(),
            "{json}".into(),
        ] {
            let (value, strategy) = request_id_value_from_headers(&with(&id));
            assert_ne!(value.to_str().unwrap(), id);
            assert_eq!(strategy, "uuid_v4_replaced_invalid_inbound");
        }
        let (_, strategy) = request_id_value_from_headers(&HeaderMap::new());
        assert_eq!(strategy, "uuid_v4");
    }
}

pub async fn request_id_middleware<S>(
    _state: State<S>,
    mut req: Request<Body>,
    next: Next,
) -> Response
where
    S: Clone + Send + Sync + 'static + HasRuntimeState,
{
    let (request_id_value, strategy) = request_id_value_from_headers(req.headers());
    req.headers_mut()
        .insert("x-request-id", request_id_value.clone());

    let mut response = next.run(req).await;

    response
        .headers_mut()
        .insert("x-request-id", request_id_value.clone());

    debug!(
        request_id = %request_id_value.to_str().unwrap_or("non-utf8"),
        strategy = %strategy,
        "request_id_attached"
    );

    response
}

pub async fn metrics_middleware<S>(
    State(state): State<S>,
    req: Request<Body>,
    next: Next,
) -> Response
where
    S: Clone + Send + Sync + 'static + HasRuntimeState,
{
    let runtime = state.runtime_state();
    // Protocol resolution now runs INSIDE the auth layer (it needs the
    // AuthContext for trusted tenant policy), so on the request path this
    // middleware sees no resolved protocol yet. The resolution middleware
    // mirrors the resolved `ProtocolKind` into the response extensions;
    // prefer that, falling back to the request extension for callers that
    // layer this middleware differently.
    let request_protocol = resolved_protocol(&req);

    runtime.request_count.fetch_add(1, Ordering::Relaxed);
    runtime.inflight_requests.fetch_add(1, Ordering::Relaxed);

    // Decrement in a drop guard, not after the await: when the client
    // disconnects mid-request hyper drops this future, and a plain
    // `fetch_sub` after `next.run` would never execute — the gauge (exported
    // to Prometheus) would drift upward permanently.
    struct InflightGuard(std::sync::Arc<std::sync::atomic::AtomicU64>);
    impl Drop for InflightGuard {
        fn drop(&mut self) {
            self.0.fetch_sub(1, Ordering::Relaxed);
        }
    }
    let _inflight = InflightGuard(runtime.inflight_requests.clone());

    let response = next.run(req).await;

    let protocol = response
        .extensions()
        .get::<crate::protocol::ProtocolKind>()
        .copied()
        .or(request_protocol);
    let protocol_index = protocol_metric_index(protocol);
    runtime.protocol_request_totals[protocol_index].fetch_add(1, Ordering::Relaxed);

    let code = response.status().as_u16();
    if let Some(class_index) = response_status_class_index(code) {
        match class_index {
            0 => {
                runtime.response_2xx_total.fetch_add(1, Ordering::Relaxed);
            }
            1 => {
                runtime.response_4xx_total.fetch_add(1, Ordering::Relaxed);
            }
            2 => {
                runtime.response_5xx_total.fetch_add(1, Ordering::Relaxed);
            }
            _ => {}
        }

        let slot = response_metric_slot(class_index, protocol_index);
        runtime.response_class_protocol_totals[slot].fetch_add(1, Ordering::Relaxed);
    }

    response
}

pub async fn tracing_middleware<S>(
    State(state): State<S>,
    req: Request<Body>,
    next: Next,
) -> Response
where
    S: Clone + Send + Sync + 'static + HasRuntimeState,
{
    let method = req.method().clone();
    let path = req.uri().path().to_string();
    let request_protocol = protocol_label(&req);
    let operation = operation_label(&method, &path);
    let selection_source = selection_source_label(&req, &path);
    let request_id = req
        .headers()
        .get("x-request-id")
        .and_then(|h| h.to_str().ok())
        .unwrap_or("unknown")
        .to_string();
    if request_id == "unknown" {
        debug!("tracing_missing_request_id_in_inbound_headers");
    }

    let start = Instant::now();
    let resp = next.run(req).await;
    // Protocol resolution runs inside the auth layer; the resolved protocol
    // reaches this outer middleware via the response extensions.
    let protocol = resp
        .extensions()
        .get::<crate::protocol::ProtocolKind>()
        .map(|p| p.as_str())
        .unwrap_or(request_protocol);
    let status = resp.status();
    let elapsed = start.elapsed();
    let elapsed_ms = elapsed.as_millis();

    let runtime = state.runtime_state();
    runtime.latency_sum_micros.fetch_add(
        u64::try_from(elapsed.as_micros()).unwrap_or(u64::MAX),
        Ordering::Relaxed,
    );
    let buckets = &runtime.latency_buckets;
    if elapsed_ms <= 10 {
        buckets[0].fetch_add(1, Ordering::Relaxed);
    } else if elapsed_ms <= 50 {
        buckets[1].fetch_add(1, Ordering::Relaxed);
    } else if elapsed_ms <= 100 {
        buckets[2].fetch_add(1, Ordering::Relaxed);
    } else if elapsed_ms <= 200 {
        buckets[3].fetch_add(1, Ordering::Relaxed);
    } else if elapsed_ms <= 500 {
        buckets[4].fetch_add(1, Ordering::Relaxed);
    } else if elapsed_ms <= 1000 {
        buckets[5].fetch_add(1, Ordering::Relaxed);
    } else if elapsed_ms <= 2000 {
        buckets[6].fetch_add(1, Ordering::Relaxed);
    } else {
        buckets[7].fetch_add(1, Ordering::Relaxed);
    }

    info!(
        event = "http_request_complete",
        http.method = %method,
        http.route = %path,
        http.status_code = %status.as_u16(),
        http.request_id = %request_id,
        krab.protocol = %protocol,
        krab.operation = %operation,
        krab.selection_source = %selection_source,
        duration_ms = elapsed_ms,
        "request_complete"
    );
    resp
}

/// Headers that must be forwarded on every outbound service-to-service call
/// to maintain request-id and trace correlation across the topology.
///
/// # Usage
///
/// ```rust
/// use krab_core::http::PropagationHeaders;
///
/// // Inside an Axum handler, extract the inbound headers:
/// let mut headers = axum::http::HeaderMap::new();
/// headers.insert("x-request-id", "req-123".parse().unwrap());
/// let prop = PropagationHeaders::from_request_headers(&headers);
///
/// assert_eq!(prop.request_id.as_deref(), Some("req-123"));
///
/// // Then inject them into every outbound request. `as_header_pairs` suits
/// // builder-style clients:
/// let client = reqwest::Client::new();
/// let mut builder = client.get("http://service_users:3002/api/v1/graphql");
/// for (name, value) in prop.as_header_pairs() {
///     builder = builder.header(name, value);
/// }
/// # let _ = builder;
///
/// // `inject_into_headers` suits anything holding a `HeaderMap` directly:
/// let mut outbound = axum::http::HeaderMap::new();
/// prop.inject_into_headers(&mut outbound);
/// assert_eq!(outbound.get("x-request-id").unwrap(), "req-123");
/// ```
#[derive(Debug, Clone, Default)]
pub struct PropagationHeaders {
    /// The inbound `x-request-id` value, if present and valid UTF-8.
    pub request_id: Option<String>,
    /// The inbound `x-trace-id` value, if present and valid UTF-8.
    pub trace_id: Option<String>,
}

impl PropagationHeaders {
    /// Header name carrying the request id: `x-request-id`.
    pub const REQUEST_ID_HEADER: &'static str = "x-request-id";
    /// Header name carrying the trace id: `x-trace-id`.
    pub const TRACE_ID_HEADER: &'static str = "x-trace-id";

    /// Captures the request and trace ids from inbound headers. Values are
    /// taken as-is. Behind [`crate::http::apply_common_http_layers`], the
    /// request-id middleware has already replaced a missing or unacceptable
    /// inbound `x-request-id` with a fresh UUID by the time a handler runs.
    pub fn from_request_headers(headers: &axum::http::HeaderMap) -> Self {
        Self {
            request_id: headers
                .get(Self::REQUEST_ID_HEADER)
                .and_then(|v| v.to_str().ok())
                .map(ToString::to_string),
            trace_id: headers
                .get(Self::TRACE_ID_HEADER)
                .and_then(|v| v.to_str().ok())
                .map(ToString::to_string),
        }
    }

    /// `(header name, value)` pairs for the ids that are present, for
    /// builder-style HTTP clients.
    pub fn as_header_pairs(&self) -> Vec<(&'static str, &str)> {
        let mut pairs = Vec::new();
        if let Some(id) = &self.request_id {
            pairs.push((Self::REQUEST_ID_HEADER, id.as_str()));
        }
        if let Some(tid) = &self.trace_id {
            pairs.push((Self::TRACE_ID_HEADER, tid.as_str()));
        }
        pairs
    }

    /// Inserts the ids that are present into `headers`, replacing existing
    /// values. An id that is not a valid header value is skipped silently.
    pub fn inject_into_headers(&self, headers: &mut axum::http::HeaderMap) {
        if let Some(id) = &self.request_id {
            if let Ok(v) = axum::http::HeaderValue::from_str(id) {
                headers.insert(
                    axum::http::HeaderName::from_static(Self::REQUEST_ID_HEADER),
                    v,
                );
            }
        }
        if let Some(tid) = &self.trace_id {
            if let Ok(v) = axum::http::HeaderValue::from_str(tid) {
                headers.insert(
                    axum::http::HeaderName::from_static(Self::TRACE_ID_HEADER),
                    v,
                );
            }
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn propagation_headers_round_trip() {
        let mut map = axum::http::HeaderMap::new();
        map.insert(
            axum::http::HeaderName::from_static("x-request-id"),
            axum::http::HeaderValue::from_static("req-abc"),
        );
        map.insert(
            axum::http::HeaderName::from_static("x-trace-id"),
            axum::http::HeaderValue::from_static("trace-xyz"),
        );

        let prop = PropagationHeaders::from_request_headers(&map);
        assert_eq!(prop.request_id.as_deref(), Some("req-abc"));
        assert_eq!(prop.trace_id.as_deref(), Some("trace-xyz"));

        let mut out = axum::http::HeaderMap::new();
        prop.inject_into_headers(&mut out);
        assert_eq!(
            out.get("x-request-id").and_then(|v| v.to_str().ok()),
            Some("req-abc")
        );
        assert_eq!(
            out.get("x-trace-id").and_then(|v| v.to_str().ok()),
            Some("trace-xyz")
        );
    }

    #[test]
    fn propagation_headers_missing_fields_produce_empty_pairs() {
        let map = axum::http::HeaderMap::new();
        let prop = PropagationHeaders::from_request_headers(&map);
        assert!(prop.request_id.is_none());
        assert!(prop.trace_id.is_none());
        assert!(prop.as_header_pairs().is_empty());
    }

    #[test]
    fn request_id_generation_preserves_inbound_header_when_present() {
        let mut headers = axum::http::HeaderMap::new();
        headers.insert(
            axum::http::HeaderName::from_static("x-request-id"),
            axum::http::HeaderValue::from_static("req-123"),
        );

        let (value, strategy) = request_id_value_from_headers(&headers);
        assert_eq!(strategy, "inbound");
        assert_eq!(value.to_str().ok(), Some("req-123"));
    }

    #[test]
    fn request_id_generation_creates_uuid_when_absent() {
        let headers = axum::http::HeaderMap::new();
        let (value, strategy) = request_id_value_from_headers(&headers);
        assert_eq!(strategy, "uuid_v4");
        assert!(value.to_str().ok().is_some());
    }
}