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
408
409
410
411
412
413
mod storage;

use crate::{status, Executor, Request, Response};
use http::header::AsHeaderName;
use http::StatusCode;
use http::{Method, Uri, Version};
use std::any::Any;
use std::borrow::Cow;
use std::net::SocketAddr;
use std::ops::{Deref, DerefMut};
use std::sync::Arc;

pub use storage::Variable;
use storage::{Storage, Value};

/// A structure to share request, response and other data between middlewares.
///
/// ### Example
///
/// ```rust
/// use roa_core::{App, Context, Next, Result};
/// use log::info;
/// use async_std::fs::File;
///
/// let app = App::new().gate(gate).end(end);
/// async fn gate(ctx: &mut Context, next: Next<'_>) -> Result {
///     info!("{} {}", ctx.method(), ctx.uri());
///     next.await
/// }
///
/// async fn end(ctx: &mut Context) -> Result {
///     ctx.resp.write_reader(File::open("assets/welcome.html").await?);
///     Ok(())
/// }
/// ```
pub struct Context<S = ()> {
    /// The request, to read http method, uri, version, headers and body.
    pub req: Request,

    /// The response, to set http status, version, headers and body.
    pub resp: Response,

    /// The executor, to spawn futures or blocking works.
    pub exec: Executor,

    /// Socket addr of last client or proxy.
    pub remote_addr: SocketAddr,

    storage: Storage,
    state: S,
}

impl<S> Context<S> {
    /// Construct a context from a request, an app and a addr_stream.
    #[inline]
    pub(crate) fn new(
        request: Request,
        state: S,
        exec: Executor,
        remote_addr: SocketAddr,
    ) -> Self {
        Self {
            req: request,
            resp: Response::default(),
            state,
            exec,
            storage: Storage::default(),
            remote_addr,
        }
    }

    /// Clone URI.
    ///
    /// ### Example
    /// ```rust
    /// use roa_core::{App, Context, Result};
    ///
    /// let app = App::new().end(get);
    ///
    /// async fn get(ctx: &mut Context) -> Result {
    ///     assert_eq!("/", ctx.uri().to_string());
    ///     Ok(())
    /// }
    /// ```
    #[inline]
    pub fn uri(&self) -> &Uri {
        &self.req.uri
    }

    /// Clone request::method.
    ///
    /// ### Example
    /// ```rust
    /// use roa_core::{App, Context, Result};
    /// use roa_core::http::Method;
    ///
    /// let app = App::new().end(get);
    ///
    /// async fn get(ctx: &mut Context) -> Result {
    ///     assert_eq!(Method::GET, ctx.method());
    ///     Ok(())
    /// }
    /// ```
    #[inline]
    pub fn method(&self) -> &Method {
        &self.req.method
    }

    /// Search for a header value and try to get its string reference.
    ///
    /// ### Example
    /// ```rust
    /// use roa_core::{App, Context, Result};
    /// use roa_core::http::header::CONTENT_TYPE;
    ///
    /// let app = App::new().end(get);
    ///
    /// async fn get(ctx: &mut Context) -> Result {
    ///     assert_eq!(
    ///         Some("text/plain"),
    ///         ctx.get(CONTENT_TYPE),
    ///     );
    ///     Ok(())
    /// }
    /// ```
    #[inline]
    pub fn get(&self, name: impl AsHeaderName) -> Option<&str> {
        self.req
            .headers
            .get(name)
            .and_then(|value| value.to_str().ok())
    }

    /// Search for a header value and get its string reference.
    ///
    /// Otherwise return a 400 BAD REQUEST.
    ///
    /// ### Example
    /// ```rust
    /// use roa_core::{App, Context, Result};
    /// use roa_core::http::header::CONTENT_TYPE;
    ///
    /// let app = App::new().end(get);
    ///
    /// async fn get(ctx: &mut Context) -> Result {
    ///     assert_eq!(
    ///         "text/plain",
    ///         ctx.must_get(CONTENT_TYPE)?,
    ///     );
    ///     Ok(())
    /// }
    /// ```
    #[inline]
    pub fn must_get(&self, name: impl AsHeaderName) -> crate::Result<&str> {
        let value = self
            .req
            .headers
            .get(name)
            .ok_or_else(|| status!(StatusCode::BAD_REQUEST))?;
        value
            .to_str()
            .map_err(|err| status!(StatusCode::BAD_REQUEST, err))
    }
    /// Clone response::status.
    ///
    /// ### Example
    /// ```rust
    /// use roa_core::{App, Context, Result};
    /// use roa_core::http::StatusCode;
    ///
    /// let app = App::new().end(get);
    ///
    /// async fn get(ctx: &mut Context) -> Result {
    ///     assert_eq!(StatusCode::OK, ctx.status());
    ///     Ok(())
    /// }
    /// ```
    #[inline]
    pub fn status(&self) -> StatusCode {
        self.resp.status
    }

    /// Clone request::version.
    ///
    /// ### Example
    /// ```rust
    /// use roa_core::{App, Context, Result};
    /// use roa_core::http::Version;
    ///
    /// let app = App::new().end(get);
    ///
    /// async fn get(ctx: &mut Context) -> Result {
    ///     assert_eq!(Version::HTTP_11, ctx.version());
    ///     Ok(())
    /// }
    /// ```
    #[inline]
    pub fn version(&self) -> Version {
        self.req.version
    }

    /// Store key-value pair in specific scope.
    ///
    /// ### Example
    /// ```rust
    /// use roa_core::{App, Context, Result, Next};
    ///
    /// struct Scope;
    /// struct AnotherScope;
    ///
    /// async fn gate(ctx: &mut Context, next: Next<'_>) -> Result {
    ///     ctx.store_scoped(Scope, "id", "1".to_string());
    ///     next.await
    /// }
    ///
    /// async fn end(ctx: &mut Context) -> Result {
    ///     assert_eq!(1, ctx.load_scoped::<Scope, String>("id").unwrap().parse::<i32>()?);
    ///     assert!(ctx.load_scoped::<AnotherScope, String>("id").is_none());
    ///     Ok(())
    /// }
    ///
    /// let app = App::new().gate(gate).end(end);
    /// ```
    #[inline]
    pub fn store_scoped<SC, K, V>(
        &mut self,
        scope: SC,
        key: K,
        value: V,
    ) -> Option<Arc<V>>
    where
        SC: Any,
        K: Into<Cow<'static, str>>,
        V: Value,
    {
        self.storage.insert(scope, key, value)
    }

    /// Store key-value pair in public scope.
    ///
    /// ### Example
    /// ```rust
    /// use roa_core::{App, Context, Result, Next};
    ///
    /// async fn gate(ctx: &mut Context, next: Next<'_>) -> Result {
    ///     ctx.store("id", "1".to_string());
    ///     next.await
    /// }
    ///
    /// async fn end(ctx: &mut Context) -> Result {
    ///     assert_eq!(1, ctx.load::<String>("id").unwrap().parse::<i32>()?);
    ///     Ok(())
    /// }
    ///
    /// let app = App::new().gate(gate).end(end);
    /// ```
    #[inline]
    pub fn store<K, V>(&mut self, key: K, value: V) -> Option<Arc<V>>
    where
        K: Into<Cow<'static, str>>,
        V: Value,
    {
        self.store_scoped(PublicScope, key, value)
    }

    /// Search for value by key in specific scope.
    ///
    /// ### Example
    ///
    /// ```rust
    /// use roa_core::{App, Context, Result, Next};
    ///
    /// struct Scope;
    ///
    /// async fn gate(ctx: &mut Context, next: Next<'_>) -> Result {
    ///     ctx.store_scoped(Scope, "id", "1".to_owned());
    ///     next.await
    /// }
    ///
    /// async fn end(ctx: &mut Context) -> Result {
    ///     assert_eq!(1, ctx.load_scoped::<Scope, String>("id").unwrap().parse::<i32>()?);
    ///     Ok(())
    /// }
    ///
    /// let app = App::new().gate(gate).end(end);
    /// ```
    #[inline]
    pub fn load_scoped<'a, SC, V>(&self, key: &'a str) -> Option<Variable<'a, V>>
    where
        SC: Any,
        V: Value,
    {
        self.storage.get::<SC, V>(key)
    }

    /// Search for value by key in public scope.
    ///
    /// ### Example
    /// ```rust
    /// use roa_core::{App, Context, Result, Next};
    ///
    /// async fn gate(ctx: &mut Context, next: Next<'_>) -> Result {
    ///     ctx.store("id", "1".to_string());
    ///     next.await
    /// }
    ///
    /// async fn end(ctx: &mut Context) -> Result {
    ///     assert_eq!(1, ctx.load::<String>("id").unwrap().parse::<i32>()?);
    ///     Ok(())
    /// }
    ///
    /// let app = App::new().gate(gate).end(end);
    /// ```
    #[inline]
    pub fn load<'a, V>(&self, key: &'a str) -> Option<Variable<'a, V>>
    where
        V: Value,
    {
        self.load_scoped::<PublicScope, V>(key)
    }
}

/// Public storage scope.
struct PublicScope;

impl<S> Deref for Context<S> {
    type Target = S;
    #[inline]
    fn deref(&self) -> &Self::Target {
        &self.state
    }
}

impl<S> DerefMut for Context<S> {
    #[inline]
    fn deref_mut(&mut self) -> &mut Self::Target {
        &mut self.state
    }
}

impl<S: Clone> Clone for Context<S> {
    #[inline]
    fn clone(&self) -> Self {
        Self {
            req: Request::default(),
            resp: Response::new(),
            state: self.state.clone(),
            exec: self.exec.clone(),
            storage: self.storage.clone(),
            remote_addr: self.remote_addr,
        }
    }
}

#[cfg(all(test, feature = "runtime"))]
mod tests_with_runtime {
    use crate::{App, Context, Next, Request, Status};
    use http::{HeaderValue, StatusCode, Version};
    use std::error::Error;

    #[async_std::test]
    async fn status_and_version() -> Result<(), Box<dyn Error>> {
        async fn test(ctx: &mut Context) -> Result<(), Status> {
            assert_eq!(Version::HTTP_11, ctx.version());
            assert_eq!(StatusCode::OK, ctx.status());
            Ok(())
        }
        let service = App::new().end(test).http_service();
        service.serve(Request::default()).await;
        Ok(())
    }

    #[derive(Clone)]
    struct State {
        data: usize,
    }

    #[async_std::test]
    async fn state() -> Result<(), Box<dyn Error>> {
        async fn gate(ctx: &mut Context<State>, next: Next<'_>) -> Result<(), Status> {
            ctx.data = 1;
            next.await
        }

        async fn test(ctx: &mut Context<State>) -> Result<(), Status> {
            assert_eq!(1, ctx.data);
            Ok(())
        }
        let service = App::state(State { data: 1 })
            .gate(gate)
            .end(test)
            .http_service();
        service.serve(Request::default()).await;
        Ok(())
    }

    #[async_std::test]
    async fn must_get() -> Result<(), Box<dyn Error>> {
        use http::header::{CONTENT_TYPE, HOST};
        async fn test(ctx: &mut Context) -> Result<(), Status> {
            assert_eq!(Ok("github.com"), ctx.must_get(HOST));
            ctx.must_get(CONTENT_TYPE)?;
            unreachable!()
        }
        let service = App::new().end(test).http_service();
        let mut req = Request::default();
        req.headers
            .insert(HOST, HeaderValue::from_static("github.com"));
        let resp = service.serve(req).await;
        assert_eq!(StatusCode::BAD_REQUEST, resp.status);
        Ok(())
    }
}