work-manager 0.1.3

A library for managing asynchronous work tasks.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
//! # Work Manager
//!
//! `work-manager` is a library designed to simplify the management of asynchronous tasks.
//! It allows you to define [`Job`]s, chain them into [`Sequence`]s, and schedule them using a [`WorkManager`].
//!
//! ## Key Features
//!
//! *   **Job Abstraction**: Implement the [`Job`] trait to define units of work.
//! *   **Job Sequencing**: Chain jobs together using [`Job::then`], passing results from one to the next.
//! *   **Task Management**: Use [`WorkManager`] to enqueue one-off or periodic jobs.
//! *   **Cancellation**: Easily cancel jobs by name.
//!
//! ## Example
//!
//! ```rust
//! use work_manager::{Job, WorkManager};
//! use std::time::Duration;
//!
//! #[derive(Clone)]
//! struct PrintJob {
//!     message: String,
//! }
//!
//! impl Job for PrintJob {
//!     type Output = ();
//!     type Error = std::io::Error;
//!
//!     async fn run(self) -> Result<Self::Output, Self::Error> {
//!         println!("{}", self.message);
//!         Ok(())
//!     }
//! }
//!
//! # #[tokio::main]
//! # async fn main() {
//! let mut manager = WorkManager::new();
//!
//! // Enqueue a single job
//! manager.enqueue("print_hello", PrintJob { message: "Hello".into() }, false);
//!
//! // Enqueue a periodic job
//! manager.enqueue_periodic(
//!     "print_tick",
//!     PrintJob { message: "Tick".into() },
//!     Duration::from_secs(1),
//!     false,
//!     |_| Ok(())
//! );
//! # }
//! ```

use std::collections::HashMap;
use std::error::Error;
use tokio::task::{JoinHandle, JoinSet, spawn};
use tokio::time::Duration;

/// A job that can be run asynchronously.
pub trait Job: Send + Sync + Sized {
    type Output: Send + Sync + 'static;
    /// Job-specific error type. Must be convertible into a boxed error so
    /// `WorkManager` does not need to be generic over the error.
    type Error: Send + Sync + 'static + Into<Box<dyn Error + Send + Sync>>;

    /// Runs the job and returns the result.
    fn run(
        self,
    ) -> impl std::future::Future<Output = Result<Self::Output, Self::Error>> + Send + Sync + 'static;

    /// Turns this job into a sequence where the next job depends on the output of this job.
    /// Does not execute anything until the entire sequence is run.
    fn then<F, Next>(self, next: F) -> Sequence<Self, Next, F>
    where
        F: FnOnce(Result<Self::Output, Self::Error>) -> Result<Next, Self::Error> + Send + Sync,
        Next: Job<Error = Self::Error>,
    {
        Sequence { prev: self, next }
    }

    /// Turns this job into a sequence of many jobs depending on the output of this job.
    /// Does not execute anything until the entire sequence is run.
    fn then_many<F, Next>(self, next: F) -> Sequence<Self, Vec<Next>, F>
    where
        F: FnOnce(Result<Self::Output, Self::Error>) -> Result<Vec<Next>, Self::Error>
            + Send
            + Sync,
        Next: Job<Error = Self::Error>,
    {
        Sequence { prev: self, next }
    }
}

/// 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.
pub struct Sequence<
    Prev: Job,
    Next,
    F: FnOnce(Result<Prev::Output, Prev::Error>) -> Result<Next, Prev::Error> + Send + Sync,
> {
    prev: Prev,
    next: F,
}

impl<Prev, Next, F> Clone for Sequence<Prev, Next, F>
where
    Prev: Job + Clone,
    F: FnOnce(Result<Prev::Output, Prev::Error>) -> Result<Next, Prev::Error> + Send + Sync + Clone,
    Next: Job<Error = Prev::Error>,
{
    fn clone(&self) -> Self {
        Self {
            prev: self.prev.clone(),
            next: self.next.clone(),
        }
    }
}

impl<Prev, Next, F> Clone for Sequence<Prev, Vec<Next>, F>
where
    Prev: Job + Clone,
    F: FnOnce(Result<Prev::Output, Prev::Error>) -> Result<Vec<Next>, Prev::Error>
        + Send
        + Sync
        + Clone,
    Next: Job<Error = Prev::Error>,
{
    fn clone(&self) -> Self {
        Self {
            prev: self.prev.clone(),
            next: self.next.clone(),
        }
    }
}

impl<Prev, Next, F> Job for Sequence<Prev, Next, F>
where
    Prev: Job + 'static,
    F: FnOnce(Result<Prev::Output, Prev::Error>) -> Result<Next, Prev::Error>
        + Send
        + Sync
        + 'static,
    Next: Job<Error = Prev::Error> + 'static,
{
    type Output = Next::Output;
    type Error = Prev::Error;

    /// Runs the sequence as a job and returns the result.
    async fn run(self) -> Result<Self::Output, Self::Error> {
        // run all previous jobs
        let output = self.prev.run().await;

        // pass the output to the next job generator and run it
        let job = (self.next)(output)?;
        job.run().await
    }
}

impl<Prev, Next, F> Job for Sequence<Prev, Vec<Next>, F>
where
    Prev: Job + 'static,
    F: FnOnce(Result<Prev::Output, Prev::Error>) -> Result<Vec<Next>, Prev::Error>
        + Send
        + Sync
        + 'static,
    Next: Job<Error = Prev::Error> + 'static,
{
    type Output = Vec<Next::Output>;
    type Error = Prev::Error;

    /// Runs the sequence as a job and returns the result.
    async fn run(self) -> Result<Self::Output, Self::Error> {
        // run all previous jobs
        let output = self.prev.run().await;

        // pass the output to the next job generator and run it
        let jobs = (self.next)(output)?;

        // iterate over the jobs and run them all in parallel
        let mut set = JoinSet::new();
        for job in jobs {
            set.spawn(job.run());
        }

        // capture the results
        let results = set.join_all().await;
        results.into_iter().collect()
    }
}

/// Manages the execution of asynchronous jobs.
pub struct WorkManager {
    handles: HashMap<String, JoinHandle<Result<(), Box<dyn Error + Send + Sync>>>>,
}

// Implement common methods for WorkManager
impl WorkManager {
    /// Creates a new WorkManager.
    pub fn new() -> Self {
        Self {
            handles: HashMap::new(),
        }
    }

    /// Cancels an enqueued job by the given name.
    pub fn cancel(&mut self, name: &str) {
        if let Some(handle) = self.handles.remove(name) {
            handle.abort();
        }
    }

    /// Cancels all enqueued jobs.
    pub fn cancel_all(&mut self) {
        for (_, handle) in self.handles.drain() {
            handle.abort();
        }
    }
}

// Implement job-focused methods for WorkManager
impl WorkManager {
    /// Enqueues a job for execution.
    /// If a job with the same name already exists, it will be overwritten if `overwrite` is true.
    pub fn enqueue(&mut self, name: &str, job: impl Job + 'static, overwrite: bool) -> bool {
        if self.handles.contains_key(name) {
            if overwrite {
                self.cancel(name);
            } else {
                return false;
            }
        }

        let handle: JoinHandle<Result<(), Box<dyn Error + Send + Sync>>> =
            spawn(async move { job.run().await.map(|_| ()).map_err(Into::into) });

        self.handles.insert(name.into(), handle);
        true
    }

    /// Enqueues a periodic job for execution at specified intervals.
    /// If a job with the same name already exists, it will be overwritten if `overwrite` is true.
    ///
    /// `on_error` is a callback that is invoked whenever the job returns an error.
    /// The callback receives the job's error and returns `Ok` to continue or
    /// `Err` to stop the periodic execution and finish the task.
    pub fn enqueue_periodic<J, F>(
        &mut self,
        name: &str,
        job: J,
        interval: Duration,
        overwrite: bool,
        on_error: F,
    ) -> bool
    where
        J: Job + Clone + 'static,
        F: Fn(J::Error) -> Result<(), J::Error> + Send + Sync + 'static,
    {
        if self.handles.contains_key(name) {
            if overwrite {
                self.cancel(name);
            } else {
                return false;
            }
        }

        let handle: JoinHandle<Result<(), Box<dyn Error + Send + Sync>>> = spawn(async move {
            let mut interval = tokio::time::interval(interval);
            interval.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Skip);
            loop {
                match job.clone().run().await {
                    Ok(_) => {}
                    Err(e) => match on_error(e) {
                        Ok(_) => {}
                        Err(e) => {
                            return Err(e.into());
                        }
                    },
                }
                interval.tick().await;
            }
        });

        self.handles.insert(name.into(), handle);
        true
    }
}

impl Drop for WorkManager {
    fn drop(&mut self) {
        self.cancel_all();
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use tokio::sync::mpsc;

    // create a mock job
    struct EchoJob {
        message: String,
    }

    // create a mock job that errors
    struct ErrorJob {}

    // implement the Job trait for the mock job
    impl Job for EchoJob {
        type Output = String;
        type Error = std::io::Error;

        async fn run(self) -> Result<Self::Output, Self::Error> {
            println!("{}", self.message);
            Ok(self.message)
        }
    }

    // implement the Job trait for the mock job that errors
    impl Job for ErrorJob {
        type Output = String;
        type Error = std::io::Error;

        async fn run(self) -> Result<Self::Output, Self::Error> {
            Err(std::io::Error::new(
                std::io::ErrorKind::Other,
                "This error is expected",
            ))
        }
    }

    // create a mock job that sends a message via channel
    struct ChannelJob {
        sender: mpsc::Sender<String>,
        message: String,
    }

    impl Job for ChannelJob {
        type Output = ();
        type Error = std::io::Error;

        async fn run(self) -> Result<Self::Output, Self::Error> {
            let _ = self.sender.send(self.message).await;
            Ok(())
        }
    }

    #[derive(Clone)]
    struct PeriodicChannelJob {
        sender: mpsc::Sender<String>,
        message: String,
    }

    impl Job for PeriodicChannelJob {
        type Output = ();
        type Error = std::io::Error;

        async fn run(self) -> Result<Self::Output, Self::Error> {
            let _ = self.sender.send(self.message.clone()).await;
            Ok(())
        }
    }

    // test to see if we can run a single job
    #[tokio::test]
    async fn run_job() {
        let echo = EchoJob {
            message: "run_job".into(),
        };

        let result = echo.run().await;
        assert_eq!(result.unwrap(), "run_job");
    }

    // test to see if we can run a sequence of jobs
    #[tokio::test]
    async fn run_sequence() {
        let echo = EchoJob {
            message: "run_sequence_1".into(),
        };

        let sequence = echo.then(|result| {
            assert_eq!(result?, "run_sequence_1");
            Ok(EchoJob {
                message: "run_sequence_2".into(),
            })
        });

        let result = sequence.run().await;
        assert_eq!(result.unwrap(), "run_sequence_2");
    }

    // test to see if we can run a sequence of many jobs
    #[tokio::test]
    async fn run_sequence_many() {
        let echo = EchoJob {
            message: "run_sequence_1".into(),
        };

        let sequence = echo.then_many(|result| {
            let result = result?;
            assert_eq!(result, "run_sequence_1");

            let mut jobs = Vec::with_capacity(result.len());
            for i in 0..result.len().clone() {
                jobs.push(EchoJob {
                    message: format!("run_sequence_many_{}", i),
                });
            }

            Ok(jobs)
        });

        let result = sequence.run().await.unwrap();
        assert_eq!(result.len(), 14);
        assert_eq!(result[0], "run_sequence_many_0");
        assert_eq!(result[13], "run_sequence_many_13");
    }

    // test to see if we can run a complex sequence of many jobs
    #[tokio::test]
    async fn run_sequence_many_complex() {
        let echo = EchoJob {
            message: "run_sequence_1".into(),
        };

        let sequence = echo.then_many(|result| {
            let result = result?;
            assert_eq!(result, "run_sequence_1");

            let mut jobs = Vec::with_capacity(result.len());
            for i in 0..result.len().clone() {
                let echo_a = EchoJob {
                    message: format!("run_sequence_many_{}_a", i),
                };
                let echo_b = echo_a.then(move |result| {
                    assert_eq!(result?, format!("run_sequence_many_{}_a", i));
                    Ok(EchoJob {
                        message: format!("run_sequence_many_{}_b", i),
                    })
                });
                let echo_c = echo_b.then(move |result| {
                    assert_eq!(result?, format!("run_sequence_many_{}_b", i));
                    Ok(EchoJob {
                        message: format!("run_sequence_many_{}_c", i),
                    })
                });

                jobs.push(echo_c);
            }

            Ok(jobs)
        });

        let result = sequence.run().await.unwrap();
        assert_eq!(result.len(), 14);
        assert_eq!(result[0], "run_sequence_many_0_c");
        assert_eq!(result[13], "run_sequence_many_13_c");
    }

    // test to see if we can run a sequence of jobs
    #[tokio::test]
    async fn run_sequence_err() {
        let echo = EchoJob {
            message: "run_sequence_err_1".into(),
        };

        let sequence = echo
            .then(|result| {
                assert_eq!(result?, "run_sequence_err_1");
                Ok(ErrorJob {})
            })
            .then(|result| {
                assert_eq!(result?, "run_sequence_err_1");
                Ok(EchoJob {
                    message: "run_sequence_err_2".into(),
                })
            });

        let result = sequence.run().await;
        assert!(result.is_err());
        assert_eq!(
            format!("{:?}", result),
            "Err(Custom { kind: Other, error: \"This error is expected\" })"
        );
    }

    #[tokio::test]
    async fn test_work_manager_enqueue() {
        let (tx, mut rx) = mpsc::channel(1);
        let mut manager = WorkManager::new();

        let job = ChannelJob {
            sender: tx,
            message: "enqueue_test".into(),
        };

        assert!(manager.enqueue("test_job", job, false));

        let result = rx.recv().await;
        assert_eq!(result, Some("enqueue_test".to_string()));
    }

    #[tokio::test]
    async fn test_work_manager_overwrite() {
        let mut manager = WorkManager::new();
        let echo = EchoJob {
            message: "1".into(),
        };

        // First enqueue
        assert!(manager.enqueue("job", echo, false));

        // Try enqueue same name, overwrite false
        let echo2 = EchoJob {
            message: "2".into(),
        };
        assert!(!manager.enqueue("job", echo2, false));

        // Try enqueue same name, overwrite true
        let echo3 = EchoJob {
            message: "3".into(),
        };
        assert!(manager.enqueue("job", echo3, true));
    }

    #[tokio::test]
    async fn test_work_manager_cancel() {
        let (tx, mut rx) = mpsc::channel(1);
        let mut manager = WorkManager::new();

        // A job that waits a bit then sends
        struct DelayedJob {
            sender: mpsc::Sender<String>,
        }
        impl Job for DelayedJob {
            type Output = ();
            type Error = std::io::Error;
            async fn run(self) -> Result<(), std::io::Error> {
                tokio::time::sleep(Duration::from_millis(50)).await;
                let _ = self.sender.send("done".to_string()).await;
                Ok(())
            }
        }

        manager.enqueue("delayed", DelayedJob { sender: tx }, false);
        manager.cancel("delayed");

        // Wait a bit longer than the job duration
        tokio::time::sleep(Duration::from_millis(100)).await;

        // Should not receive anything because it was cancelled
        assert!(rx.try_recv().is_err());
    }

    #[tokio::test]
    async fn test_work_manager_periodic() {
        let (tx, mut rx) = mpsc::channel(10);
        let mut manager = WorkManager::new();

        let job = PeriodicChannelJob {
            sender: tx,
            message: "tick".into(),
        };

        // No error handler: errors (if any) are ignored, job continues
        manager.enqueue_periodic(
            "periodic",
            job,
            Duration::from_millis(10),
            false,
            |_| Ok(()),
        );

        // Expect at least 3 ticks
        for _ in 0..3 {
            let val = rx.recv().await;
            assert_eq!(val, Some("tick".to_string()));
        }
        manager.cancel("periodic");
    }

    #[tokio::test]
    async fn test_periodic_panic_behavior() {
        let (tx, mut rx) = mpsc::channel(10);
        let mut manager = WorkManager::new();

        #[derive(Clone)]
        struct FailsAfterOne {
            sender: mpsc::Sender<String>,
            counter: std::sync::Arc<std::sync::atomic::AtomicUsize>,
        }
        impl Job for FailsAfterOne {
            type Output = ();
            type Error = std::io::Error;
            async fn run(self) -> Result<(), std::io::Error> {
                let count = self
                    .counter
                    .fetch_add(1, std::sync::atomic::Ordering::SeqCst);
                if count == 0 {
                    let _ = self.sender.send("ok".to_string()).await;
                    Ok(())
                } else {
                    Err(std::io::Error::new(std::io::ErrorKind::Other, "boom"))
                }
            }
        }

        let job = FailsAfterOne {
            sender: tx,
            counter: std::sync::Arc::new(std::sync::atomic::AtomicUsize::new(0)),
        };

        // Use an error handler that stops after the first error (panic-like behavior)
        manager.enqueue_periodic("fail_job", job, Duration::from_millis(10), false, |err| {
            Err(err)
        });

        assert_eq!(rx.recv().await, Some("ok".to_string()));

        // Wait to ensure no more messages come (it should have errored and stopped)
        tokio::time::sleep(Duration::from_millis(50)).await;
        assert!(rx.try_recv().is_err());
    }

    #[tokio::test]
    async fn test_periodic_panic_continue() {
        let (tx, mut rx) = mpsc::channel(10);
        let mut manager = WorkManager::new();

        #[derive(Clone)]
        struct FailsAfterOne {
            sender: mpsc::Sender<String>,
            counter: std::sync::Arc<std::sync::atomic::AtomicUsize>,
        }
        impl Job for FailsAfterOne {
            type Output = ();
            type Error = std::io::Error;
            async fn run(self) -> Result<(), std::io::Error> {
                let count = self
                    .counter
                    .fetch_add(1, std::sync::atomic::Ordering::SeqCst);
                if count == 0 {
                    let _ = self.sender.send("ok".to_string()).await;
                    Ok(())
                } else {
                    Err(std::io::Error::new(std::io::ErrorKind::Other, "boom"))
                }
            }
        }

        let job = FailsAfterOne {
            sender: tx,
            counter: std::sync::Arc::new(std::sync::atomic::AtomicUsize::new(0)),
        };

        // Use an error handler that continues after an error (panic-like behavior)
        manager.enqueue_periodic(
            "fail_job",
            job,
            Duration::from_millis(10),
            false,
            |_| Ok(()),
        );

        // Expect the first ok
        let val = rx.recv().await;
        assert_eq!(val, Some("ok".to_string()));

        // Expect at least 3 ignored errors
        for _ in 0..3 {
            assert!(rx.try_recv().is_err());
        }
        manager.cancel("fail_job");
    }
}