actix-request-identifier 4.2.0

Middlerware for actix-web to associate an ID with each request.
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
#![deny(unused, missing_docs)]
//! This is an actix-web middleware to associate every request with a unique ID. This ID can be
//! used to track errors in an application.

use std::{
    fmt::{self, Display},
    pin::Pin,
    task::{Context, Poll},
};

use actix_web::{
    dev::{Payload, Service, ServiceRequest, ServiceResponse, Transform},
    error::ResponseError,
    http::header::{HeaderName, HeaderValue},
    Error as ActixError, FromRequest, HttpMessage, HttpRequest,
};
use futures::{
    future::{ok, ready, Ready},
    Future,
};
use uuid::Uuid;

/// The default header used for the request ID.
pub const DEFAULT_HEADER: &str = "x-request-id";

/// Possible error types for the middleware.
#[derive(Debug, Clone)]
pub enum Error {
    /// There is no ID associated with this request.
    NoAssociatedId,
}

/// Configuration setting to decide weather the request id from the incoming request header should
/// be used, if present or if a new one should be generated in any case.
#[derive(Clone, Copy, PartialEq, Eq, Default)]
pub enum IdReuse {
    /// Reuse the incoming request id.
    UseIncoming,
    /// Ignore the incoming request id and generate a random one, even if the request supplied an
    /// id.
    #[default]
    IgnoreIncoming,
}

/// ID wrapper for requests.
pub struct RequestIdMiddleware<S> {
    service: S,
    header_name: HeaderName,
    id_generator: Generator,
    use_incoming_id: IdReuse,
}

type Generator = fn() -> HeaderValue;

/// A middleware for generating per-request unique IDs
pub struct RequestIdentifier {
    header_name: &'static str,
    id_generator: Generator,
    use_incoming_id: IdReuse,
}

/// Request ID that can be extracted in handlers.
#[derive(Clone)]
pub struct RequestId(HeaderValue);

impl Display for RequestId {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}", self.as_str())
    }
}

impl ResponseError for Error {}

impl fmt::Display for Error {
    fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
        use Error::NoAssociatedId;
        match self {
            NoAssociatedId => write!(fmt, "NoAssociatedId"),
        }
    }
}

impl RequestId {
    /// Get the value of the response header for this request id.
    pub const fn header_value(&self) -> &HeaderValue {
        &self.0
    }

    /// Get a string representation of this ID
    ///
    /// # Panics
    ///
    /// If the header value contains non-ASCII characters
    pub fn as_str(&self) -> &str {
        self.0.to_str().expect("Non-ASCII IDs are not supported")
    }
}

impl RequestIdentifier {
    /// Create a default middleware using [`DEFAULT_HEADER`](./constant.DEFAULT_HEADER.html) as the header name and
    /// UUID v4 for ID generation.
    #[must_use]
    #[cfg(feature = "uuid-generator")]
    pub fn with_uuid() -> Self {
        Self::default()
    }

    /// Create a default middleware using [`DEFAULT_HEADER`](./constant.DEFAULT_HEADER.html) as the header name and
    /// UUID v7 for ID generation.
    #[must_use]
    #[cfg(feature = "uuid-v7-generator")]
    pub fn with_uuid_v7() -> Self {
        Self::with_generator(uuid_v7_generator)
    }

    /// Create a middleware using a custom header name and UUID v4 for ID generation.
    #[must_use]
    #[cfg(feature = "uuid-generator")]
    pub fn with_header(header_name: &'static str) -> Self {
        Self {
            header_name,
            ..Default::default()
        }
    }

    /// Change the header name for this middleware.
    #[must_use]
    pub const fn header(self, header_name: &'static str) -> Self {
        Self {
            header_name,
            ..self
        }
    }

    /// Create a middleware using [`DEFAULT_HEADER`](./constant.DEFAULT_HEADER.html) as the header
    /// name and IDs as generated by `id_generator`. `id_generator` should return a unique ID
    /// (ASCII only), each time it is invoked.
    #[must_use]
    pub fn with_generator(id_generator: Generator) -> Self {
        Self {
            id_generator,
            header_name: DEFAULT_HEADER,
            use_incoming_id: IdReuse::default(),
        }
    }

    /// Change the ID generator for this middleware.
    #[must_use]
    pub fn generator(self, id_generator: Generator) -> Self {
        Self {
            id_generator,
            ..self
        }
    }

    /// Change the behavior for incoming request id headers. When this is set to
    /// [`IdReuse::UseIncoming`](./enum.IdReuse.html#variant.UseIncoming) (the default), each request is checked if it
    /// contains a header by the specified name and if it exists, the id from that header is used, otherwise a random id
    /// is generated. When this is set to [`IdReuse::IgnoreIncoming`](./enum.IdReuse.html#variant.IgnoreIncoming), the
    /// id from the request header is ignored.
    #[must_use]
    pub fn use_incoming_id(self, use_incoming_id: IdReuse) -> Self {
        Self {
            use_incoming_id,
            ..self
        }
    }
}

#[cfg(feature = "uuid-generator")]
impl Default for RequestIdentifier {
    fn default() -> Self {
        Self {
            header_name: DEFAULT_HEADER,
            id_generator: default_generator,
            use_incoming_id: IdReuse::default(),
        }
    }
}

/// Default UUID v4 based ID generator.
#[cfg(feature = "uuid-generator")]
fn default_generator() -> HeaderValue {
    let uuid = Uuid::new_v4();
    HeaderValue::from_str(&uuid.to_string())
        // This unwrap can never fail since UUID v4 generated IDs are ASCII-only
        .unwrap()
}

#[cfg(feature = "uuid-v7-generator")]
fn uuid_v7_generator() -> HeaderValue {
    let uuid = Uuid::now_v7();
    HeaderValue::from_str(&uuid.to_string())
        // This unwrap can never fail since UUID v7 generated IDs are ASCII-only
        .unwrap()
}

impl<S, B> Transform<S, ServiceRequest> for RequestIdentifier
where
    S: Service<ServiceRequest, Response = ServiceResponse<B>, Error = ActixError>,
    S::Future: 'static,
    B: 'static,
{
    type Response = S::Response;
    type Error = S::Error;
    type Transform = RequestIdMiddleware<S>;
    type InitError = ();
    type Future = Ready<Result<Self::Transform, Self::InitError>>;

    fn new_transform(&self, service: S) -> Self::Future {
        // associate with the request
        ok(RequestIdMiddleware {
            service,
            header_name: HeaderName::from_static(self.header_name),
            id_generator: self.id_generator,
            use_incoming_id: self.use_incoming_id,
        })
    }
}

#[allow(clippy::type_complexity)]
impl<S, B> Service<ServiceRequest> for RequestIdMiddleware<S>
where
    S: Service<ServiceRequest, Response = ServiceResponse<B>, Error = ActixError>,
    S::Future: 'static,
    B: 'static,
{
    type Response = S::Response;
    type Error = S::Error;
    type Future = Pin<Box<dyn Future<Output = Result<Self::Response, Self::Error>>>>;

    fn poll_ready(&self, ctx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
        self.service.poll_ready(ctx)
    }

    fn call(&self, request: ServiceRequest) -> Self::Future {
        let header_name = self.header_name.clone();
        let header_value = match self.use_incoming_id {
            IdReuse::UseIncoming => request
                .headers()
                .get(&header_name)
                .map_or_else(self.id_generator, Clone::clone),
            IdReuse::IgnoreIncoming => (self.id_generator)(),
        };

        // make the id available as an extractor in route handlers
        let request_id = RequestId(header_value.clone());
        request.extensions_mut().insert(request_id);

        let fut = self.service.call(request);
        Box::pin(async move {
            let mut response = fut.await?;

            response.headers_mut().insert(header_name, header_value);

            Ok(response)
        })
    }
}

impl FromRequest for RequestId {
    type Error = Error;
    type Future = Ready<Result<Self, Self::Error>>;

    fn from_request(req: &HttpRequest, _: &mut Payload) -> Self::Future {
        ready(
            req.extensions()
                .get::<RequestId>()
                .cloned()
                .ok_or(Error::NoAssociatedId),
        )
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use actix_web::{test, web, App};
    use bytes::Bytes;

    #[allow(clippy::unused_async)]
    async fn handler(id: RequestId) -> String {
        id.as_str().to_string()
    }

    // Using a macro to reduce code duplication when initializing the test service.
    // The return type of `test::init_service` is to complicated to create a normal function.
    macro_rules! service {
        ($middleware:expr) => {
            test::init_service(
                App::new()
                    .wrap($middleware)
                    .route("/", web::get().to(handler)),
            )
            .await
        };
    }

    async fn test_get(middleware: RequestIdentifier) -> ServiceResponse {
        let service = service!(middleware);
        test::call_service(&service, test::TestRequest::get().uri("/").to_request()).await
    }

    #[actix_web::test]
    async fn default_identifier() {
        let resp = test_get(RequestIdentifier::with_uuid()).await;
        let uid = resp
            .headers()
            .get(HeaderName::from_static(DEFAULT_HEADER))
            .map(|v| v.to_str().unwrap().to_string())
            .unwrap();
        let body: Bytes = test::read_body(resp).await;
        let body = String::from_utf8_lossy(&body);
        assert_eq!(uid, body);
    }

    #[cfg(feature = "uuid-v7-generator")]
    #[actix_web::test]
    async fn uuid_v7() {
        let resp = test_get(RequestIdentifier::with_uuid_v7()).await;
        let uid = resp
            .headers()
            .get(HeaderName::from_static(DEFAULT_HEADER))
            .map(|v| v.to_str().unwrap().to_string())
            .unwrap();
        let body: Bytes = test::read_body(resp).await;
        let body = String::from_utf8_lossy(&body);
        assert_eq!(uid, body);
    }

    #[actix_web::test]
    async fn deterministic_identifier() {
        let resp = test_get(RequestIdentifier::with_generator(|| {
            HeaderValue::from_static("look ma, i'm an id")
        }))
        .await;
        let uid = resp
            .headers()
            .get(HeaderName::from_static(DEFAULT_HEADER))
            .map(|v| v.to_str().unwrap().to_string())
            .unwrap();
        let body: Bytes = test::read_body(resp).await;
        let body = String::from_utf8_lossy(&body);
        assert_eq!(uid, body);
    }

    #[actix_web::test]
    async fn custom_header() {
        let resp = test_get(RequestIdentifier::with_header("custom-header")).await;
        assert!(resp
            .headers()
            .get(HeaderName::from_static(DEFAULT_HEADER))
            .is_none());
        let uid = resp
            .headers()
            .get(HeaderName::from_static("custom-header"))
            .map(|v| v.to_str().unwrap().to_string())
            .unwrap();
        let body: Bytes = test::read_body(resp).await;
        let body = String::from_utf8_lossy(&body);
        assert_eq!(uid, body);
    }

    #[actix_web::test]
    async fn existing_request_id() {
        let uuid4 = Uuid::new_v4().to_string();
        let service =
            service!(RequestIdentifier::with_uuid().use_incoming_id(IdReuse::UseIncoming));
        let req = test::TestRequest::get()
            .insert_header((DEFAULT_HEADER, uuid4.as_str()))
            .uri("/")
            .to_request();
        let resp = test::call_service(&service, req).await;
        let uid = resp
            .headers()
            .get(HeaderName::from_static(DEFAULT_HEADER))
            .map(|v| v.to_str().unwrap().to_string())
            .unwrap();
        assert_eq!(uid, uuid4);
        let body: Bytes = test::read_body(resp).await;
        let body = String::from_utf8_lossy(&body);
        assert_eq!(body, uuid4);
    }

    #[actix_web::test]
    async fn ignore_existing_request_id() {
        let uuid4 = Uuid::new_v4().to_string();
        let service = service!(RequestIdentifier::with_uuid()
            // use deterministic generator so we can check, if the supplied id is
            // ignored
            .generator(|| HeaderValue::from_static("0")));
        let req = test::TestRequest::get()
            .insert_header((DEFAULT_HEADER, uuid4.as_str()))
            .uri("/")
            .to_request();
        let resp = test::call_service(&service, req).await;
        let uid = resp
            .headers()
            .get(HeaderName::from_static(DEFAULT_HEADER))
            .map(|v| v.to_str().unwrap().to_string())
            .unwrap();
        assert_eq!(uid, "0");
        let body: Bytes = test::read_body(resp).await;
        let body = String::from_utf8_lossy(&body);
        assert_eq!(body, "0");
    }
}