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
//! A few common `MakeRequestId` implementations for use with `tower-http`

#![warn(clippy::nursery)]
#![warn(clippy::pedantic)]
#![warn(clippy::cargo)]
#![warn(missing_docs)]
#![allow(clippy::needless_doctest_main)]

use std::sync::{
    atomic::{AtomicUsize, Ordering},
    Arc,
};

use hyper::Request;
use tower_http::request_id::{MakeRequestId, RequestId};

#[cfg(feature = "uuid")]
use uuid::Uuid;

#[cfg(feature = "ulid")]
use ulid::Ulid;

/// A [`MakeRequestId`] that generates a [`RequestId`] from a [`Uuid`].
///
/// [`MakeRequestId`]: ::tower_http::request_id::MakeRequestId
/// [`RequestId`]: ::tower_http::request_id::RequestId
/// [`Uuid`]: ::uuid::Uuid
#[derive(Clone, Copy, Debug, Default)]
#[cfg(feature = "uuid")]
pub struct MakeRequestUuid;

#[cfg(feature = "uuid")]
impl MakeRequestId for MakeRequestUuid {
    fn make_request_id<B>(
        &mut self,
        #[allow(unused_variables)] request: &Request<B>,
    ) -> Option<RequestId> {
        Some(RequestId::new(
            Uuid::new_v4()
                .to_string()
                .parse()
                .expect("uuid should only contain ascii characters"),
        ))
    }
}

/// A [`MakeRequestId`] that generates a [`RequestId`] from a [`Ulid`].
///
/// [`MakeRequestId`]: ::tower_http::request_id::MakeRequestId
/// [`RequestId`]: ::tower_http::request_id::RequestId
/// [`Ulid`]: ::ulid::Ulid
#[derive(Clone, Copy, Debug, Default)]
#[cfg(feature = "ulid")]
pub struct MakeRequestUlid;

#[cfg(feature = "ulid")]
impl MakeRequestId for MakeRequestUlid {
    fn make_request_id<B>(
        &mut self,
        #[allow(unused_variables)] request: &Request<B>,
    ) -> Option<RequestId> {
        Some(RequestId::new(
            Ulid::new()
                .to_string()
                .parse()
                .expect("ulid should only contain ascii characters"),
        ))
    }
}

/// A [`MakeRequestId`] that uses an atomic counter to generate [`RequestId`]s.
///
/// [`MakeRequestId`]: ::tower_http::request_id::MakeRequestId
/// [`RequestId`]: ::tower_http::request_id::RequestId
#[derive(Clone, Debug, Default)]
pub struct MakeRequestIdCounter {
    counter: Arc<AtomicUsize>,
}

impl MakeRequestIdCounter {
    /// Create a new `MakeRequestIdCounter`.
    #[must_use]
    pub fn new() -> Self {
        Self::default()
    }
}

impl MakeRequestId for MakeRequestIdCounter {
    fn make_request_id<B>(
        &mut self,
        #[allow(unused_variables)] request: &Request<B>,
    ) -> Option<RequestId> {
        Some(RequestId::new(
            self.counter
                .fetch_add(1, Ordering::Relaxed)
                .to_string()
                .parse()
                .expect("usize should only contain ascii characters"),
        ))
    }
}

#[cfg(test)]
mod tests {
    use hyper::Request;
    use tower_http::request_id::MakeRequestId;

    use super::*;

    #[test]
    fn make_request_id_counter() {
        let mut make_request_id = MakeRequestIdCounter::new();

        let next = make_request_id
            .make_request_id(&Request::new(()))
            .unwrap()
            .into_header_value();

        assert_eq!("0", next.to_str().unwrap());

        let next = make_request_id
            .make_request_id(&Request::new(()))
            .unwrap()
            .into_header_value();

        assert_eq!("1", next.to_str().unwrap());
    }

    #[test]
    #[cfg(feature = "uuid")]
    fn make_request_uuid() {
        let mut make_request_id = MakeRequestUuid;

        let next = make_request_id
            .make_request_id(&Request::new(()))
            .unwrap()
            .into_header_value();

        assert!(uuid::Uuid::try_parse_ascii(next.as_bytes()).is_ok());
    }

    #[test]
    #[cfg(feature = "ulid")]
    fn make_request_ulid() {
        let mut make_request_id = MakeRequestUlid;

        let next = make_request_id
            .make_request_id(&Request::new(()))
            .unwrap()
            .into_header_value();

        assert!(ulid::Ulid::from_string(next.to_str().unwrap()).is_ok());
    }
}