Skip to main content

utils/
background.rs

1//! A one-at-a-time background job with a pollable state.
2//!
3//! `Runner<P, R>` holds `Idle` or `Running` in a mutex. `try_start` spawns
4//! the job and refuses a second start while one runs. The job publishes
5//! progress through `Progress::update`. A drop guard returns the runner to
6//! `Idle` when the job ends, even on panic. The lock is never held across
7//! an await.
8
9use std::future::Future;
10use std::sync::{Arc, Mutex, MutexGuard};
11
12use time::OffsetDateTime;
13use tracing::Instrument;
14
15pub struct Runner<P, R> {
16    state: Mutex<RunnerState<P, R>>,
17}
18
19#[derive(Debug, Clone)]
20pub enum RunnerState<P, R> {
21    Idle {
22        last: Option<LastRun<R>>,
23    },
24    Running {
25        started_at: OffsetDateTime,
26        progress: P,
27    },
28}
29
30#[derive(Debug, Clone, PartialEq, Eq)]
31pub struct LastRun<R> {
32    pub finished_at: OffsetDateTime,
33    pub outcome: Result<R, String>,
34}
35
36/// Handle the job uses to publish progress.
37pub struct Progress<P, R> {
38    runner: Arc<Runner<P, R>>,
39}
40
41impl<P, R> Progress<P, R> {
42    /// Lock, mutate, release. No await runs under the lock.
43    pub fn update(&self, f: impl FnOnce(&mut P)) {
44        if let RunnerState::Running { progress, .. } = &mut *self.runner.lock() {
45            f(progress);
46        }
47    }
48
49    /// Build a `Progress` handle bound to `runner` outside of `try_start`,
50    /// for tests that need to drive `fetch_missing_with` directly against a
51    /// runner already placed in `Running`.
52    #[cfg(any(test, feature = "test-support"))]
53    pub fn for_test(runner: Arc<Runner<P, R>>) -> Self {
54        Self { runner }
55    }
56}
57
58impl<P, R> Default for Runner<P, R> {
59    fn default() -> Self {
60        Self::new()
61    }
62}
63
64impl<P, R> Runner<P, R> {
65    pub fn new() -> Self {
66        Self {
67            state: Mutex::new(RunnerState::Idle { last: None }),
68        }
69    }
70
71    fn lock(&self) -> MutexGuard<'_, RunnerState<P, R>> {
72        self.state
73            .lock()
74            .unwrap_or_else(|poisoned| poisoned.into_inner())
75    }
76
77    pub fn is_running(&self) -> bool {
78        matches!(*self.lock(), RunnerState::Running { .. })
79    }
80}
81
82impl<P: Clone + Send + 'static, R: Clone + Send + 'static> Runner<P, R> {
83    /// Start `job` unless a run is in progress. Returns `false` when one is.
84    pub fn try_start<F, Fut>(self: &Arc<Self>, initial: P, job: F) -> bool
85    where
86        F: FnOnce(Progress<P, R>) -> Fut + Send + 'static,
87        Fut: Future<Output = Result<R, String>> + Send + 'static,
88    {
89        {
90            let mut state = self.lock();
91            if matches!(*state, RunnerState::Running { .. }) {
92                return false;
93            }
94            *state = RunnerState::Running {
95                started_at: OffsetDateTime::now_utc(),
96                progress: initial,
97            };
98        }
99        let mut guard = RunningGuard {
100            runner: Arc::clone(self),
101            outcome: None,
102        };
103        let progress = Progress {
104            runner: Arc::clone(self),
105        };
106        tokio::spawn(
107            async move {
108                guard.outcome = Some(job(progress).await);
109                // Explicit: the guard's Drop publishes the outcome.
110                drop(guard);
111            }
112            .in_current_span(),
113        );
114        true
115    }
116
117    pub fn snapshot(&self) -> RunnerState<P, R> {
118        self.lock().clone()
119    }
120
121    /// Poll until the runner is `Idle` and return its last run. Panics after
122    /// two seconds.
123    #[cfg(any(test, feature = "test-support"))]
124    pub async fn wait_idle(&self) -> Option<LastRun<R>> {
125        for _ in 0..400 {
126            if let RunnerState::Idle { last } = self.snapshot() {
127                return last;
128            }
129            tokio::time::sleep(std::time::Duration::from_millis(5)).await;
130        }
131        panic!("runner did not go idle");
132    }
133}
134
135/// Resets the runner to `Idle` when the job ends, whether it returned or
136/// panicked.
137struct RunningGuard<P, R> {
138    runner: Arc<Runner<P, R>>,
139    outcome: Option<Result<R, String>>,
140}
141
142impl<P, R> Drop for RunningGuard<P, R> {
143    fn drop(&mut self) {
144        let outcome = self
145            .outcome
146            .take()
147            .unwrap_or_else(|| Err("interrupted before completion".to_string()));
148        *self.runner.lock() = RunnerState::Idle {
149            last: Some(LastRun {
150                finished_at: OffsetDateTime::now_utc(),
151                outcome,
152            }),
153        };
154    }
155}
156
157#[cfg(test)]
158mod tests {
159    use std::sync::Arc;
160    use std::time::Duration;
161
162    use super::*;
163
164    #[tokio::test]
165    async fn second_start_is_refused_while_running() {
166        let runner: Arc<Runner<u32, u32>> = Arc::new(Runner::new());
167        let (tx, rx) = tokio::sync::oneshot::channel::<()>();
168        assert!(runner.try_start(0, |_| async move {
169            let _ = rx.await;
170            Ok(1)
171        }));
172        assert!(!runner.try_start(0, |_| async { Ok(2) }));
173        assert!(runner.is_running());
174        tx.send(()).unwrap();
175        let last = runner.wait_idle().await.expect("last run");
176        assert_eq!(last.outcome, Ok(1));
177    }
178
179    #[tokio::test]
180    async fn progress_updates_are_visible_in_snapshot() {
181        let runner: Arc<Runner<u32, ()>> = Arc::new(Runner::new());
182        let (tx, rx) = tokio::sync::oneshot::channel::<()>();
183        runner.try_start(0, |progress| async move {
184            progress.update(|p| *p = 7);
185            let _ = rx.await;
186            Ok(())
187        });
188        for _ in 0..200 {
189            if let RunnerState::Running { progress: 7, .. } = runner.snapshot() {
190                break;
191            }
192            tokio::time::sleep(Duration::from_millis(5)).await;
193        }
194        assert!(matches!(
195            runner.snapshot(),
196            RunnerState::Running { progress: 7, .. }
197        ));
198        tx.send(()).unwrap();
199        runner.wait_idle().await;
200    }
201
202    #[tokio::test]
203    async fn error_outcome_is_kept() {
204        let runner: Arc<Runner<(), ()>> = Arc::new(Runner::new());
205        runner.try_start((), |_| async { Err("boom".to_string()) });
206        let last = runner.wait_idle().await.expect("last run");
207        assert_eq!(last.outcome, Err("boom".to_string()));
208    }
209
210    #[tokio::test]
211    async fn panic_leaves_idle_with_interrupted_message() {
212        let runner: Arc<Runner<(), ()>> = Arc::new(Runner::new());
213        runner.try_start((), |_| async { panic!("job died") });
214        let last = runner.wait_idle().await.expect("last run");
215        assert_eq!(
216            last.outcome,
217            Err("interrupted before completion".to_string())
218        );
219    }
220}