summaryrefslogtreecommitdiff
path: root/src/utils.rs
blob: 70c8c11b0fd3c86accbc511f908d0d43bcf1e69a (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
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
use std::convert::Infallible;

use futures::Future;
use rocket::{
    fairing::{self, Fairing, Info, Kind},
    http::Status,
    request::{FromRequest, Outcome},
    tokio::{
        self,
        sync::broadcast::{channel, Sender},
        task::JoinHandle,
    },
    Request, Response, Sentinel,
};

// does the same as try_outcome!(...).map_forward(|_| data),
// but without moving data in non-failure cases.
macro_rules! try_outcome_data {
    ($data:expr, $e:expr) => {
        match $e {
            ::rocket::outcome::Outcome::Success(val) => val,
            ::rocket::outcome::Outcome::Failure(e) => {
                return ::rocket::outcome::Outcome::Failure(::std::convert::From::from(e))
            },
            ::rocket::outcome::Outcome::Forward(()) => {
                return ::rocket::outcome::Outcome::Forward($data)
            },
        }
    };
}

pub fn spawn_logged<F>(context: &'static str, future: F) -> JoinHandle<()>
where
    F: Future<Output = anyhow::Result<()>> + Send + 'static,
{
    tokio::spawn(async move {
        if let Err(e) = future.await {
            warn!("{context}: {e:?}");
        }
    })
}

pub struct DeferredActions;
struct HasDeferredActions;

pub struct DeferAction(Sender<()>);

#[async_trait]
impl Fairing for DeferredActions {
    fn info(&self) -> Info {
        Info { name: "deferred actions", kind: Kind::Ignite | Kind::Response }
    }

    async fn on_ignite(&self, rocket: rocket::Rocket<rocket::Build>) -> fairing::Result {
        Ok(rocket.manage(HasDeferredActions))
    }

    async fn on_response<'r>(&self, req: &'r Request<'_>, res: &mut Response<'r>) {
        if res.status() == Status::Ok {
            if let Some(DeferAction(tx)) = req.local_cache(|| None) {
                // could have no receivers, that's not an error here
                tx.send(()).ok();
            }
        }
    }
}

impl<'r> Sentinel for &'r DeferAction {
    fn abort(rocket: &rocket::Rocket<rocket::Ignite>) -> bool {
        rocket.state::<HasDeferredActions>().is_none()
    }
}

#[async_trait]
impl<'r> FromRequest<'r> for &'r DeferAction {
    type Error = Infallible;

    async fn from_request(req: &'r Request<'_>) -> Outcome<Self, Self::Error> {
        Outcome::Success(
            req.local_cache(|| {
                let (tx, _) = channel(1);
                Some(DeferAction(tx))
            })
            .as_ref()
            .unwrap(),
        )
    }
}

impl DeferAction {
    pub fn spawn_after_success<F>(&self, context: &'static str, future: F)
    where
        F: Future<Output = anyhow::Result<()>> + Send + 'static,
    {
        let mut r = self.0.subscribe();
        spawn_logged(context, async move {
            match r.recv().await {
                Ok(_) => {
                    // the request finished with success, now wait for it to be dropped
                    // to ensure that all other fairings have run to completion.
                    r.recv().await.ok();
                    future.await
                },
                Err(_) => Ok(()),
            }
        });
    }
}