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
use crate::{request::Request, response::Response, router::Router};

#[cfg(feature = "operation")]
pub static OPERATION_ID_HEADER: &str = "Operation-Id";

/// State of the Http context. It represent whether the context is used
/// `Before(..)` or `After(..)` calling the handler responsible of generating a
/// responder. Empty will be the state of a context when the request is being
/// processed by the handler, or when its original state has been moved by using
/// take & take unchecked methods
pub enum State {
    Before(Box<Request>),
    After(Box<Response>),
    Empty,
}

impl Default for State {
    fn default() -> Self {
        State::Empty
    }
}

impl State {
    /// Take the current context leaving `State::Empty` behind
    pub fn take(&mut self) -> Self {
        std::mem::take(self)
    }

    /// Take the current request leaving `State::Empty` behind
    /// Returns `Some(Request)` if the state was `Before` or `None` if it was
    /// something else
    pub fn take_request(&mut self) -> Option<Request> {
        match std::mem::take(self) {
            State::Before(r) => Some(*r),
            _ => None,
        }
    }

    /// Take the current request leaving `State::Empty` behind
    ///
    /// # Panics
    /// Panics if the state is not `Before`
    pub fn take_request_unchecked(&mut self) -> Request {
        match std::mem::take(self) {
            State::Before(r) => *r,
            _ => panic!("State::take_request_unchecked should be called only before the handler & when it is ensured that the request wasn't moved"),
        }
    }

    /// Take the current response leaving `State::Empty` behind
    /// Returns `Some(Response)` if the state was `After` or `None` if it was
    /// something else
    pub fn take_response(&mut self) -> Option<Response> {
        match std::mem::take(self) {
            State::After(r) => Some(*r),
            _ => None,
        }
    }

    /// Take the current response leaving `State::Empty` behind
    ///
    /// # Panics
    /// Panics if the state is not `After`
    pub fn take_response_unchecked(&mut self) -> Response {
        match std::mem::take(self) {
            State::After(r) => *r,
            _ => panic!("State::take_response_unchecked should be called only after the handler & when it is ensured that the response wasn't moved"),
        }
    }

    /// Returns `Some` of the current request if state if `Before`
    pub fn request(&self) -> Option<&Request> {
        match self {
            State::Before(r) => Some(r),
            _ => None,
        }
    }

    /// Returns `Some` of the current request as a mutable ref if state if
    /// `Before`
    pub fn request_mut(&mut self) -> Option<&Request> {
        match self {
            State::Before(r) => Some(r),
            _ => None,
        }
    }

    /// Returns the current request
    ///
    /// # Panics
    /// Panics if state is not `Before`
    pub fn request_unchecked(&self) -> &Request {
        match self {
            State::Before(r) => r,
            _ => panic!("State::request_unchecked should be called only before the handler & when it is ensured that the request wasn't moved"),
        }
    }

    /// Returns the current request as a mutable ref
    ///
    /// # Panics
    /// panics if state is not `Before`
    pub fn request_unchecked_mut(&mut self) -> &mut Request {
        match self {
            State::Before(r) => r,
            _ => panic!("State::request_unchecked_mut should be called only before the handler & when it is ensured that the request wasn't moved"),
        }
    }

    /// Returns `Some` of the current response if state if `After`
    pub fn response(&self) -> Option<&Response> {
        match self {
            State::After(r) => Some(r),
            _ => None,
        }
    }

    /// Returns `Some` of the current response as a mutable ref if state if
    /// `After`
    pub fn response_mut(&mut self) -> Option<&mut Response> {
        match self {
            State::After(r) => Some(r),
            _ => None,
        }
    }

    /// Returns the current response
    ///
    /// # Panics
    /// Panics if state is not `After`
    pub fn response_unchecked(&self) -> &Response {
        match self {
            State::After(r) => r,
            _ => panic!("State::response_unchecked should be called only before the handler & when it is ensured that the request wasn't moved"),
        }
    }

    /// Returns the current response as a mutable ref
    ///
    /// # Panics
    /// Panics if state is not `After`
    pub fn response_unchecked_mut(&mut self) -> &mut Response {
        match self {
            State::After(r) => r,
            _ => panic!("State::response_unchecked_mut should be called only before the handler & when it is ensured that the request wasn't moved"),
        }
    }
}

/// Context representing the relationship between a request and a response
/// This structure only appears inside Middleware since the act before and after
/// the request
///
/// There is no guaranty the the request nor the response will be set at any
/// given time, since they could be moved out by a badly implemented middleware
pub struct HttpContext {
    /// The incoming request `Before` it is handled by the router
    /// OR
    /// The outgoing response `After` the request was handled by the router
    pub state: State,
    #[cfg(feature = "operation")]
    /// Unique Identifier of the current request->response chain
    pub operation_id: crate::http_context::operation::OperationId,
    pub(crate) router: Option<Router>,
}

impl HttpContext {
    pub(crate) fn new(request: Request, router: Router) -> Self {
        #[cfg(not(feature = "operation"))]
        {
            let state = State::Before(Box::new(request));
            let router = Some(router);
            HttpContext { state, router }
        }

        #[cfg(feature = "operation")]
        {
            use std::str::FromStr;
            let mut request = request;
            let operation_id = request
                .headers()
                .get(OPERATION_ID_HEADER)
                .and_then(|h| h.to_str().ok())
                .and_then(|op_id_str| operation::OperationId::from_str(op_id_str).ok())
                .unwrap_or_else(operation::OperationId::new);
            *request.operation_id_mut() = operation_id;
            let state = State::Before(Box::new(request));
            let router = Some(router);
            HttpContext { state, router, operation_id }
        }
    }

    /// Explicitly set the inner state to `Before` with the given response
    pub fn before(&mut self, request: Request) {
        self.state = State::Before(Box::new(request))
    }

    /// Explicitly set the inner state to `After` with the given response
    pub fn after(&mut self, response: Response) {
        self.state = State::After(Box::new(response))
    }
}

#[cfg(feature = "operation")]
pub mod operation {
    use serde::{de::Visitor, Deserialize, Deserializer, Serialize, Serializer};
    use std::{
        fmt::{Debug, Display, Formatter},
        str::FromStr,
    };
    use uuid::Uuid;

    /// Represent a single operation from a incoming request until a response is
    /// produced
    #[derive(Clone, Copy, Eq, Hash, Ord, PartialEq, PartialOrd, Default)]
    pub struct OperationId(Uuid);

    impl OperationId {
        pub fn new() -> OperationId {
            OperationId(Uuid::new_v4())
        }

        pub fn to_u128(&self) -> u128 {
            self.0.as_u128()
        }
    }

    impl Display for OperationId {
        fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
            std::fmt::Display::fmt(&self.0.to_hyphenated_ref(), f)
        }
    }

    impl Debug for OperationId {
        fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
            std::fmt::Display::fmt(&self.0.to_hyphenated_ref(), f)
        }
    }

    impl FromStr for OperationId {
        type Err = uuid::Error;

        fn from_str(s: &str) -> Result<Self, Self::Err> {
            Uuid::parse_str(s).map(OperationId)
        }
    }

    struct OperationIdVisitor;

    impl<'de> Visitor<'de> for OperationIdVisitor {
        type Value = OperationId;

        fn expecting(&self, formatter: &mut Formatter) -> std::fmt::Result {
            formatter.write_str("Invalid operation id")
        }

        fn visit_str<E>(self, v: &str) -> Result<Self::Value, E>
        where
            E: serde::de::Error,
        {
            v.parse::<OperationId>().map_err(serde::de::Error::custom)
        }

        fn visit_string<E>(self, v: String) -> Result<Self::Value, E>
        where
            E: serde::de::Error,
        {
            v.parse::<OperationId>().map_err(serde::de::Error::custom)
        }
    }

    impl<'de> Deserialize<'de> for OperationId {
        fn deserialize<D>(deserializer: D) -> Result<Self, <D as Deserializer<'de>>::Error>
        where
            D: Deserializer<'de>,
        {
            deserializer.deserialize_str(OperationIdVisitor)
        }
    }

    impl Serialize for OperationId {
        fn serialize<S>(&self, serializer: S) -> Result<<S as Serializer>::Ok, <S as Serializer>::Error>
        where
            S: Serializer,
        {
            serializer.serialize_str(self.to_string().as_str())
        }
    }
}