Skip to main content

rskit_http/
extractors.rs

1use http::{Extensions, HeaderMap};
2
3/// Request identifier carried through HTTP request extensions.
4#[derive(Debug, Clone)]
5pub struct RequestId(pub String);
6
7impl RequestId {
8    /// Read a request id from headers or generate a new UUID.
9    #[must_use]
10    pub fn from_headers(headers: &HeaderMap) -> Self {
11        Self(
12            headers
13                .get("x-request-id")
14                .and_then(|value| value.to_str().ok())
15                .map(str::to_owned)
16                .unwrap_or_else(|| uuid::Uuid::new_v4().to_string()),
17        )
18    }
19}
20
21/// Correlation identifier carried through HTTP request extensions.
22#[derive(Debug, Clone)]
23pub struct CorrelationId(pub String);
24
25impl CorrelationId {
26    /// Read a correlation id from headers or generate a new UUID.
27    #[must_use]
28    pub fn from_headers(headers: &HeaderMap) -> Self {
29        Self(
30            headers
31                .get("x-correlation-id")
32                .and_then(|value| value.to_str().ok())
33                .map(str::to_owned)
34                .unwrap_or_else(|| uuid::Uuid::new_v4().to_string()),
35        )
36    }
37}
38
39/// Store a [`RequestId`] in request extensions.
40pub fn set_request_id(extensions: &mut Extensions, request_id: impl Into<String>) {
41    extensions.insert(RequestId(request_id.into()));
42}
43
44/// Retrieve a [`RequestId`] from request extensions.
45#[must_use]
46pub fn request_id_from_extensions(extensions: &Extensions) -> Option<&RequestId> {
47    extensions.get::<RequestId>()
48}
49
50/// Store a [`CorrelationId`] in request extensions.
51pub fn set_correlation_id(extensions: &mut Extensions, correlation_id: impl Into<String>) {
52    extensions.insert(CorrelationId(correlation_id.into()));
53}
54
55/// Retrieve a [`CorrelationId`] from request extensions.
56#[must_use]
57pub fn correlation_id_from_extensions(extensions: &Extensions) -> Option<&CorrelationId> {
58    extensions.get::<CorrelationId>()
59}