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//!     |_| Ok(())
48//! );
49//! # }
50//! ```
51
52use std::collections::HashMap;
53use std::error::Error;
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    /// Job-specific error type. Must be convertible into a boxed error so
61    /// `WorkManager` does not need to be generic over the error.
62    type Error: Send + Sync + 'static + Into<Box<dyn Error + Send + Sync>>;
63
64    /// Runs the job and returns the result.
65    fn run(
66        self,
67    ) -> impl std::future::Future<Output = Result<Self::Output, Self::Error>> + Send + Sync;
68
69    /// Turns this job into a sequence where the next job depends on the output of this job.
70    /// Does not execute anything until the entire sequence is run.
71    fn then<F, Next>(self, next: F) -> Sequence<Self, Next, F>
72    where
73        F: FnOnce(Result<Self::Output, Self::Error>) -> Result<Next, Self::Error> + Send + Sync,
74        Next: Job<Error = Self::Error>,
75    {
76        Sequence { prev: self, next }
77    }
78}
79
80/// 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.
81pub struct Sequence<
82    Prev: Job,
83    Next,
84    F: FnOnce(Result<Prev::Output, Prev::Error>) -> Result<Next, Prev::Error> + Send + Sync,
85> {
86    prev: Prev,
87    next: F,
88}
89
90impl<Prev, Next, F> Job for Sequence<Prev, Next, F>
91where
92    Prev: Job,
93    F: FnOnce(Result<Prev::Output, Prev::Error>) -> Result<Next, Prev::Error> + Send + Sync,
94    Next: Job<Error = Prev::Error>,
95{
96    type Output = Next::Output;
97    type Error = Prev::Error;
98
99    /// Runs the sequence as a job and returns the result.
100    async fn run(self) -> Result<Self::Output, Self::Error> {
101        // run all previous jobs
102        let output = self.prev.run().await;
103
104        // pass the output to the next job generator and run it
105        let job = (self.next)(output)?;
106        job.run().await
107    }
108
109    fn then<Fn, Nx>(self, next: Fn) -> Sequence<Self, Nx, Fn>
110    where
111        Fn: FnOnce(Result<Self::Output, Self::Error>) -> Result<Nx, Self::Error> + Send + Sync,
112        Nx: Job<Error = Self::Error>,
113    {
114        Sequence { prev: self, next }
115    }
116}
117
118/// Manages the execution of asynchronous jobs.
119pub struct WorkManager {
120    handles: HashMap<String, JoinHandle<Result<(), Box<dyn Error + Send + Sync>>>>,
121}
122
123// Implement common methods for WorkManager
124impl WorkManager {
125    /// Creates a new WorkManager.
126    pub fn new() -> Self {
127        Self {
128            handles: HashMap::new(),
129        }
130    }
131
132    /// Cancels an enqueued job by the given name.
133    pub fn cancel(&mut self, name: &str) {
134        if let Some(handle) = self.handles.remove(name) {
135            handle.abort();
136        }
137    }
138
139    /// Cancels all enqueued jobs.
140    pub fn cancel_all(&mut self) {
141        for (_, handle) in self.handles.drain() {
142            handle.abort();
143        }
144    }
145}
146
147// Implement job-focused methods for WorkManager
148impl WorkManager {
149    /// Enqueues a job for execution.
150    /// If a job with the same name already exists, it will be overwritten if `overwrite` is true.
151    pub fn enqueue(&mut self, name: &str, job: impl Job + 'static, overwrite: bool) -> bool {
152        if self.handles.contains_key(name) {
153            if overwrite {
154                self.cancel(name);
155            } else {
156                return false;
157            }
158        }
159
160        let handle: JoinHandle<Result<(), Box<dyn Error + Send + Sync>>> =
161            spawn(async move { job.run().await.map(|_| ()).map_err(Into::into) });
162
163        self.handles.insert(name.into(), handle);
164        true
165    }
166
167    /// Enqueues a periodic job for execution at specified intervals.
168    /// If a job with the same name already exists, it will be overwritten if `overwrite` is true.
169    ///
170    /// `on_error` is a callback that is invoked whenever the job returns an error.
171    /// The callback receives the job's error and returns `Ok` to continue or
172    /// `Err` to stop the periodic execution and finish the task.
173    pub fn enqueue_periodic<J, F>(
174        &mut self,
175        name: &str,
176        job: J,
177        interval: Duration,
178        overwrite: bool,
179        on_error: F,
180    ) -> bool
181    where
182        J: Job + Clone + 'static,
183        F: Fn(J::Error) -> Result<(), J::Error> + Send + Sync + 'static,
184    {
185        if self.handles.contains_key(name) {
186            if overwrite {
187                self.cancel(name);
188            } else {
189                return false;
190            }
191        }
192
193        let handle: JoinHandle<Result<(), Box<dyn Error + Send + Sync>>> = spawn(async move {
194            let mut interval = tokio::time::interval(interval);
195            interval.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Skip);
196            loop {
197                match job.clone().run().await {
198                    Ok(_) => {}
199                    Err(e) => match on_error(e) {
200                        Ok(_) => {}
201                        Err(e) => {
202                            return Err(e.into());
203                        }
204                    },
205                }
206                interval.tick().await;
207            }
208        });
209
210        self.handles.insert(name.into(), handle);
211        true
212    }
213}
214
215impl Drop for WorkManager {
216    fn drop(&mut self) {
217        self.cancel_all();
218    }
219}
220
221#[cfg(test)]
222mod tests {
223    use super::*;
224    use tokio::sync::mpsc;
225
226    // create a mock job
227    struct EchoJob {
228        message: String,
229    }
230
231    // create a mock job that errors
232    struct ErrorJob {}
233
234    // implement the Job trait for the mock job
235    impl Job for EchoJob {
236        type Output = String;
237        type Error = std::io::Error;
238
239        async fn run(self) -> Result<Self::Output, Self::Error> {
240            println!("{}", self.message);
241            Ok(self.message)
242        }
243    }
244
245    // implement the Job trait for the mock job that errors
246    impl Job for ErrorJob {
247        type Output = String;
248        type Error = std::io::Error;
249
250        async fn run(self) -> Result<Self::Output, Self::Error> {
251            Err(std::io::Error::new(
252                std::io::ErrorKind::Other,
253                "This error is expected",
254            ))
255        }
256    }
257
258    // create a mock job that sends a message via channel
259    struct ChannelJob {
260        sender: mpsc::Sender<String>,
261        message: String,
262    }
263
264    impl Job for ChannelJob {
265        type Output = ();
266        type Error = std::io::Error;
267
268        async fn run(self) -> Result<Self::Output, Self::Error> {
269            let _ = self.sender.send(self.message).await;
270            Ok(())
271        }
272    }
273
274    #[derive(Clone)]
275    struct PeriodicChannelJob {
276        sender: mpsc::Sender<String>,
277        message: String,
278    }
279
280    impl Job for PeriodicChannelJob {
281        type Output = ();
282        type Error = std::io::Error;
283
284        async fn run(self) -> Result<Self::Output, Self::Error> {
285            let _ = self.sender.send(self.message.clone()).await;
286            Ok(())
287        }
288    }
289
290    // test to see if we can run a single job
291    #[tokio::test]
292    async fn run_job() {
293        let echo = EchoJob {
294            message: "run_job".into(),
295        };
296
297        let result = echo.run().await;
298        assert_eq!(result.unwrap(), "run_job");
299    }
300
301    // test to see if we can run a sequence of jobs
302    #[tokio::test]
303    async fn run_sequence() {
304        let echo = EchoJob {
305            message: "run_sequence_1".into(),
306        };
307
308        let sequence = echo.then(|result| {
309            assert_eq!(result?, "run_sequence_1");
310            Ok(EchoJob {
311                message: "run_sequence_2".into(),
312            })
313        });
314
315        let result = sequence.run().await;
316        assert_eq!(result.unwrap(), "run_sequence_2");
317    }
318
319    // test to see if we can run a sequence of jobs
320    #[tokio::test]
321    async fn run_sequence_err() {
322        let echo = EchoJob {
323            message: "run_sequence_err_1".into(),
324        };
325
326        let sequence = echo
327            .then(|result| {
328                assert_eq!(result?, "run_sequence_err_1");
329                Ok(ErrorJob {})
330            })
331            .then(|result| {
332                assert_eq!(result?, "run_sequence_err_1");
333                Ok(EchoJob {
334                    message: "run_sequence_err_2".into(),
335                })
336            });
337
338        let result = sequence.run().await;
339        assert!(result.is_err());
340        assert_eq!(
341            format!("{:?}", result),
342            "Err(Custom { kind: Other, error: \"This error is expected\" })"
343        );
344    }
345
346    #[tokio::test]
347    async fn test_work_manager_enqueue() {
348        let (tx, mut rx) = mpsc::channel(1);
349        let mut manager = WorkManager::new();
350
351        let job = ChannelJob {
352            sender: tx,
353            message: "enqueue_test".into(),
354        };
355
356        assert!(manager.enqueue("test_job", job, false));
357
358        let result = rx.recv().await;
359        assert_eq!(result, Some("enqueue_test".to_string()));
360    }
361
362    #[tokio::test]
363    async fn test_work_manager_overwrite() {
364        let mut manager = WorkManager::new();
365        let echo = EchoJob {
366            message: "1".into(),
367        };
368
369        // First enqueue
370        assert!(manager.enqueue("job", echo, false));
371
372        // Try enqueue same name, overwrite false
373        let echo2 = EchoJob {
374            message: "2".into(),
375        };
376        assert!(!manager.enqueue("job", echo2, false));
377
378        // Try enqueue same name, overwrite true
379        let echo3 = EchoJob {
380            message: "3".into(),
381        };
382        assert!(manager.enqueue("job", echo3, true));
383    }
384
385    #[tokio::test]
386    async fn test_work_manager_cancel() {
387        let (tx, mut rx) = mpsc::channel(1);
388        let mut manager = WorkManager::new();
389
390        // A job that waits a bit then sends
391        struct DelayedJob {
392            sender: mpsc::Sender<String>,
393        }
394        impl Job for DelayedJob {
395            type Output = ();
396            type Error = std::io::Error;
397            async fn run(self) -> Result<(), std::io::Error> {
398                tokio::time::sleep(Duration::from_millis(50)).await;
399                let _ = self.sender.send("done".to_string()).await;
400                Ok(())
401            }
402        }
403
404        manager.enqueue("delayed", DelayedJob { sender: tx }, false);
405        manager.cancel("delayed");
406
407        // Wait a bit longer than the job duration
408        tokio::time::sleep(Duration::from_millis(100)).await;
409
410        // Should not receive anything because it was cancelled
411        assert!(rx.try_recv().is_err());
412    }
413
414    #[tokio::test]
415    async fn test_work_manager_periodic() {
416        let (tx, mut rx) = mpsc::channel(10);
417        let mut manager = WorkManager::new();
418
419        let job = PeriodicChannelJob {
420            sender: tx,
421            message: "tick".into(),
422        };
423
424        // No error handler: errors (if any) are ignored, job continues
425        manager.enqueue_periodic(
426            "periodic",
427            job,
428            Duration::from_millis(10),
429            false,
430            |_| Ok(()),
431        );
432
433        // Expect at least 3 ticks
434        for _ in 0..3 {
435            let val = rx.recv().await;
436            assert_eq!(val, Some("tick".to_string()));
437        }
438        manager.cancel("periodic");
439    }
440
441    #[tokio::test]
442    async fn test_periodic_panic_behavior() {
443        let (tx, mut rx) = mpsc::channel(10);
444        let mut manager = WorkManager::new();
445
446        #[derive(Clone)]
447        struct FailsAfterOne {
448            sender: mpsc::Sender<String>,
449            counter: std::sync::Arc<std::sync::atomic::AtomicUsize>,
450        }
451        impl Job for FailsAfterOne {
452            type Output = ();
453            type Error = std::io::Error;
454            async fn run(self) -> Result<(), std::io::Error> {
455                let count = self
456                    .counter
457                    .fetch_add(1, std::sync::atomic::Ordering::SeqCst);
458                if count == 0 {
459                    let _ = self.sender.send("ok".to_string()).await;
460                    Ok(())
461                } else {
462                    Err(std::io::Error::new(std::io::ErrorKind::Other, "boom"))
463                }
464            }
465        }
466
467        let job = FailsAfterOne {
468            sender: tx,
469            counter: std::sync::Arc::new(std::sync::atomic::AtomicUsize::new(0)),
470        };
471
472        // Use an error handler that stops after the first error (panic-like behavior)
473        manager.enqueue_periodic("fail_job", job, Duration::from_millis(10), false, |err| {
474            Err(err)
475        });
476
477        assert_eq!(rx.recv().await, Some("ok".to_string()));
478
479        // Wait to ensure no more messages come (it should have errored and stopped)
480        tokio::time::sleep(Duration::from_millis(50)).await;
481        assert!(rx.try_recv().is_err());
482    }
483
484    #[tokio::test]
485    async fn test_periodic_panic_continue() {
486        let (tx, mut rx) = mpsc::channel(10);
487        let mut manager = WorkManager::new();
488
489        #[derive(Clone)]
490        struct FailsAfterOne {
491            sender: mpsc::Sender<String>,
492            counter: std::sync::Arc<std::sync::atomic::AtomicUsize>,
493        }
494        impl Job for FailsAfterOne {
495            type Output = ();
496            type Error = std::io::Error;
497            async fn run(self) -> Result<(), std::io::Error> {
498                let count = self
499                    .counter
500                    .fetch_add(1, std::sync::atomic::Ordering::SeqCst);
501                if count == 0 {
502                    let _ = self.sender.send("ok".to_string()).await;
503                    Ok(())
504                } else {
505                    Err(std::io::Error::new(std::io::ErrorKind::Other, "boom"))
506                }
507            }
508        }
509
510        let job = FailsAfterOne {
511            sender: tx,
512            counter: std::sync::Arc::new(std::sync::atomic::AtomicUsize::new(0)),
513        };
514
515        // Use an error handler that continues after an error (panic-like behavior)
516        manager.enqueue_periodic(
517            "fail_job",
518            job,
519            Duration::from_millis(10),
520            false,
521            |_| Ok(()),
522        );
523
524        // Expect the first ok
525        let val = rx.recv().await;
526        assert_eq!(val, Some("ok".to_string()));
527
528        // Expect at least 3 ignored errors
529        for _ in 0..3 {
530            assert!(rx.try_recv().is_err());
531        }
532        manager.cancel("fail_job");
533    }
534}