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
#![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,
    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,
}

/// ID wrapper for requests.
pub struct RequestIdMiddleware<S> {
    service: S,
    header_name: HeaderName,
    id: RequestId,
}

type Generator = fn() -> HeaderValue;

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

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

impl ResponseError for Error {}

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

impl RequestId {
    fn header_value(&self) -> &HeaderValue {
        &self.0
    }

    /// Get a string representation of this ID
    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.
    pub fn with_uuid() -> Self {
        Default::default()
    }

    /// Create a middleware using a custom header name and UUID v4 for ID generation.
    pub fn with_header(header_name: &'static str) -> Self {
        Self {
            header_name,
            id_generator: default_generator,
        }
    }

    /// Change the header name for this middleware.
    pub 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.
    pub fn with_generator(id_generator: Generator) -> Self {
        Self {
            header_name: DEFAULT_HEADER,
            id_generator,
        }
    }

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

impl Default for RequestIdentifier {
    fn default() -> Self {
        Self {
            header_name: DEFAULT_HEADER,
            id_generator: default_generator,
        }
    }
}

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

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

    fn new_transform(&self, service: S) -> Self::Future {
        // generate a new ID
        let value = (self.id_generator)();

        // associate with the request
        ok(RequestIdMiddleware {
            service,
            header_name: HeaderName::from_static(self.header_name),
            id: RequestId(value),
        })
    }
}

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

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

    fn call(&mut self, req: ServiceRequest) -> Self::Future {
        req.extensions_mut().insert(self.id.clone());
        let fut = self.service.call(req);
        // TODO: clone needed?
        let header_name = self.header_name.clone();
        let header_value = self.id.header_value().clone();

        Box::pin(async move {
            let mut res = fut.await?;

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

            Ok(res)
        })
    }
}

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

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

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

    async fn handler(id: RequestId) -> String {
        id.as_str().to_string()
    }

    async fn test_get(middleware: RequestIdentifier) -> ServiceResponse {
        let mut service = test::init_service(
            App::new()
                .wrap(middleware)
                .route("/", web::get().to(handler)),
        )
        .await;
        test::call_service(&mut service, test::TestRequest::get().uri("/").to_request()).await
    }

    #[actix_rt::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.bytes());
        assert_eq!(uid, body);
    }

    #[actix_rt::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.bytes());
        assert_eq!(uid, body);
    }

    #[actix_rt::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.bytes());
        assert_eq!(uid, body);
    }
}