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