Skip to main content

tablo_core/
settle.rs

1//! The work a panel runs after its response, such as sending auth mail, and [`settled`], which
2//! waits for it.
3
4use std::{
5    future::Future,
6    sync::{
7        Arc,
8        atomic::{AtomicUsize, Ordering},
9    },
10};
11
12use tokio::sync::Notify;
13use topcoat::{
14    context::{Cx, try_context},
15    router::Router,
16};
17
18/// Waits until the work the router's panels run after their responses has finished: the auth
19/// mail every request so far left behind is sent or handed to its delivery, or its failure
20/// logged.
21///
22/// A panel sends its auth mail once the response has left, so that how long a request takes
23/// tells no one whether an account exists. That work runs beside the server, which stops
24/// waiting for it once its last response is sent. Await this after `topcoat::serve_until` or
25/// `topcoat::start` returns, so a shutdown sends the mail already promised:
26///
27/// ```rust,no_run
28/// # async fn run(router: topcoat::router::Router, serving: impl Future<Output = std::io::Result<()>>) -> std::io::Result<()> {
29/// use std::time::Duration;
30///
31/// // `serving` is `topcoat::serve_until(listener, router.clone(), stop)`.
32/// serving.await?;
33/// if tokio::time::timeout(Duration::from_secs(30), tablo_core::settled(&router))
34///     .await
35///     .is_err()
36/// {
37///     tracing::warn!("stopping with auth mail still unsent");
38/// }
39/// # Ok(())
40/// # }
41/// ```
42///
43/// `tablo::testing::TestClient` awaits it after every request, so a test reads the mail a
44/// request sent as soon as the request returns. A router that mounts no panel has no
45/// such work, and this returns at once.
46pub async fn settled(router: &Router) {
47    if let Some(after) = router.context().get::<AfterResponse>() {
48        after.settled().await;
49    }
50}
51
52/// The router's work in flight after a response, shared by every panel it mounts. Cloning it
53/// is cheap.
54#[derive(Clone, Default)]
55pub(crate) struct AfterResponse(Arc<Running>);
56
57#[derive(Default)]
58struct Running {
59    count: AtomicUsize,
60    idle: Notify,
61}
62
63impl AfterResponse {
64    /// Runs `work` beside the request on the router `cx` serves, which [`settled`] waits for; on
65    /// a context outside every router, beside nothing that waits.
66    pub(crate) fn spawn(cx: &Cx, work: impl Future<Output = ()> + Send + 'static) {
67        match try_context::<Self>(cx) {
68            Some(after) => after.run(work),
69            None => drop(tokio::spawn(work)),
70        }
71    }
72
73    /// Runs `work` in a task of its own, counted until it ends.
74    fn run(&self, work: impl Future<Output = ()> + Send + 'static) {
75        // Counted before the task starts, so a `settled` right after the response sees it.
76        let guard = Guard::new(Arc::clone(&self.0));
77        tokio::spawn(async move {
78            let _guard = guard;
79            work.await;
80        });
81    }
82
83    async fn settled(&self) {
84        loop {
85            let idle = self.0.idle.notified();
86            let mut idle = std::pin::pin!(idle);
87            // Registered before the count is read, so a task ending in between still wakes it.
88            idle.as_mut().enable();
89            if self.0.count.load(Ordering::Acquire) == 0 {
90                return;
91            }
92            idle.await;
93        }
94    }
95}
96
97/// One unit of work in flight: counted while it lives, so a task that panics still ends.
98struct Guard(Arc<Running>);
99
100impl Guard {
101    fn new(running: Arc<Running>) -> Self {
102        running.count.fetch_add(1, Ordering::AcqRel);
103        Self(running)
104    }
105}
106
107impl Drop for Guard {
108    fn drop(&mut self) {
109        if self.0.count.fetch_sub(1, Ordering::AcqRel) == 1 {
110            self.0.idle.notify_waiters();
111        }
112    }
113}
114
115#[cfg(test)]
116mod tests;