Skip to main content

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