work_manager/
lib.rs

1//! # Work Manager
2//!
3//! `work-manager` is a library designed to simplify the management of asynchronous tasks.
4//! It allows you to define [`Job`]s, chain them into [`Sequence`]s, and schedule them using a [`WorkManager`].
5//!
6//! ## Key Features
7//!
8//! *   **Job Abstraction**: Implement the [`Job`] trait to define units of work.
9//! *   **Job Sequencing**: Chain jobs together using [`Job::then`], passing results from one to the next.
10//! *   **Task Management**: Use [`WorkManager`] to enqueue one-off or periodic jobs.
11//! *   **Cancellation**: Easily cancel jobs by name.
12//!
13//! ## Example
14//!
15//! ```rust
16//! use work_manager::{Job, WorkManager};
17//! use std::time::Duration;
18//!
19//! #[derive(Clone)]
20//! struct PrintJob {
21//!     message: String,
22//! }
23//!
24//! impl Job for PrintJob {
25//!     type Output = ();
26//!     type Error = std::io::Error;
27//!
28//!     async fn run(self) -> Result<Self::Output, Self::Error> {
29//!         println!("{}", self.message);
30//!         Ok(())
31//!     }
32//! }
33//!
34//! # #[tokio::main]
35//! # async fn main() {
36//! let mut manager = WorkManager::new();
37//!
38//! // Enqueue a single job
39//! manager.enqueue("print_hello", PrintJob { message: "Hello".into() }, false);
40//!
41//! // Enqueue a periodic job
42//! manager.enqueue_periodic(
43//!     "print_tick",
44//!     PrintJob { message: "Tick".into() },
45//!     Duration::from_secs(1),
46//!     false,
47//!     false
48//! );
49//! # }
50//! ```
51
52use std::collections::HashMap;
53use std::fmt::Debug;
54use tokio::task::{JoinHandle, spawn};
55use tokio::time::Duration;
56
57/// A job that can be run asynchronously.
58pub trait Job: Send + Sync + Sized {
59    type Output: Send + Sync + 'static;
60    type Error: Send + Sync + 'static;
61
62    /// Runs the job and returns the result.
63    fn run(
64        self,
65    ) -> impl std::future::Future<Output = Result<Self::Output, Self::Error>> + Send + Sync;
66
67    /// Turns this job into a sequence where the next job depends on the output of this job.
68    /// Does not execute anything until the entire sequence is run.
69    fn then<F, Next>(self, next: F) -> Sequence<Self, Next, F>
70    where
71        F: FnOnce(Result<Self::Output, Self::Error>) -> Result<Next, Self::Error> + Send + Sync,
72        Next: Job<Error = Self::Error>,
73    {
74        Sequence { prev: self, next }
75    }
76}
77
78/// A struct representing a sequence where the second job is generated based on the first and the result is passed into its next function generator.
79pub struct Sequence<
80    Prev: Job,
81    Next,
82    F: FnOnce(Result<Prev::Output, Prev::Error>) -> Result<Next, Prev::Error> + Send + Sync,
83> {
84    prev: Prev,
85    next: F,
86}
87
88impl<Prev, Next, F> Job for Sequence<Prev, Next, F>
89where
90    Prev: Job,
91    F: FnOnce(Result<Prev::Output, Prev::Error>) -> Result<Next, Prev::Error> + Send + Sync,
92    Next: Job<Error = Prev::Error>,
93{
94    type Output = Next::Output;
95    type Error = Prev::Error;
96
97    /// Runs the sequence as a job and returns the result.
98    async fn run(self) -> Result<Self::Output, Self::Error> {
99        // run all previous jobs
100        let output = self.prev.run().await;
101
102        // pass the output to the next job generator and run it
103        let job = (self.next)(output)?;
104        job.run().await
105    }
106
107    fn then<Fn, Nx>(self, next: Fn) -> Sequence<Self, Nx, Fn>
108    where
109        Fn: FnOnce(Result<Self::Output, Self::Error>) -> Result<Nx, Self::Error> + Send + Sync,
110        Nx: Job<Error = Self::Error>,
111    {
112        Sequence { prev: self, next }
113    }
114}
115
116/// Manages the execution of asynchronous jobs.
117pub struct WorkManager<E> {
118    handles: HashMap<String, JoinHandle<Result<(), E>>>,
119}
120
121// Implement common methods for WorkManager
122impl<E> WorkManager<E> {
123    /// Creates a new WorkManager.
124    pub fn new() -> Self {
125        Self {
126            handles: HashMap::new(),
127        }
128    }
129
130    /// Cancels an enqueued job by the given name.
131    pub fn cancel(&mut self, name: &str) {
132        if let Some(handle) = self.handles.remove(name) {
133            handle.abort();
134        }
135    }
136
137    /// Cancels all enqueued jobs.
138    pub fn cancel_all(&mut self) {
139        for (_, handle) in self.handles.drain() {
140            handle.abort();
141        }
142    }
143}
144
145// Implement job-focused methods for WorkManager
146impl<E: Debug + Send + Sync + 'static> WorkManager<E> {
147    /// Enqueues a job for execution.
148    /// If a job with the same name already exists, it will be overwritten if `overwrite` is true.
149    pub fn enqueue(
150        &mut self,
151        name: &str,
152        job: impl Job<Error = E> + 'static,
153        overwrite: bool,
154    ) -> bool {
155        if self.handles.contains_key(name) {
156            if overwrite {
157                self.cancel(name);
158            } else {
159                return false;
160            }
161        }
162
163        let handle: JoinHandle<Result<(), E>> = spawn(async move {
164            job.run().await?;
165            Ok(())
166        });
167
168        self.handles.insert(name.into(), handle);
169        return true;
170    }
171
172    /// Enqueues a periodic job for execution at specified intervals.
173    /// If a job with the same name already exists, it will be overwritten if `overwrite` is true.
174    /// If `panic` is true, the periodic job will cancel and return the error upon encountering one.
175    pub fn enqueue_periodic(
176        &mut self,
177        name: &str,
178        job: impl Job<Error = E> + Clone + 'static,
179        interval: Duration,
180        overwrite: bool,
181        panic: bool,
182    ) -> bool {
183        if self.handles.contains_key(name) {
184            if overwrite {
185                self.cancel(name);
186            } else {
187                return false;
188            }
189        }
190
191        let handle: JoinHandle<Result<(), E>> = spawn(async move {
192            let mut interval = tokio::time::interval(interval);
193            interval.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Skip);
194            loop {
195                match job.clone().run().await {
196                    Ok(_) => {}
197                    Err(e) => {
198                        if panic {
199                            return Err(e);
200                        } else {
201                            eprintln!("Error: {:?}", e);
202                        }
203                    }
204                }
205                interval.tick().await;
206            }
207        });
208
209        self.handles.insert(name.into(), handle);
210        return true;
211    }
212}
213
214impl<E> Drop for WorkManager<E> {
215    fn drop(&mut self) {
216        self.cancel_all();
217    }
218}
219
220#[cfg(test)]
221mod tests {
222    use super::*;
223    use tokio::sync::mpsc;
224
225    // create a mock job
226    struct EchoJob {
227        message: String,
228    }
229
230    // create a mock job that errors
231    struct ErrorJob {}
232
233    // implement the Job trait for the mock job
234    impl Job for EchoJob {
235        type Output = String;
236        type Error = std::io::Error;
237
238        async fn run(self) -> Result<Self::Output, Self::Error> {
239            println!("{}", self.message);
240            Ok(self.message)
241        }
242    }
243
244    // implement the Job trait for the mock job that errors
245    impl Job for ErrorJob {
246        type Output = String;
247        type Error = std::io::Error;
248
249        async fn run(self) -> Result<Self::Output, Self::Error> {
250            Err(std::io::Error::new(
251                std::io::ErrorKind::Other,
252                "This error is expected",
253            ))
254        }
255    }
256
257    // create a mock job that sends a message via channel
258    struct ChannelJob {
259        sender: mpsc::Sender<String>,
260        message: String,
261    }
262
263    impl Job for ChannelJob {
264        type Output = ();
265        type Error = std::io::Error;
266
267        async fn run(self) -> Result<Self::Output, Self::Error> {
268            let _ = self.sender.send(self.message).await;
269            Ok(())
270        }
271    }
272
273    #[derive(Clone)]
274    struct PeriodicChannelJob {
275        sender: mpsc::Sender<String>,
276        message: String,
277    }
278
279    impl Job for PeriodicChannelJob {
280        type Output = ();
281        type Error = std::io::Error;
282
283        async fn run(self) -> Result<Self::Output, Self::Error> {
284            let _ = self.sender.send(self.message.clone()).await;
285            Ok(())
286        }
287    }
288
289    // test to see if we can run a single job
290    #[tokio::test]
291    async fn run_job() {
292        let echo = EchoJob {
293            message: "run_job".into(),
294        };
295
296        let result = echo.run().await;
297        assert_eq!(result.unwrap(), "run_job");
298    }
299
300    // test to see if we can run a sequence of jobs
301    #[tokio::test]
302    async fn run_sequence() {
303        let echo = EchoJob {
304            message: "run_sequence_1".into(),
305        };
306
307        let sequence = echo.then(|result| {
308            assert_eq!(result?, "run_sequence_1");
309            Ok(EchoJob {
310                message: "run_sequence_2".into(),
311            })
312        });
313
314        let result = sequence.run().await;
315        assert_eq!(result.unwrap(), "run_sequence_2");
316    }
317
318    // test to see if we can run a sequence of jobs
319    #[tokio::test]
320    async fn run_sequence_err() {
321        let echo = EchoJob {
322            message: "run_sequence_err_1".into(),
323        };
324
325        let sequence = echo
326            .then(|result| {
327                assert_eq!(result?, "run_sequence_err_1");
328                Ok(ErrorJob {})
329            })
330            .then(|result| {
331                assert_eq!(result?, "run_sequence_err_1");
332                Ok(EchoJob {
333                    message: "run_sequence_err_2".into(),
334                })
335            });
336
337        let result = sequence.run().await;
338        assert!(result.is_err());
339        assert_eq!(
340            format!("{:?}", result),
341            "Err(Custom { kind: Other, error: \"This error is expected\" })"
342        );
343    }
344
345    #[tokio::test]
346    async fn test_work_manager_enqueue() {
347        let (tx, mut rx) = mpsc::channel(1);
348        let mut manager = WorkManager::new();
349
350        let job = ChannelJob {
351            sender: tx,
352            message: "enqueue_test".into(),
353        };
354
355        assert!(manager.enqueue("test_job", job, false));
356
357        let result = rx.recv().await;
358        assert_eq!(result, Some("enqueue_test".to_string()));
359    }
360
361    #[tokio::test]
362    async fn test_work_manager_overwrite() {
363        let mut manager: WorkManager<std::io::Error> = WorkManager::new();
364        let echo = EchoJob {
365            message: "1".into(),
366        };
367
368        // First enqueue
369        assert!(manager.enqueue("job", echo, false));
370
371        // Try enqueue same name, overwrite false
372        let echo2 = EchoJob {
373            message: "2".into(),
374        };
375        assert!(!manager.enqueue("job", echo2, false));
376
377        // Try enqueue same name, overwrite true
378        let echo3 = EchoJob {
379            message: "3".into(),
380        };
381        assert!(manager.enqueue("job", echo3, true));
382    }
383
384    #[tokio::test]
385    async fn test_work_manager_cancel() {
386        let (tx, mut rx) = mpsc::channel(1);
387        let mut manager = WorkManager::new();
388
389        // A job that waits a bit then sends
390        struct DelayedJob {
391            sender: mpsc::Sender<String>,
392        }
393        impl Job for DelayedJob {
394            type Output = ();
395            type Error = std::io::Error;
396            async fn run(self) -> Result<(), std::io::Error> {
397                tokio::time::sleep(Duration::from_millis(50)).await;
398                let _ = self.sender.send("done".to_string()).await;
399                Ok(())
400            }
401        }
402
403        manager.enqueue("delayed", DelayedJob { sender: tx }, false);
404        manager.cancel("delayed");
405
406        // Wait a bit longer than the job duration
407        tokio::time::sleep(Duration::from_millis(100)).await;
408
409        // Should not receive anything because it was cancelled
410        assert!(rx.try_recv().is_err());
411    }
412
413    #[tokio::test]
414    async fn test_work_manager_periodic() {
415        let (tx, mut rx) = mpsc::channel(10);
416        let mut manager = WorkManager::new();
417
418        let job = PeriodicChannelJob {
419            sender: tx,
420            message: "tick".into(),
421        };
422
423        manager.enqueue_periodic("periodic", job, Duration::from_millis(10), false, false);
424
425        // Expect at least 3 ticks
426        for _ in 0..3 {
427            let val = rx.recv().await;
428            assert_eq!(val, Some("tick".to_string()));
429        }
430        manager.cancel("periodic");
431    }
432
433    #[tokio::test]
434    async fn test_periodic_panic_behavior() {
435        let (tx, mut rx) = mpsc::channel(10);
436        let mut manager = WorkManager::new();
437
438        #[derive(Clone)]
439        struct FailsAfterOne {
440            sender: mpsc::Sender<String>,
441            counter: std::sync::Arc<std::sync::atomic::AtomicUsize>,
442        }
443        impl Job for FailsAfterOne {
444            type Output = ();
445            type Error = std::io::Error;
446            async fn run(self) -> Result<(), std::io::Error> {
447                let count = self
448                    .counter
449                    .fetch_add(1, std::sync::atomic::Ordering::SeqCst);
450                if count == 0 {
451                    let _ = self.sender.send("ok".to_string()).await;
452                    Ok(())
453                } else {
454                    Err(std::io::Error::new(std::io::ErrorKind::Other, "boom"))
455                }
456            }
457        }
458
459        let job = FailsAfterOne {
460            sender: tx,
461            counter: std::sync::Arc::new(std::sync::atomic::AtomicUsize::new(0)),
462        };
463
464        // panic = true, should stop after error
465        manager.enqueue_periodic("fail_job", job, Duration::from_millis(10), false, true);
466
467        assert_eq!(rx.recv().await, Some("ok".to_string()));
468
469        // Wait to ensure no more messages come (it should have errored and stopped)
470        tokio::time::sleep(Duration::from_millis(50)).await;
471        assert!(rx.try_recv().is_err());
472    }
473}