1use std::collections::HashMap;
35use std::future::Future;
36use std::panic::AssertUnwindSafe;
37use std::sync::atomic::{AtomicBool, AtomicU32, Ordering};
38use std::sync::{Arc, Mutex};
39use std::time::{Duration, SystemTime, UNIX_EPOCH};
40
41use async_trait::async_trait;
42use futures::FutureExt;
43use tokio::sync::{Notify, Semaphore};
44use tokio::task::JoinSet;
45use tokio::time::Instant;
46use tokio_util::sync::CancellationToken;
47
48const MAX_BACKOFF_DOUBLINGS: u32 = 5;
50
51#[derive(Debug, Clone, Copy, PartialEq, Eq)]
53#[non_exhaustive]
54pub enum Schedule {
55 Every(Duration),
58 EveryTick,
61 Continuous,
63 DailyUtc { hour: u8, minute: u8 },
67}
68
69impl Schedule {
70 pub fn daily_utc(hour: u8, minute: u8) -> Option<Self> {
72 (hour < 24 && minute < 60).then_some(Self::DailyUtc { hour, minute })
73 }
74
75 fn takes_a_permit(self) -> bool {
76 matches!(self, Self::Every(_) | Self::DailyUtc { .. })
77 }
78}
79
80#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
82#[error("{0}")]
83pub struct ServiceError(pub String);
84
85impl ServiceError {
86 pub fn new(message: impl Into<String>) -> Self {
87 Self(message.into())
88 }
89}
90
91#[derive(Debug, Clone)]
93pub struct ServiceContext {
94 shutdown: CancellationToken,
95 run: u64,
96 failures: u32,
97}
98
99impl ServiceContext {
100 pub fn shutdown(&self) -> &CancellationToken {
102 &self.shutdown
103 }
104
105 pub fn run(&self) -> u64 {
123 self.run
124 }
125
126 pub fn failures(&self) -> u32 {
128 self.failures
129 }
130}
131
132#[async_trait]
134pub trait Service: Send + Sync + 'static {
135 fn name(&self) -> &str;
136 fn schedule(&self) -> Schedule;
137
138 async fn start(&self, _ctx: &ServiceContext) -> Result<(), ServiceError> {
141 Ok(())
142 }
143
144 async fn run(&self, ctx: &ServiceContext) -> Result<(), ServiceError>;
145
146 async fn stop(&self) {}
148}
149
150pub struct FnService<F> {
152 name: String,
153 schedule: Schedule,
154 run: F,
155}
156
157impl<F, Fut> FnService<F>
158where
159 F: Fn() -> Fut + Send + Sync + 'static,
160 Fut: Future<Output = Result<(), ServiceError>> + Send + 'static,
161{
162 pub fn new(name: impl Into<String>, schedule: Schedule, run: F) -> Self {
163 Self {
164 name: name.into(),
165 schedule,
166 run,
167 }
168 }
169}
170
171#[async_trait]
172impl<F, Fut> Service for FnService<F>
173where
174 F: Fn() -> Fut + Send + Sync + 'static,
175 Fut: Future<Output = Result<(), ServiceError>> + Send + 'static,
176{
177 fn name(&self) -> &str {
178 &self.name
179 }
180
181 fn schedule(&self) -> Schedule {
182 self.schedule
183 }
184
185 async fn run(&self, _ctx: &ServiceContext) -> Result<(), ServiceError> {
186 (self.run)().await
187 }
188}
189
190#[derive(Debug, Clone, PartialEq, Eq)]
193#[non_exhaustive]
194pub enum ServiceEvent {
195 Launched { service: String, run: u64 },
197 Ended {
200 service: String,
201 run: u64,
202 outcome: ServiceRunEnd,
203 elapsed: Duration,
204 },
205 StartFailed { service: String, error: String },
207}
208
209#[derive(Debug, Clone, PartialEq, Eq)]
211#[non_exhaustive]
212pub enum ServiceRunEnd {
213 Succeeded { previous_failures: u32 },
215 Failed { failures: u32, error: String },
217 Aborted,
220 Skipped,
223}
224
225pub trait ServiceObserver: Send + Sync {
227 fn event(&self, event: ServiceEvent);
228}
229
230#[async_trait]
232pub trait ServiceGate: Send + Sync {
233 async fn ready(&self) -> bool;
234}
235
236#[derive(Debug, Clone)]
238pub struct ServiceWaker(Arc<Notify>);
239
240impl ServiceWaker {
241 pub fn wake(&self) {
242 self.0.notify_one();
243 }
244}
245
246struct Slot {
247 service: Arc<dyn Service>,
248 schedule: Schedule,
249 last_run: Option<Instant>,
250 runs: u64,
251 running: Arc<AtomicBool>,
252 failures: Arc<AtomicU32>,
253}
254
255type InFlight = Arc<Mutex<HashMap<(usize, u64), (String, Option<Instant>)>>>;
258
259#[derive(Clone, Copy)]
262struct WallClock {
263 started: Instant,
264 wall_at_start: Duration,
265}
266
267impl WallClock {
268 fn now() -> Self {
269 Self {
270 started: Instant::now(),
271 wall_at_start: SystemTime::now()
272 .duration_since(UNIX_EPOCH)
273 .unwrap_or_default(),
274 }
275 }
276
277 fn wall(&self, at: Instant) -> u64 {
279 (self.wall_at_start + at.saturating_duration_since(self.started)).as_secs()
280 }
281}
282
283fn last_daily(wall: u64, hour: u8, minute: u8) -> u64 {
286 const DAY: u64 = 86_400;
287 let at = u64::from(hour) * 3600 + u64::from(minute) * 60;
288 let today = wall - wall % DAY + at;
289 if today <= wall {
290 today
291 } else {
292 today.saturating_sub(DAY)
293 }
294}
295
296pub struct ServiceHost {
305 slots: Vec<Slot>,
306 tick: Duration,
307 permits: Arc<Semaphore>,
308 gate: Option<Arc<dyn ServiceGate>>,
309 observer: Option<Arc<dyn ServiceObserver>>,
310 wake: Arc<Notify>,
311 grace: Duration,
312}
313
314impl ServiceHost {
315 pub fn new(tick: Duration) -> Self {
317 Self {
318 slots: Vec::new(),
319 tick,
320 permits: Arc::new(Semaphore::new(Semaphore::MAX_PERMITS)),
321 gate: None,
322 observer: None,
323 wake: Arc::new(Notify::new()),
324 grace: Duration::from_secs(10),
325 }
326 }
327
328 pub fn max_concurrent(mut self, limit: usize) -> Self {
330 self.permits = Arc::new(Semaphore::new(limit.max(1)));
331 self
332 }
333
334 pub fn grace(mut self, grace: Duration) -> Self {
336 self.grace = grace;
337 self
338 }
339
340 pub fn gate(mut self, gate: Arc<dyn ServiceGate>) -> Self {
341 self.gate = Some(gate);
342 self
343 }
344
345 pub fn observer(mut self, observer: Arc<dyn ServiceObserver>) -> Self {
346 self.observer = Some(observer);
347 self
348 }
349
350 pub fn service(mut self, service: Arc<dyn Service>) -> Self {
351 self.slots.push(Slot {
352 schedule: service.schedule(),
353 service,
354 last_run: None,
355 runs: 0,
356 running: Arc::new(AtomicBool::new(false)),
357 failures: Arc::new(AtomicU32::new(0)),
358 });
359 self
360 }
361
362 pub fn waker(&self) -> ServiceWaker {
363 ServiceWaker(self.wake.clone())
364 }
365
366 pub async fn run(mut self, shutdown: CancellationToken) {
369 let ctx = ServiceContext {
370 shutdown,
371 run: 0,
372 failures: 0,
373 };
374 for slot in &self.slots {
375 if let Err(error) = slot.service.start(&ctx).await {
376 self.emit(ServiceEvent::StartFailed {
377 service: slot.service.name().to_string(),
378 error: error.0,
379 });
380 }
381 }
382
383 let clock = WallClock::now();
384 let in_flight: InFlight = Arc::default();
385 let mut runs = JoinSet::new();
386 while !ctx.shutdown.is_cancelled() {
387 let ready = match &self.gate {
388 Some(gate) => gate.ready().await,
389 None => true,
390 };
391 if ready {
392 self.launch_due(&ctx, clock, &in_flight, &mut runs);
393 }
394 while runs.try_join_next().is_some() {}
395 tokio::select! {
396 _ = tokio::time::sleep(self.tick) => {}
397 _ = self.wake.notified() => {}
398 _ = ctx.shutdown.cancelled() => {}
399 }
400 }
401
402 let drained = tokio::time::timeout(self.grace, async {
403 while runs.join_next().await.is_some() {}
404 })
405 .await;
406 if drained.is_err() {
407 runs.shutdown().await;
408 let now = Instant::now();
411 let mut left: Vec<_> = in_flight
412 .lock()
413 .expect("in-flight runs poisoned")
414 .drain()
415 .collect();
416 left.sort_by_key(|((slot, run), _)| (*slot, *run));
417 for ((_, run), (service, began)) in left {
418 let (outcome, elapsed) = match began {
419 Some(began) => (ServiceRunEnd::Aborted, now - began),
420 None => (ServiceRunEnd::Skipped, Duration::ZERO),
421 };
422 self.emit(ServiceEvent::Ended {
423 service,
424 run,
425 outcome,
426 elapsed,
427 });
428 }
429 }
430 for slot in &self.slots {
431 slot.service.stop().await;
432 }
433 }
434
435 fn emit(&self, event: ServiceEvent) {
436 if let Some(observer) = &self.observer {
437 observer.event(event);
438 }
439 }
440
441 fn launch_due(
442 &mut self,
443 ctx: &ServiceContext,
444 clock: WallClock,
445 in_flight: &InFlight,
446 runs: &mut JoinSet<()>,
447 ) {
448 let now = Instant::now();
449 let tick = self.tick;
450 for index in 0..self.slots.len() {
451 let slot = &mut self.slots[index];
452 if slot.running.load(Ordering::Relaxed) || !is_due(slot, tick, now, clock) {
453 continue;
454 }
455 slot.last_run = Some(now);
456 slot.runs += 1;
457 slot.running.store(true, Ordering::Relaxed);
458 let run = Run {
459 service: slot.service.clone(),
460 ctx: ServiceContext {
461 shutdown: ctx.shutdown.clone(),
462 run: slot.runs,
463 failures: slot.failures.load(Ordering::Relaxed),
464 },
465 permits: slot.schedule.takes_a_permit().then(|| self.permits.clone()),
466 running: slot.running.clone(),
467 failures: slot.failures.clone(),
468 observer: self.observer.clone(),
469 in_flight: in_flight.clone(),
470 key: (index, slot.runs),
471 name: slot.service.name().to_string(),
472 };
473 in_flight
474 .lock()
475 .expect("in-flight runs poisoned")
476 .insert(run.key, (run.name.clone(), None));
477 let launched = ServiceEvent::Launched {
478 service: run.name.clone(),
479 run: run.key.1,
480 };
481 self.emit(launched);
482 runs.spawn(run_once(run));
483 }
484 }
485}
486
487fn is_due(slot: &Slot, tick: Duration, now: Instant, clock: WallClock) -> bool {
488 if let Schedule::DailyUtc { hour, minute } = slot.schedule {
489 let since = clock.wall(slot.last_run.unwrap_or(clock.started));
492 let moment = last_daily(clock.wall(now), hour, minute);
493 return moment > since;
494 }
495 let interval = match slot.schedule {
496 Schedule::Every(interval) => interval,
497 _ => tick,
498 };
499 let Some(last) = slot.last_run else {
500 return true;
501 };
502 let failures = slot.failures.load(Ordering::Relaxed);
503 let wait = match (slot.schedule, failures) {
504 (Schedule::EveryTick, 0) | (Schedule::Continuous, 0) => Duration::ZERO,
505 (_, 0) => interval,
506 (_, failures) => interval * 2u32.pow(failures.min(MAX_BACKOFF_DOUBLINGS)),
507 };
508 now.duration_since(last) >= wait
509}
510
511struct Run {
513 service: Arc<dyn Service>,
514 ctx: ServiceContext,
515 permits: Option<Arc<Semaphore>>,
516 running: Arc<AtomicBool>,
517 failures: Arc<AtomicU32>,
518 observer: Option<Arc<dyn ServiceObserver>>,
519 in_flight: InFlight,
520 key: (usize, u64),
521 name: String,
522}
523
524impl Run {
525 fn end(&self, outcome: ServiceRunEnd, elapsed: Duration) {
528 self.in_flight
529 .lock()
530 .expect("in-flight runs poisoned")
531 .remove(&self.key);
532 if let Some(observer) = &self.observer {
533 observer.event(ServiceEvent::Ended {
534 service: self.name.clone(),
535 run: self.key.1,
536 outcome,
537 elapsed,
538 });
539 }
540 }
541}
542
543async fn run_once(run: Run) {
544 let _permit = match &run.permits {
545 Some(permits) => tokio::select! {
546 permit = permits.clone().acquire_owned() => permit.ok(),
547 _ = run.ctx.shutdown.cancelled() => {
548 run.running.store(false, Ordering::Relaxed);
549 run.end(ServiceRunEnd::Skipped, Duration::ZERO);
550 return;
551 }
552 },
553 None => None,
554 };
555 let began = Instant::now();
556 if let Some(entry) = run
557 .in_flight
558 .lock()
559 .expect("in-flight runs poisoned")
560 .get_mut(&run.key)
561 {
562 entry.1 = Some(began);
563 }
564 let result = AssertUnwindSafe(run.service.run(&run.ctx))
565 .catch_unwind()
566 .await;
567 let elapsed = began.elapsed();
568 run.running.store(false, Ordering::Relaxed);
569 let failed = |error: String| ServiceRunEnd::Failed {
570 failures: run.failures.fetch_add(1, Ordering::Relaxed) + 1,
571 error,
572 };
573 let outcome = match result {
574 Ok(Ok(())) => ServiceRunEnd::Succeeded {
575 previous_failures: run.failures.swap(0, Ordering::Relaxed),
576 },
577 Ok(Err(error)) => failed(error.0),
578 Err(_) => failed("the service panicked".to_string()),
579 };
580 run.end(outcome, elapsed);
581}
582
583#[cfg(test)]
584mod tests {
585 use super::*;
586 use std::sync::atomic::AtomicUsize;
587
588 const TICK: Duration = Duration::from_secs(1);
589
590 fn counted(
591 schedule: Schedule,
592 result: impl Fn(usize) -> Result<(), ServiceError> + Send + Sync + 'static,
593 ) -> (Arc<dyn Service>, Arc<AtomicUsize>) {
594 let count = Arc::new(AtomicUsize::new(0));
595 let runs = count.clone();
596 let result = Arc::new(result);
597 let service = FnService::new("synthetic", schedule, move || {
598 let n = runs.fetch_add(1, Ordering::SeqCst);
599 let result = result.clone();
600 async move { result(n) }
601 });
602 (Arc::new(service), count)
603 }
604
605 async fn run_for(host: ServiceHost, length: Duration) {
607 let shutdown = CancellationToken::new();
608 let stopping = shutdown.clone();
609 let handle = tokio::spawn(host.run(shutdown));
610 tokio::time::sleep(length).await;
611 stopping.cancel();
612 handle.await.unwrap();
613 }
614
615 #[tokio::test(start_paused = true)]
616 async fn runs_at_once_then_at_its_interval() {
617 let (service, count) = counted(Schedule::Every(Duration::from_secs(10)), |_| Ok(()));
618 run_for(
619 ServiceHost::new(TICK).service(service),
620 Duration::from_millis(9_500),
621 )
622 .await;
623 assert_eq!(count.load(Ordering::SeqCst), 1);
624
625 let (service, count) = counted(Schedule::Every(Duration::from_secs(10)), |_| Ok(()));
626 run_for(
627 ServiceHost::new(TICK).service(service),
628 Duration::from_millis(10_500),
629 )
630 .await;
631 assert_eq!(count.load(Ordering::SeqCst), 2);
632 }
633
634 #[tokio::test(start_paused = true)]
635 async fn every_tick_runs_each_tick_and_on_wake() {
636 let (service, count) = counted(Schedule::EveryTick, |_| Ok(()));
637 run_for(
638 ServiceHost::new(TICK).service(service),
639 Duration::from_millis(3_500),
640 )
641 .await;
642 assert_eq!(count.load(Ordering::SeqCst), 4);
643
644 let (service, count) = counted(Schedule::EveryTick, |_| Ok(()));
645 let host = ServiceHost::new(Duration::from_secs(1000)).service(service);
646 let waker = host.waker();
647 let shutdown = CancellationToken::new();
648 let handle = tokio::spawn(host.run(shutdown.clone()));
649 tokio::time::sleep(Duration::from_millis(10)).await;
650 waker.wake();
651 tokio::time::sleep(Duration::from_millis(10)).await;
652 shutdown.cancel();
653 handle.await.unwrap();
654 assert_eq!(count.load(Ordering::SeqCst), 2);
655 }
656
657 #[tokio::test(start_paused = true)]
658 async fn a_slow_run_never_overlaps_itself() {
659 let active = Arc::new(AtomicUsize::new(0));
660 let worst = Arc::new(AtomicUsize::new(0));
661 let (a, w) = (active.clone(), worst.clone());
662 let service = FnService::new("slow", Schedule::EveryTick, move || {
663 let (a, w) = (a.clone(), w.clone());
664 async move {
665 w.fetch_max(a.fetch_add(1, Ordering::SeqCst) + 1, Ordering::SeqCst);
666 tokio::time::sleep(Duration::from_secs(5)).await;
667 a.fetch_sub(1, Ordering::SeqCst);
668 Ok(())
669 }
670 });
671 run_for(
672 ServiceHost::new(TICK).service(Arc::new(service)),
673 Duration::from_secs(20),
674 )
675 .await;
676 assert_eq!(worst.load(Ordering::SeqCst), 1);
677 }
678
679 #[tokio::test(start_paused = true)]
680 async fn failures_back_off_and_a_success_resets() {
681 let (service, count) = counted(Schedule::Every(Duration::from_secs(10)), |n| {
683 if n < 2 {
684 Err(ServiceError::new("synthetic"))
685 } else {
686 Ok(())
687 }
688 });
689 run_for(
690 ServiceHost::new(TICK).service(service),
691 Duration::from_millis(19_500),
692 )
693 .await;
694 assert_eq!(count.load(Ordering::SeqCst), 1, "still backing off");
695
696 let (service, count) = counted(Schedule::Every(Duration::from_secs(10)), |n| {
697 if n < 2 {
698 Err(ServiceError::new("synthetic"))
699 } else {
700 Ok(())
701 }
702 });
703 run_for(
704 ServiceHost::new(TICK).service(service),
705 Duration::from_millis(70_500),
706 )
707 .await;
708 assert_eq!(count.load(Ordering::SeqCst), 4);
710 }
711
712 #[derive(Default)]
713 struct Recorded(Mutex<Vec<ServiceEvent>>);
714
715 impl ServiceObserver for Recorded {
716 fn event(&self, event: ServiceEvent) {
717 self.0.lock().unwrap().push(event);
718 }
719 }
720
721 #[tokio::test(start_paused = true)]
722 async fn a_panic_is_a_failure_and_the_host_survives() {
723 let (service, count) = counted(Schedule::EveryTick, |n| {
724 assert!(n > 0, "synthetic panic");
725 Ok(())
726 });
727 let seen = Arc::new(Recorded::default());
728 let host = ServiceHost::new(TICK)
729 .observer(seen.clone())
730 .service(service);
731 run_for(host, Duration::from_millis(2_500)).await;
732 assert_eq!(count.load(Ordering::SeqCst), 2);
733 let events = seen.0.lock().unwrap();
734 assert!(events.iter().any(|e| matches!(
735 e,
736 ServiceEvent::Ended {
737 outcome: ServiceRunEnd::Failed { failures: 1, error },
738 ..
739 } if error.contains("panicked")
740 )));
741 assert!(events.iter().any(|e| matches!(
742 e,
743 ServiceEvent::Ended {
744 outcome: ServiceRunEnd::Succeeded {
745 previous_failures: 1
746 },
747 ..
748 }
749 )));
750 }
751
752 struct Closed;
753
754 #[async_trait]
755 impl ServiceGate for Closed {
756 async fn ready(&self) -> bool {
757 false
758 }
759 }
760
761 #[tokio::test(start_paused = true)]
762 async fn a_closed_gate_launches_nothing() {
763 let (service, count) = counted(Schedule::EveryTick, |_| Ok(()));
764 let host = ServiceHost::new(TICK)
765 .gate(Arc::new(Closed))
766 .service(service);
767 run_for(host, Duration::from_secs(5)).await;
768 assert_eq!(count.load(Ordering::SeqCst), 0);
769 }
770
771 #[tokio::test(start_paused = true)]
772 async fn the_limit_binds_every_services_but_not_cycle_work() {
773 let held = |name: &'static str, schedule, seen: Arc<AtomicUsize>| {
774 Arc::new(FnService::new(name, schedule, move || {
775 let seen = seen.clone();
776 async move {
777 seen.fetch_add(1, Ordering::SeqCst);
778 tokio::time::sleep(Duration::from_secs(100)).await;
779 Ok(())
780 }
781 }))
782 };
783 let periodic = Arc::new(AtomicUsize::new(0));
784 let cycle = Arc::new(AtomicUsize::new(0));
785 let every = Schedule::Every(Duration::from_secs(1000));
786 let host = ServiceHost::new(TICK)
787 .max_concurrent(1)
788 .grace(Duration::ZERO)
789 .service(held("a", every, periodic.clone()))
790 .service(held("b", every, periodic.clone()))
791 .service(held("cycle", Schedule::EveryTick, cycle.clone()));
792 run_for(host, Duration::from_secs(5)).await;
793 assert_eq!(periodic.load(Ordering::SeqCst), 1);
794 assert_eq!(cycle.load(Ordering::SeqCst), 1);
795 }
796
797 #[tokio::test(start_paused = true)]
798 async fn continuous_work_restarts_when_it_ends() {
799 let (service, count) = counted(Schedule::Continuous, |_| Ok(()));
800 run_for(
801 ServiceHost::new(TICK).service(service),
802 Duration::from_millis(2_500),
803 )
804 .await;
805 assert_eq!(count.load(Ordering::SeqCst), 3);
806 }
807
808 struct Lifecycle(Arc<Mutex<Vec<&'static str>>>);
809
810 #[async_trait]
811 impl Service for Lifecycle {
812 fn name(&self) -> &str {
813 "lifecycle"
814 }
815 fn schedule(&self) -> Schedule {
816 Schedule::Continuous
817 }
818 async fn start(&self, _ctx: &ServiceContext) -> Result<(), ServiceError> {
819 self.0.lock().unwrap().push("start");
820 Ok(())
821 }
822 async fn run(&self, ctx: &ServiceContext) -> Result<(), ServiceError> {
823 self.0.lock().unwrap().push("run");
824 ctx.shutdown().cancelled().await;
825 self.0.lock().unwrap().push("drained");
826 Ok(())
827 }
828 async fn stop(&self) {
829 self.0.lock().unwrap().push("stop");
830 }
831 }
832
833 #[tokio::test(start_paused = true)]
834 async fn shutdown_drains_then_stops() {
835 let order = Arc::new(Mutex::new(Vec::new()));
836 let host = ServiceHost::new(TICK).service(Arc::new(Lifecycle(order.clone())));
837 run_for(host, Duration::from_secs(1)).await;
838 assert_eq!(*order.lock().unwrap(), ["start", "run", "drained", "stop"]);
839 }
840
841 #[tokio::test(start_paused = true)]
842 async fn a_run_that_ignores_shutdown_is_aborted_after_the_grace() {
843 let service = FnService::new("stubborn", Schedule::Continuous, || async {
844 std::future::pending::<()>().await;
845 Ok(())
846 });
847 let host = ServiceHost::new(TICK)
848 .grace(Duration::from_secs(2))
849 .service(Arc::new(service));
850 let shutdown = CancellationToken::new();
851 let handle = tokio::spawn(host.run(shutdown.clone()));
852 tokio::time::sleep(Duration::from_millis(100)).await;
853 shutdown.cancel();
854 let started = Instant::now();
855 handle.await.unwrap();
856 assert_eq!(started.elapsed(), Duration::from_secs(2));
857 }
858
859 fn by_run(events: &[ServiceEvent]) -> Vec<(u64, String)> {
861 events
862 .iter()
863 .filter_map(|event| match event {
864 ServiceEvent::Launched { run, .. } => Some((*run, "launched".to_string())),
865 ServiceEvent::Ended {
866 run,
867 outcome,
868 elapsed,
869 ..
870 } => Some((*run, format!("{outcome:?} after {}ms", elapsed.as_millis()))),
871 _ => None,
872 })
873 .collect()
874 }
875
876 #[tokio::test(start_paused = true)]
877 async fn every_launch_ends_once_with_its_number_and_time() {
878 let numbers = Arc::new(Mutex::new(Vec::new()));
879 struct Timed(Arc<Mutex<Vec<(u64, u32)>>>);
880 #[async_trait]
881 impl Service for Timed {
882 fn name(&self) -> &str {
883 "timed"
884 }
885 fn schedule(&self) -> Schedule {
886 Schedule::Every(Duration::from_secs(10))
887 }
888 async fn run(&self, ctx: &ServiceContext) -> Result<(), ServiceError> {
889 self.0.lock().unwrap().push((ctx.run(), ctx.failures()));
890 tokio::time::sleep(Duration::from_millis(50)).await;
891 if ctx.run() == 1 {
892 Err(ServiceError::new("synthetic"))
893 } else {
894 Ok(())
895 }
896 }
897 }
898 let seen = Arc::new(Recorded::default());
899 let host = ServiceHost::new(TICK)
900 .observer(seen.clone())
901 .service(Arc::new(Timed(numbers.clone())));
902 run_for(host, Duration::from_millis(25_000)).await;
903 assert_eq!(*numbers.lock().unwrap(), [(1, 0), (2, 1)]);
904 assert_eq!(
905 by_run(&seen.0.lock().unwrap()),
906 [
907 (1, "launched".to_string()),
908 (
909 1,
910 "Failed { failures: 1, error: \"synthetic\" } after 50ms".to_string()
911 ),
912 (2, "launched".to_string()),
913 (
914 2,
915 "Succeeded { previous_failures: 1 } after 50ms".to_string()
916 ),
917 ]
918 );
919 }
920
921 #[tokio::test(start_paused = true)]
922 async fn a_run_aborted_at_shutdown_still_ends() {
923 let stubborn = FnService::new("stubborn", Schedule::Continuous, || async {
924 std::future::pending::<()>().await;
925 Ok(())
926 });
927 let waiting = FnService::new("waiting", Schedule::Every(TICK), || async { Ok(()) });
928 let holder = FnService::new("holder", Schedule::Every(TICK), || async {
929 std::future::pending::<()>().await;
930 Ok(())
931 });
932 let seen = Arc::new(Recorded::default());
933 let host = ServiceHost::new(TICK)
934 .max_concurrent(1)
935 .grace(Duration::from_secs(2))
936 .observer(seen.clone())
937 .service(Arc::new(stubborn))
938 .service(Arc::new(holder))
939 .service(Arc::new(waiting));
940 run_for(host, Duration::from_millis(500)).await;
941 let events = seen.0.lock().unwrap();
942 let ends: Vec<_> = events
943 .iter()
944 .filter_map(|event| match event {
945 ServiceEvent::Ended {
946 service, outcome, ..
947 } => Some((service.as_str(), outcome.clone())),
948 _ => None,
949 })
950 .collect();
951 let launched = events
952 .iter()
953 .filter(|event| matches!(event, ServiceEvent::Launched { .. }))
954 .count();
955 assert_eq!(launched, 3);
956 assert_eq!(
957 ends,
958 [
959 ("waiting", ServiceRunEnd::Skipped),
960 ("stubborn", ServiceRunEnd::Aborted),
961 ("holder", ServiceRunEnd::Aborted),
962 ]
963 );
964 }
965
966 #[test]
967 fn the_last_daily_moment_is_today_or_yesterday() {
968 let day = 86_400;
969 let noon = 10 * day + 12 * 3600;
970 assert_eq!(last_daily(noon, 2, 0), 10 * day + 2 * 3600);
971 assert_eq!(last_daily(noon, 23, 30), 9 * day + 23 * 3600 + 1800);
972 assert_eq!(last_daily(noon, 12, 0), noon);
973 assert_eq!(Schedule::daily_utc(24, 0), None);
974 assert_eq!(
975 Schedule::daily_utc(2, 59),
976 Some(Schedule::DailyUtc {
977 hour: 2,
978 minute: 59
979 })
980 );
981 }
982
983 #[tokio::test(start_paused = true)]
984 async fn a_daily_service_runs_once_a_day_at_its_time() {
985 let wall = SystemTime::now()
987 .duration_since(UNIX_EPOCH)
988 .unwrap()
989 .as_secs()
990 + 120;
991 let (hour, minute) = (((wall % 86_400) / 3600) as u8, ((wall % 3600) / 60) as u8);
992 let (service, count) = counted(Schedule::DailyUtc { hour, minute }, |_| Ok(()));
993 let host = ServiceHost::new(Duration::from_secs(30)).service(service);
994 let shutdown = CancellationToken::new();
995 let handle = tokio::spawn(host.run(shutdown.clone()));
996 tokio::time::sleep(Duration::from_secs(1)).await;
997 assert_eq!(count.load(Ordering::SeqCst), 0, "not at start");
998 tokio::time::sleep(Duration::from_secs(125)).await;
999 assert_eq!(count.load(Ordering::SeqCst), 1, "at its time");
1000 tokio::time::sleep(Duration::from_secs(3600)).await;
1001 assert_eq!(count.load(Ordering::SeqCst), 1, "once");
1002 tokio::time::sleep(Duration::from_secs(86_400)).await;
1003 assert_eq!(count.load(Ordering::SeqCst), 2, "next day");
1004 shutdown.cancel();
1005 handle.await.unwrap();
1006 }
1007}