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
#![warn(clippy::nursery)]
#![warn(clippy::pedantic)]
#![warn(clippy::cargo)]
#![warn(missing_docs)]
#![allow(clippy::needless_doctest_main)]
use std::sync::{
atomic::{AtomicUsize, Ordering},
Arc,
};
macro_rules! make_request_id {
{
$([$feature:literal])?
$Type:ident;
|$($this:ident)?| $create:expr
} => {
$(#[cfg(feature = $feature)])*
impl ::tower_http::request_id::MakeRequestId for $Type {
fn make_request_id<B>(
&mut self,
#[allow(unused_variables)] request: &::hyper::Request<B>,
) -> ::std::option::Option<::tower_http::request_id::RequestId> {
$(let $this = self;)*
::std::option::Option::Some(::tower_http::request_id::RequestId::new(
::std::str::FromStr::from_str(&::std::string::ToString::to_string(&$create))
.expect("request id should only contain ascii characters"),
))
}
}
};
}
#[derive(Clone, Copy, Debug, Default)]
#[cfg(feature = "uuid")]
pub struct MakeRequestUuid;
make_request_id! {
["uuid"]
MakeRequestUuid;
| | uuid::Uuid::new_v4()
}
#[derive(Clone, Copy, Debug, Default)]
#[cfg(feature = "ulid")]
pub struct MakeRequestUlid;
make_request_id! {
["ulid"]
MakeRequestUlid;
| | ulid::Ulid::new()
}
#[derive(Clone, Debug, Default)]
pub struct MakeRequestIdCounter {
counter: Arc<AtomicUsize>,
}
impl MakeRequestIdCounter {
#[must_use]
pub fn new() -> Self {
Self::default()
}
}
make_request_id!(
MakeRequestIdCounter;
|this| this.counter.fetch_add(1, Ordering::SeqCst)
);
#[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());
}
}