1use std::collections::HashMap;
53use std::error::Error;
54use tokio::task::{JoinHandle, spawn};
55use tokio::time::Duration;
56
57pub trait Job: Send + Sync + Sized {
59 type Output: Send + Sync + 'static;
60 type Error: Send + Sync + 'static + Into<Box<dyn Error + Send + Sync>>;
63
64 fn run(
66 self,
67 ) -> impl std::future::Future<Output = Result<Self::Output, Self::Error>> + Send + Sync;
68
69 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
80pub 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 async fn run(self) -> Result<Self::Output, Self::Error> {
101 let output = self.prev.run().await;
103
104 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
118pub struct WorkManager {
120 handles: HashMap<String, JoinHandle<Result<(), Box<dyn Error + Send + Sync>>>>,
121}
122
123impl WorkManager {
125 pub fn new() -> Self {
127 Self {
128 handles: HashMap::new(),
129 }
130 }
131
132 pub fn cancel(&mut self, name: &str) {
134 if let Some(handle) = self.handles.remove(name) {
135 handle.abort();
136 }
137 }
138
139 pub fn cancel_all(&mut self) {
141 for (_, handle) in self.handles.drain() {
142 handle.abort();
143 }
144 }
145}
146
147impl WorkManager {
149 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 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 struct EchoJob {
228 message: String,
229 }
230
231 struct ErrorJob {}
233
234 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 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 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 #[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 #[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 #[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 assert!(manager.enqueue("job", echo, false));
371
372 let echo2 = EchoJob {
374 message: "2".into(),
375 };
376 assert!(!manager.enqueue("job", echo2, false));
377
378 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 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 tokio::time::sleep(Duration::from_millis(100)).await;
409
410 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 manager.enqueue_periodic(
426 "periodic",
427 job,
428 Duration::from_millis(10),
429 false,
430 |_| Ok(()),
431 );
432
433 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 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 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 manager.enqueue_periodic(
517 "fail_job",
518 job,
519 Duration::from_millis(10),
520 false,
521 |_| Ok(()),
522 );
523
524 let val = rx.recv().await;
526 assert_eq!(val, Some("ok".to_string()));
527
528 for _ in 0..3 {
530 assert!(rx.try_recv().is_err());
531 }
532 manager.cancel("fail_job");
533 }
534}