Skip to main content

aidaemon_core/
service.rs

1//! Background work an application runs beside its agents.
2//!
3//! A [`Service`] states when it runs; a [`ServiceHost`] runs it. The host
4//! gives every service the same treatment: one run at a time, backoff after
5//! failures, a panic counted as a failure, and a bounded drain on shutdown.
6//!
7//! An agent run started from a service is built with [`crate::AgentBuilder`]
8//! like any other, so it carries the same safeguards.
9//!
10//! How the host schedules, exactly:
11//!
12//! - [`Schedule::Every`] is measured from one launch to the next, not from
13//!   the end of a run. A service never overlaps itself: a run still going
14//!   when the next is due delays it.
15//! - After a failure (an `Err` or a panic) the wait is the interval doubled
16//!   per failure in a row, up to 2^5 times; a success resets it.
17//! - [`Schedule::DailyUtc`] runs once a day at a wall-clock time, in UTC,
18//!   counted on the runtime's clock from the host's start (so paused Tokio
19//!   time in a test moves it too). A failed run waits for the next day.
20//! - The host looks for due work every `tick` and on [`ServiceWaker::wake`],
21//!   so a run starts up to one tick late.
22//! - [`ServiceHost::run`] consumes the host: add every service before it
23//!   starts.
24//! - [`ServiceHost::gate`] is asked before each tick's launches; while it
25//!   says no, nothing new starts (runs already going continue).
26//!
27//! Every launch gets one [`ServiceEvent::Launched`] and exactly one
28//! [`ServiceEvent::Ended`], with the run's number, how it ended
29//! ([`ServiceRunEnd`]: succeeded, failed, aborted at shutdown, or skipped
30//! because the host stopped before it began) and how long it ran, on
31//! Tokio's clock. The run's [`ServiceContext`] carries the same number, to
32//! tie the agent runs it starts to it.
33
34use 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
48/// Most doublings of a failing service's interval.
49const MAX_BACKOFF_DOUBLINGS: u32 = 5;
50
51/// When a service runs (see [`ServiceHost`] for the exact rules).
52#[derive(Debug, Clone, Copy, PartialEq, Eq)]
53#[non_exhaustive]
54pub enum Schedule {
55    /// At most this often, measured from launch to launch; the first run is
56    /// at once. Runs share the host's concurrency limit.
57    Every(Duration),
58    /// On every tick and wake-up, for cycle work that must not wait behind
59    /// [`Schedule::Every`] services.
60    EveryTick,
61    /// Long-lived work, started once and restarted if it ends.
62    Continuous,
63    /// Once a day at `hour:minute` UTC, the first time at the next such
64    /// moment after the host starts. Runs share the host's concurrency
65    /// limit.
66    DailyUtc { hour: u8, minute: u8 },
67}
68
69impl Schedule {
70    /// [`Schedule::DailyUtc`], or `None` for a time that does not exist.
71    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/// Why a service's run failed.
81#[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/// What a service can see of its host and of the run it is in.
92#[derive(Debug, Clone)]
93pub struct ServiceContext {
94    shutdown: CancellationToken,
95    run: u64,
96    failures: u32,
97}
98
99impl ServiceContext {
100    /// Cancelled when the host stops. Long runs should watch it.
101    pub fn shutdown(&self) -> &CancellationToken {
102        &self.shutdown
103    }
104
105    /// This run's number: 1 for the service's first run, then one more per
106    /// launch, the same number its [`ServiceEvent`]s carry. 0 in
107    /// [`Service::start`]. To tie an agent run to it, start the agent from
108    /// a state you made, whose id you know:
109    ///
110    /// ```no_run
111    /// # async fn demo(agent: aidaemon_core::Agent, ctx: &aidaemon_core::ServiceContext) {
112    /// let state = aidaemon_core::RunState::new(
113    ///     agent.id(),
114    ///     &format!("service:nightly:{}", ctx.run()),
115    ///     "Write the nightly report",
116    /// );
117    /// let run_id = state.run_id; // every Event of the run carries it
118    /// let outcome = agent.run_from(state, ctx.shutdown().child_token()).await;
119    /// # let _ = (run_id, outcome);
120    /// # }
121    /// ```
122    pub fn run(&self) -> u64 {
123        self.run
124    }
125
126    /// How many runs in a row failed just before this one.
127    pub fn failures(&self) -> u32 {
128        self.failures
129    }
130}
131
132/// Work a [`ServiceHost`] runs in the background.
133#[async_trait]
134pub trait Service: Send + Sync + 'static {
135    fn name(&self) -> &str;
136    fn schedule(&self) -> Schedule;
137
138    /// Once, before any service's first run. A failure is reported and the
139    /// service still runs.
140    async fn start(&self, _ctx: &ServiceContext) -> Result<(), ServiceError> {
141        Ok(())
142    }
143
144    async fn run(&self, ctx: &ServiceContext) -> Result<(), ServiceError>;
145
146    /// Once, after the host has drained.
147    async fn stop(&self) {}
148}
149
150/// A [`Service`] from a closure.
151pub 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/// What happened to a service. Every [`ServiceEvent::Launched`] is
191/// followed by exactly one [`ServiceEvent::Ended`] with the same `run`.
192#[derive(Debug, Clone, PartialEq, Eq)]
193#[non_exhaustive]
194pub enum ServiceEvent {
195    /// A run was launched.
196    Launched { service: String, run: u64 },
197    /// A run ended, however it ended. `elapsed` is how long it ran, on
198    /// Tokio's clock (zero for a run that never began).
199    Ended {
200        service: String,
201        run: u64,
202        outcome: ServiceRunEnd,
203        elapsed: Duration,
204    },
205    /// `start` failed.
206    StartFailed { service: String, error: String },
207}
208
209/// How one run of a service ended.
210#[derive(Debug, Clone, PartialEq, Eq)]
211#[non_exhaustive]
212pub enum ServiceRunEnd {
213    /// `previous_failures` is the streak it ended.
214    Succeeded { previous_failures: u32 },
215    /// It returned an error or panicked. `failures` counts the streak.
216    Failed { failures: u32, error: String },
217    /// Still going when the host's grace period ran out, so it was
218    /// aborted. Neither a success nor a failure.
219    Aborted,
220    /// The host stopped while the run waited for a concurrency permit, so
221    /// it never began.
222    Skipped,
223}
224
225/// Receives every [`ServiceEvent`], for logs and dashboards.
226pub trait ServiceObserver: Send + Sync {
227    fn event(&self, event: ServiceEvent);
228}
229
230/// Decides whether a tick launches anything.
231#[async_trait]
232pub trait ServiceGate: Send + Sync {
233    async fn ready(&self) -> bool;
234}
235
236/// Ends the host's wait for the next tick.
237#[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
255/// Runs launched and not yet ended: their service, number and when they
256/// began, so a host that aborts them can still end each one.
257type InFlight = Arc<Mutex<HashMap<(usize, u64), (String, Option<Instant>)>>>;
258
259/// The wall clock as the runtime's clock moves: UTC at the host's start
260/// plus Tokio time since.
261#[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    /// Seconds since the Unix epoch at `at`.
278    fn wall(&self, at: Instant) -> u64 {
279        (self.wall_at_start + at.saturating_duration_since(self.started)).as_secs()
280    }
281}
282
283/// The latest `hour:minute` UTC at or before `wall` (seconds since the
284/// epoch).
285fn 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
296/// Runs [`Service`]s until told to stop.
297///
298/// The rules it schedules by: [`Every`](Schedule::Every) counts from launch
299/// to launch, a service never overlaps itself, a failure doubles the wait
300/// per failure in a row (up to 2^5, reset by a success),
301/// [`DailyUtc`](Schedule::DailyUtc) runs once a day at its UTC time (a
302/// failed run waits for the next day), due work starts on the next tick or
303/// wake-up, and every launch ends with exactly one [`ServiceEvent::Ended`].
304pub 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    /// A host that looks for due work every `tick`.
316    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    /// At most `limit` [`Schedule::Every`] runs at once.
329    pub fn max_concurrent(mut self, limit: usize) -> Self {
330        self.permits = Arc::new(Semaphore::new(limit.max(1)));
331        self
332    }
333
334    /// How long a stopping host waits for runs to end before aborting them.
335    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    /// Run until `shutdown` is cancelled, then stop launching, drain for the
367    /// grace period, abort what is left and call each service's `stop`.
368    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            // Every task has stopped: what is left in flight was aborted
409            // (or never began) and gets its one end here.
410            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        // Due once the day's moment has passed since the last run (or the
490        // host's start).
491        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
511/// One launched run and what it reports to.
512struct 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    /// End the run: leave the in-flight set and report, with no await in
526    /// between, so an abort can never end it a second time.
527    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    /// Run `host` for `length` of paused time, then stop it.
606    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        // Fails twice: runs at 0, then +20s (2x), then +40s (4x), then ok.
682        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        // 0, 20, 60, then the interval again: 70.
709        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    /// Each run's events, in order, as (run, what).
860    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        // Due in one to two minutes (UTC), then once a day.
986        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}