summaryrefslogtreecommitdiff
path: root/src/clock.rs
blob: 9ffef8238e693b68c3447ac9ca04734a0b5be260 (plain)
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
use axum::{
    extract::{Extension, FromRequestParts, Request},
    http::{request::Parts, StatusCode},
    middleware::Next,
    response::Response,
};
use chrono::Utc;

pub type DateTime = chrono::DateTime<chrono::Utc>;

// Extractor that provides the "current time" for a request. This time is
// calculated once per request, even if the extractor is used in multiple
// places. This requires the [middleware] function to be installed with
// [axum::middleware::from_fn] around the current route.
#[derive(Clone)]
pub struct RequestedAt(pub DateTime);

impl RequestedAt {
    fn now() -> Self {
        Self(Utc::now())
    }
}

#[async_trait::async_trait]
impl<S> FromRequestParts<S> for RequestedAt
where
    S: Send + Sync,
{
    type Rejection = <Extension<Self> as FromRequestParts<S>>::Rejection;

    async fn from_request_parts(parts: &mut Parts, state: &S) -> Result<Self, Self::Rejection> {
        // This is purely for ergonomics: it allows `RequestedAt` to be extracted
        // without having to wrap it in `Extension<>`. Callers _can_ still do that,
        // but they aren't forced to.
        let Extension(requested_at) = Extension::from_request_parts(parts, state).await?;

        Ok(requested_at)
    }
}

impl From<DateTime> for RequestedAt {
    fn from(timestamp: DateTime) -> Self {
        Self(timestamp)
    }
}

impl std::ops::Deref for RequestedAt {
    type Target = DateTime;

    fn deref(&self) -> &Self::Target {
        let Self(timestamp) = self;
        timestamp
    }
}

// Computes a canonical "requested at" time for each request it wraps. This
// time can be recovered using the [RequestedAt] extractor.
pub async fn middleware(mut req: Request, next: Next) -> Result<Response, StatusCode> {
    let now = RequestedAt::now();
    req.extensions_mut().insert(now);

    Ok(next.run(req).await)
}