Skip to main content

apalis_core/monitor/
mod.rs

1//! # Monitor
2//!
3//! `Monitor` provides centralized coordination and lifecycle management for multiple workers.
4//! It is responsible for executing, monitoring, and gracefully shutting down all registered workers in a robust and customizable manner.
5//!
6//! ## Features
7//!
8//! - Register and run one or more workers.
9//! - Handle graceful shutdown with optional timeout.
10//! - Register custom event handlers to observe worker events (e.g. task received, completed, errored).
11//! - Integrate shutdown with system signals (e.g. `SIGINT`, `SIGTERM`) or custom triggers.
12//! - **Restart Strategy:** Configure custom logic to automatically restart workers on failure.
13//!
14//! ## Usage
15//!
16//! ```rust,no_run
17//! # use apalis_core::monitor::Monitor;
18//! # use apalis_core::worker::builder::WorkerBuilder;
19//! # use apalis_core::backend::memory::MemoryStorage;
20//! # use apalis_core::task::Task;
21//! # use apalis_core::backend::TaskSink;
22//! use tower::service_fn;
23//! # use std::time::Duration;
24//!
25//! #[tokio::main]
26//! async fn main() {
27//!
28//!     async fn task(req: u32) -> Result<u32, std::io::Error> {
29//!         println!("Processing task: {:?}", req);
30//!         Ok::<_, std::io::Error>(req)
31//!     }
32//!
33//!     let monitor = Monitor::new()
34//!         .on_event(|worker, event| println!("{}: {:?}", worker.name(), event))
35//!         .register(move |_| {
36//!             WorkerBuilder::new("demo-worker")
37//!                 .backend(MemoryStorage::new())
38//!                 .build(task)
39//!          });
40//!
41//!     // Start monitor and run all registered workers
42//!     monitor.run().await.unwrap();
43//! }
44//! ```
45//!
46//! ## Graceful Shutdown with Timeout
47//!
48//! To force shutdown after a certain duration, use the `shutdown_timeout` method:
49//!
50//! ```ignore
51//! # use apalis_core::monitor::Monitor;
52//! # use std::time::Duration;
53//! let monitor = Monitor::new()
54//!     .shutdown_timeout(Duration::from_secs(10))
55//!     .run_with_signal(signal::ctrl_c())
56//!     .await
57//!     .unwrap();
58//! ```
59//!
60//! This ensures that if any worker hangs or takes too long to finish, the monitor will shut down after 10 seconds.
61//!
62//! ## Restarting Workers on Failure
63//!
64//! You can configure the monitor to restart workers when they fail, using custom logic:
65//!
66//! ```rust
67//! use apalis_core::monitor::Monitor;
68//!
69//! let monitor = Monitor::new()
70//!     .should_restart(|worker, error| {
71//!         let restarts = worker.restarts();
72//!         println!("Worker failed: {error:?}, attempt: {restarts}");
73//!         restarts < 3 // Run up to 3 times
74//!     });
75//! ```
76//!
77//! ## Observing Worker Events
78//!
79//! Register event handlers to observe worker lifecycle events:
80//!
81//! ```rust
82//! use apalis_core::monitor::Monitor;
83//!
84//! let monitor = Monitor::new()
85//!     .on_event(|worker, event| println!("Worker {}: {:?}", worker.name(), event));
86//! ```
87//!
88//! ## Registering Multiple Workers
89//!
90//! You can register multiple workers by building and registering each worker individually.
91//! This is useful when you want to run several workers with the same configuration:
92//!
93//! `rust
94//! # use apalis_core::worker::builder::WorkerBuilder;
95//! # use apalis_core::monitor::Monitor;
96//! # use apalis_core::backend::memory::MemoryStorage;
97//! # async fn task(_: u32) {}
98//! let mut monitor = Monitor::new();
99//!
100//! for index in 0..3 {
101//!     monitor = monitor.register(|restarts|
102//!         WorkerBuilder::new(format!("worker-{index}-run-{restarts}"))
103//!             .backend(MemoryStorage::new())
104//!             .build(task),
105//!     );
106//! }
107//! `.
108//!
109//! ## Example: Full Monitor Usage
110//!
111//! ```rust
112//! # use std::time::Duration;
113//! # use apalis_core::worker::builder::WorkerBuilder;
114//! # use apalis_core::monitor::Monitor;
115//! # use apalis_core::backend::memory::MemoryStorage;
116//! # async fn example() {
117//! # async fn task(_: u32) {}
118//! let monitor = Monitor::new()
119//!     .register(|index|
120//!         WorkerBuilder::new(format!("worker-{index}"))
121//!         .backend(MemoryStorage::new())
122//!         .build(task)
123//!     )
124//!     .should_restart(|wrk, _| wrk.restarts() < 5)
125//!     .on_event(|worker, event| println!("Event: {:?}", event))
126//!     .shutdown_timeout(Duration::from_secs(10));
127//! let ctx = monitor.context();
128//! monitor.run().await.unwrap();
129//! # }
130//! ```
131//!
132//! ## Error Handling
133//!
134//! If any worker fails, the monitor will return a `MonitorError` containing details about the failure.
135//! You can inspect the error to see which workers failed and why.
136//!
137//! [Worker]: crate::worker::Worker
138
139use std::{
140    fmt::{self, Debug, Formatter},
141    pin::Pin,
142    sync::{Arc, RwLock},
143    task::{Context, Poll},
144};
145
146use futures_util::{
147    Future, FutureExt, StreamExt,
148    future::{BoxFuture, Either, Shared},
149    stream::FuturesUnordered,
150};
151use tower_layer::Layer;
152use tower_service::Service;
153
154use crate::{
155    backend::{Backend, BackendConfig, future::BoxSyncFuture},
156    error::{BoxDynError, WorkerError},
157    monitor::{context::MonitorContext, shutdown::Shutdown},
158    task::Task,
159    worker::{
160        Worker,
161        context::WorkerContext,
162        event::{Event, EventHandlerBuilder},
163        lifecycle::LifecycleService,
164    },
165};
166
167pub mod context;
168pub mod shutdown;
169
170type WorkerFactory = Box<
171    dyn Fn(&mut WorkerContext) -> BoxFuture<'static, Result<(), WorkerError>>
172        + 'static
173        + Send
174        + Sync,
175>;
176
177type ShouldRestart =
178    Arc<RwLock<Option<Box<dyn Fn(&WorkerContext, &WorkerError) -> bool + 'static + Send + Sync>>>>;
179
180#[pin_project::pin_project]
181/// A worker that is monitored by the `Monitor`.
182struct MonitoredWorker {
183    factory: WorkerFactory,
184    worker: WorkerContext,
185    #[pin]
186    fut: Option<BoxSyncFuture<Result<(), WorkerError>>>,
187    should_restart: ShouldRestart,
188}
189
190/// Represents errors that occurred in a monitored worker, including its context and the error itself.
191#[derive(Debug)]
192pub struct MonitoredWorkerError {
193    ctx: WorkerContext,
194    error: WorkerError,
195}
196
197impl Future for MonitoredWorker {
198    type Output = Result<(), MonitoredWorkerError>;
199
200    fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
201        use std::panic::{AssertUnwindSafe, catch_unwind};
202
203        loop {
204            let mut this = self.as_mut().project();
205            let worker = this.worker;
206            let name = worker.name().to_owned();
207            debug!(?name, "polling worker");
208
209            // There is no future to poll.
210            if this.fut.is_none() {
211                let fut = (this.factory)(worker);
212                debug!(?name, "created new future");
213                this.fut.set(Some(fut.into()));
214            }
215
216            // Worker is running but shutdown has been called
217            if worker.is_running() && worker.is_shutting_down() {
218                info!(?name, "worker shutting down, stopping");
219                if let Err(err) = worker.stop() {
220                    error!(?name, ?err, "failed to stop worker");
221                    return Poll::Ready(Err(MonitoredWorkerError {
222                        ctx: worker.clone(),
223                        error: err,
224                    }));
225                }
226                continue;
227            }
228
229            let fut = this
230                .fut
231                .as_mut()
232                .get_mut()
233                .as_mut()
234                .expect("future was just set above; this should be unreachable");
235
236            let poll_result =
237                catch_unwind(AssertUnwindSafe(|| fut.poll_unpin(cx))).map_err(|err| {
238                    let err = if let Some(s) = err.downcast_ref::<&str>() {
239                        (*s).to_owned()
240                    } else if let Some(s) = err.downcast_ref::<String>() {
241                        s.clone()
242                    } else {
243                        "Unknown panic".to_owned()
244                    };
245                    WorkerError::PanicError(err)
246                });
247
248            match poll_result {
249                Ok(Poll::Pending) => return Poll::Pending,
250                Ok(Poll::Ready(Ok(()))) => return Poll::Ready(Ok(())),
251                Ok(Poll::Ready(Err(error))) | Err(error) => {
252                    warn!(?name, ?error, "worker future ended with error");
253                    let _fut = this.fut.as_mut().get_mut().take();
254
255                    let should_restart = match this.should_restart.read() {
256                        Ok(guard) => guard,
257                        Err(poison_err) => {
258                            error!(?name, ?poison_err, "should_restart lock poisoned");
259                            return Poll::Ready(Err(MonitoredWorkerError {
260                                ctx: worker.clone(),
261                                error,
262                            }));
263                        }
264                    };
265
266                    match should_restart.as_ref().map(|s| s.as_ref()) {
267                        Some(cb) => {
268                            if !(cb)(worker, &error) {
269                                info!(?name, "restart callback declined restart");
270                                if let Err(stop_err) = worker.stop() {
271                                    error!(?name, ?stop_err, "failed to stop worker");
272                                }
273                                return Poll::Ready(Err(MonitoredWorkerError {
274                                    ctx: worker.clone(),
275                                    error,
276                                }));
277                            }
278                            info!(?name, "restarting worker");
279                            if let Err(restart_err) = worker.restart() {
280                                error!(?name, ?restart_err, "failed to restart worker");
281                                return Poll::Ready(Err(MonitoredWorkerError {
282                                    ctx: worker.clone(),
283                                    error,
284                                }));
285                            }
286                            // Yield before building the restarted worker. Looping straight back
287                            // would let a worker that fails as soon as it starts restart in a
288                            // tight loop inside this one `poll`, starving every other future on
289                            // the task and spending a restart budget in microseconds.
290                            cx.waker().wake_by_ref();
291                            return Poll::Pending;
292                        }
293                        _ => {
294                            return Poll::Ready(Err(MonitoredWorkerError {
295                                ctx: worker.clone(),
296                                error,
297                            }));
298                        }
299                    }
300                }
301            }
302        }
303    }
304}
305
306/// A monitor for coordinating and managing a collection of workers.
307#[derive(Default)]
308pub struct Monitor {
309    workers: Vec<MonitoredWorker>,
310    terminator: Option<Shared<BoxFuture<'static, ()>>>,
311    shutdown: Shutdown,
312    event_handler: EventHandlerBuilder,
313    should_restart: ShouldRestart,
314}
315
316impl Debug for Monitor {
317    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
318        f.debug_struct("Monitor")
319            .field("shutdown", &"[Graceful shutdown listener]")
320            .field("workers", &self.workers.len())
321            .finish()
322    }
323}
324
325impl Monitor {
326    fn run_worker<Args, S, FB, M>(
327        worker: Worker<Args, FB, S, M>,
328    ) -> BoxFuture<'static, Result<(), WorkerError>>
329    where
330        FB: BackendConfig + Backend<Task = Task<FB::Args>> + Send + Unpin + 'static,
331        S: Service<Task<FB::Args>> + Send + 'static,
332        FB::Args: Send + 'static,
333        Args: Send + 'static,
334        FB::Error: Into<BoxDynError> + Send + 'static,
335        M: Layer<LifecycleService<S>> + 'static,
336        FB::Layer: Layer<<M as Layer<LifecycleService<S>>>::Service>,
337        <FB::Layer as Layer<<M as Layer<LifecycleService<S>>>::Service>>::Service:
338            Service<Task<FB::Args>>,
339        <FB::Layer as Layer<<M as Layer<LifecycleService<S>>>::Service>>::Service: Send + 'static,
340        <<FB::Layer as Layer<<M as Layer<LifecycleService<S>>>::Service>>::Service as Service<
341            Task<<FB as BackendConfig>::Args>,
342        >>::Future: Send,
343        <<FB::Layer as Layer<<M as Layer<LifecycleService<S>>>::Service>>::Service as Service<
344            Task<<FB as BackendConfig>::Args>,
345        >>::Error: Into<BoxDynError> + Send + Sync + 'static,
346        <<FB::Layer as Layer<<M as Layer<LifecycleService<S>>>::Service>>::Service as Service<
347            Task<<FB as BackendConfig>::Args>,
348        >>::Response: Send + Sync + 'static,
349    {
350        let mut stream = worker.stream();
351        async move {
352            loop {
353                match stream.next().await {
354                    Some(Err(e)) => return Err(e),
355                    None => return Ok(()),
356                    _ => (),
357                }
358            }
359        }
360        .boxed()
361    }
362    /// Registers a worker into the monitor registry.
363    ///
364    /// # Examples
365    ///
366    /// ```
367    /// use apalis_core::monitor::Monitor;
368    /// # use apalis_core::backend::memory::MemoryStorage;
369    /// # use apalis_core::worker::builder::WorkerBuilder;
370    /// # async fn example() {
371    /// let monitor = Monitor::new();
372    /// monitor
373    /// .register(|restarts| {
374    ///     WorkerBuilder::new("example-worker")
375    ///         .backend(MemoryStorage::new())
376    ///         .build(|args: u32| async {})
377    /// })
378    /// .run()
379    /// .await;
380    /// # }
381    /// ```
382    #[must_use]
383    pub fn register<Args, S, FB, M>(
384        mut self,
385        factory: impl Fn(usize) -> Worker<Args, FB, S, M> + 'static + Send + Sync,
386    ) -> Self
387    where
388        FB: BackendConfig + Backend<Task = Task<FB::Args>> + Send + Unpin + 'static,
389        S: Service<Task<FB::Args>> + Send + 'static,
390        FB::Args: Send + 'static,
391        Args: Send + 'static,
392        FB::Error: Into<BoxDynError> + Send + 'static,
393        M: Layer<LifecycleService<S>> + 'static,
394        FB::Layer: Layer<<M as Layer<LifecycleService<S>>>::Service>,
395        <FB::Layer as Layer<<M as Layer<LifecycleService<S>>>::Service>>::Service:
396            Service<Task<FB::Args>>,
397        <FB::Layer as Layer<<M as Layer<LifecycleService<S>>>::Service>>::Service: Send + 'static,
398        <<FB::Layer as Layer<<M as Layer<LifecycleService<S>>>::Service>>::Service as Service<
399            Task<<FB as BackendConfig>::Args>,
400        >>::Future: Send,
401        <<FB::Layer as Layer<<M as Layer<LifecycleService<S>>>::Service>>::Service as Service<
402            Task<<FB as BackendConfig>::Args>,
403        >>::Error: Into<BoxDynError> + Send + Sync + 'static,
404        <<FB::Layer as Layer<<M as Layer<LifecycleService<S>>>::Service>>::Service as Service<
405            Task<<FB as BackendConfig>::Args>,
406        >>::Response: Send + Sync + 'static,
407    {
408        let shutdown = Some(self.shutdown.clone());
409        let handler = self.event_handler.clone();
410
411        let (fut, worker) = {
412            let mut w = factory(0);
413            let ctx = &mut w.context;
414            ctx.bind_service::<M::Service>();
415            ctx.add_listener(move |ctx, ev| {
416                let handlers = handler.read();
417                if let Ok(handlers) = handlers {
418                    for h in handlers.iter() {
419                        h(ctx, ev);
420                    }
421                }
422            });
423            ctx.shutdown = shutdown;
424            let c = ctx.clone();
425            let fut = Self::run_worker(w).into();
426            (Some(fut), c)
427        };
428
429        let worker = MonitoredWorker {
430            fut,
431            factory: Box::new(move |worker| {
432                let mut new_worker = factory(worker.restarts());
433
434                // Replace current worker name with new name
435                if worker.name().ne(new_worker.context.name()) {
436                    let name = Arc::make_mut(&mut worker.name);
437                    *name = new_worker.context.name().to_owned();
438                }
439
440                // Reuse the current context
441                new_worker.context = worker.clone();
442
443                (Self::run_worker(new_worker)) as _
444            }),
445            worker,
446            should_restart: self.should_restart.clone(),
447        };
448        self.workers.push(worker);
449        self
450    }
451
452    /// Registers N workers into the monitor registry.
453    ///
454    /// # Examples
455    ///
456    /// ```
457    /// use apalis_core::monitor::Monitor;
458    /// # use apalis_core::backend::memory::MemoryStorage;
459    /// # use apalis_core::worker::builder::WorkerBuilder;
460    /// # async fn example() {
461    /// let monitor = Monitor::new();
462    /// monitor
463    /// .register_n(5, |index, restarts| {
464    ///     WorkerBuilder::new("example-worker")
465    ///         .backend(MemoryStorage::new())
466    ///         .build(|_: u32| async {})
467    /// })
468    /// .run()
469    /// .await;
470    /// # }
471    /// ```
472    #[must_use]
473    pub fn register_n<Args, S, FB, M>(
474        mut self,
475        count: usize,
476        factory: impl Fn(usize, usize) -> Worker<Args, FB, S, M> + 'static + Send + Sync,
477    ) -> Self
478    where
479        FB: BackendConfig + Backend<Task = Task<FB::Args>> + Send + Unpin + 'static,
480        S: Service<Task<FB::Args>> + Send + 'static,
481        FB::Args: Send + 'static,
482        Args: Send + 'static,
483        FB::Error: Into<BoxDynError> + Send + 'static,
484        M: Layer<LifecycleService<S>> + 'static,
485        FB::Layer: Layer<<M as Layer<LifecycleService<S>>>::Service>,
486        <FB::Layer as Layer<<M as Layer<LifecycleService<S>>>::Service>>::Service:
487            Service<Task<FB::Args>>,
488        <FB::Layer as Layer<<M as Layer<LifecycleService<S>>>::Service>>::Service: Send + 'static,
489        <<FB::Layer as Layer<<M as Layer<LifecycleService<S>>>::Service>>::Service as Service<
490            Task<<FB as BackendConfig>::Args>,
491        >>::Future: Send,
492        <<FB::Layer as Layer<<M as Layer<LifecycleService<S>>>::Service>>::Service as Service<
493            Task<<FB as BackendConfig>::Args>,
494        >>::Error: Into<BoxDynError> + Send + Sync + 'static,
495        <<FB::Layer as Layer<<M as Layer<LifecycleService<S>>>::Service>>::Service as Service<
496            Task<<FB as BackendConfig>::Args>,
497        >>::Response: Send + Sync + 'static,
498    {
499        let factory = Arc::new(factory);
500        for index in 0..count {
501            let f = factory.clone();
502            self = self.register(move |id| f(index, id));
503        }
504        self
505    }
506
507    /// Runs the monitor and all its registered workers until they have all completed or a shutdown signal is received.
508    ///
509    /// # Arguments
510    ///
511    /// * `signal` - A `Future` that resolves when a shutdown signal is received.
512    ///
513    /// # Errors
514    ///
515    /// Returns [`MonitorError::ShutdownSignal`] if `signal` resolves to an error, otherwise
516    /// [`MonitorError::ExitError`] if any worker exited with an error. Both are reported
517    /// whether or not a shutdown timeout is set.
518    ///
519    /// # Remarks
520    ///
521    /// If a timeout has been set using the `Monitor::shutdown_timeout` method, the monitor
522    /// will wait for all workers to complete up to the timeout duration before exiting.
523    /// If the timeout is reached and workers have not completed, the monitor will exit forcefully.
524    pub async fn run_with_signal<S>(self, signal: S) -> Result<(), MonitorError>
525    where
526        S: Send + Future<Output = std::io::Result<()>>,
527    {
528        let shutdown = self.shutdown.clone();
529        let ctx = self.context();
530        let shutdown_after = async move {
531            let res = signal.await;
532            let _ = ctx.shutdown();
533            res
534        };
535        if let Some(terminator) = self.terminator {
536            let workers = Self::run_all_workers(self.workers, shutdown).boxed();
537            let (workers, signal_error) =
538                match futures_util::future::select(workers, shutdown_after.boxed()).await {
539                    Either::Left((result, _)) => (result, None),
540                    Either::Right((signal_result, workers)) => {
541                        let workers = match futures_util::future::select(workers, terminator).await
542                        {
543                            Either::Left((result, _)) => result,
544                            Either::Right(((), _)) => Ok(()),
545                        };
546                        (workers, signal_result.err())
547                    }
548                };
549            if let Some(error) = signal_error {
550                return Err(MonitorError::ShutdownSignal(error));
551            }
552            workers?;
553        } else {
554            let runner = self.run();
555            let res = futures_util::join!(shutdown_after, runner);
556            match res {
557                (Ok(_), Ok(_)) => {
558                    // All good
559                }
560                (Err(e), Ok(_) | Err(_)) => return Err(e.into()),
561                (Ok(_), Err(e)) => return Err(e),
562            }
563        }
564        Ok(())
565    }
566
567    /// Runs the monitor and all its registered workers until they have all completed.
568    ///
569    /// # Errors
570    ///
571    /// If the monitor fails to run gracefully, a `MonitorError` will be returned.
572    ///
573    /// # Remarks
574    ///
575    /// If all workers have completed execution, then by default the monitor will start a shutdown
576    pub async fn run(self) -> Result<(), MonitorError> {
577        let shutdown = self.shutdown.clone();
578        let shutdown_future = self.shutdown.boxed().map(|_| ());
579        let (result, _) = futures_util::join!(
580            Self::run_all_workers(self.workers, shutdown),
581            shutdown_future,
582        );
583
584        result
585    }
586    async fn run_all_workers(
587        workers: Vec<MonitoredWorker>,
588        shutdown: Shutdown,
589    ) -> Result<(), MonitorError> {
590        // `FuturesUnordered` only polls a worker whose waker fired, so every shutdown path
591        // must wake the workers explicitly; `MonitorContext::shutdown` does that.
592        let results: Vec<_> = FuturesUnordered::from_iter(workers).collect().await;
593
594        shutdown.start_shutdown();
595
596        let mut errors = Vec::new();
597        // Check if any worker errored
598        for r in results {
599            match r {
600                Ok(_) => {}
601                Err(MonitoredWorkerError { ctx, error }) => {
602                    errors.push(MonitoredWorkerError { ctx, error })
603                }
604            }
605        }
606        if !errors.is_empty() {
607            return Err(MonitorError::ExitError(ExitError(errors)));
608        }
609        Ok(())
610    }
611
612    /// Handles all workers' events emitted
613    #[must_use]
614    pub fn on_event<F: Fn(&WorkerContext, &Event) + Send + Sync + 'static>(self, f: F) -> Self {
615        let _ = self.event_handler.write().map(|mut res| {
616            let _ = res.insert(Box::new(f));
617        });
618        self
619    }
620}
621
622impl Monitor {
623    /// Creates a new monitor instance.
624    ///
625    /// # Returns
626    ///
627    /// A new monitor instance, with an empty collection of workers.
628    #[must_use]
629    pub fn new() -> Self {
630        Self::default()
631    }
632
633    /// Sets a timeout duration for the monitor's shutdown process.
634    ///
635    /// # Arguments
636    ///
637    /// * `duration` - The timeout duration.
638    ///
639    /// # Returns
640    ///
641    /// The monitor instance, with the shutdown timeout duration set.
642    #[cfg(feature = "sleep")]
643    #[must_use]
644    pub fn shutdown_timeout(self, duration: std::time::Duration) -> Self {
645        self.with_terminator(crate::timer::sleep(duration))
646    }
647
648    /// Sets a future that will start being polled when the monitor's shutdown process starts.
649    ///
650    /// After shutdown has been initiated, the `terminator` future will be run, and if it completes
651    /// before all tasks are completed the shutdown process will complete, thus finishing the
652    /// shutdown even if there are outstanding tasks. This can be useful for using a timeout or
653    /// signal (or combination) to force a full shutdown even if one or more tasks are taking
654    /// longer than expected to finish.
655    #[must_use]
656    pub fn with_terminator(mut self, fut: impl Future<Output = ()> + Send + 'static) -> Self {
657        self.terminator = Some(fut.boxed().shared());
658        self
659    }
660
661    /// Allows controlling the restart strategy for workers
662    #[must_use]
663    pub fn should_restart<F>(self, cb: F) -> Self
664    where
665        F: Fn(&WorkerContext, &WorkerError) -> bool + Send + Sync + 'static,
666    {
667        let _ = self.should_restart.write().map(|mut res| {
668            let _ = res.insert(Box::new(cb));
669        });
670        self
671    }
672
673    /// Gets an instance of the Monitor's context
674    ///
675    /// Used to:
676    /// 1. Expose monitor to http and cli tools
677    /// 2. Shutdown the monitor and workers
678    #[must_use]
679    pub fn context(&self) -> MonitorContext {
680        MonitorContext {
681            shutdown: self.shutdown.clone(),
682            workers: self.workers.iter().map(|w| w.worker.clone()).collect(),
683        }
684    }
685}
686
687/// Error type for monitor operations.
688#[derive(Debug, thiserror::Error)]
689#[non_exhaustive]
690pub enum MonitorError {
691    /// Error occurred while running one or more workers
692    #[error("Worker errors:\n{0}")]
693    ExitError(#[from] ExitError),
694
695    /// Error occurred while waiting for shutdown signal
696    #[error("Shutdown signal error: {0}")]
697    ShutdownSignal(#[from] std::io::Error),
698}
699
700impl fmt::Debug for ExitError {
701    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> {
702        std::fmt::Display::fmt(&self, f)
703    }
704}
705
706/// Represents errors that occurred in a monitored worker, including its context and the error itself.
707#[derive(thiserror::Error)]
708pub struct ExitError(pub Vec<MonitoredWorkerError>);
709
710impl std::fmt::Display for ExitError {
711    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
712        writeln!(f, "MonitoredErrors:")?;
713        for worker in &self.0 {
714            writeln!(f, " - Worker `{}`: {}", worker.ctx.name(), worker.error)?;
715        }
716        Ok(())
717    }
718}
719
720#[cfg(test)]
721mod tests {
722    use super::*;
723    use crate::{
724        backend::{TaskSink, dequeue::VecDequeBackend},
725        task::task_id::TaskId,
726        worker::context::WorkerContext,
727    };
728    use core::panic;
729    use std::{io, time::Duration};
730
731    use tokio::time::sleep;
732    use tower::limit::ConcurrencyLimitLayer;
733
734    use crate::{monitor::Monitor, worker::builder::WorkerBuilder};
735
736    #[tokio::test]
737    async fn basic_with_workers() {
738        let mut backend = VecDequeBackend::new();
739
740        for i in 0..10 {
741            backend.push(i).await.unwrap();
742        }
743
744        let monitor: Monitor = Monitor::new();
745        let monitor = monitor.register(move |index| {
746            WorkerBuilder::new(format!("rango-tango-{index}"))
747                .backend(backend.clone())
748                .build(move |r: u32, id: TaskId, w: WorkerContext| async move {
749                    println!("{id:?}, {}", w.name());
750                    tokio::time::sleep(Duration::from_secs(index as u64)).await;
751                    Ok::<_, io::Error>(r)
752                })
753        });
754        let m = monitor.context();
755        tokio::spawn(async move {
756            sleep(Duration::from_millis(1500)).await;
757            m.shutdown().unwrap();
758        });
759        monitor.run().await.unwrap();
760    }
761    #[tokio::test]
762    async fn test_monitor_run() {
763        let mut backend = VecDequeBackend::new();
764
765        for i in 0..10 {
766            backend.push(i).await.unwrap();
767        }
768
769        let monitor: Monitor = Monitor::new()
770            .register(move |index| {
771                WorkerBuilder::new(format!("rango-tango-{index}"))
772                    .backend(backend.clone())
773                    .layer(ConcurrencyLimitLayer::new(1))
774                    .build(move |r| async move {
775                        sleep(Duration::from_millis(1000)).await;
776                        if r % 2 == 0 {
777                            panic!("Brrr")
778                        }
779                    })
780            })
781            .should_restart(|worker, e| {
782                let restarts = worker.restarts();
783                println!(
784                    "Encountered error in {} with {e:?} for attempt {restarts}",
785                    worker.name()
786                );
787                if restarts < 3 {
788                    return true;
789                }
790                false
791            })
792            .on_event(|wrk, e| {
793                println!("{}: {e:?}", wrk.name());
794            });
795        assert_eq!(monitor.workers.len(), 1);
796        let m = monitor.context();
797
798        tokio::spawn(async move {
799            sleep(Duration::from_millis(10000)).await;
800            m.shutdown().unwrap();
801        });
802
803        let result = monitor.run().await;
804        dbg!(&result);
805        assert!(
806            result.is_err_and(|e| matches!(e, MonitorError::ExitError(_))),
807            "Monitor did not return an error as expected"
808        );
809    }
810
811    #[tokio::test]
812    async fn test_monitor_register_multiple() {
813        let mut int_backend = VecDequeBackend::new();
814
815        let mut str_backend = VecDequeBackend::new();
816
817        for i in 0..10 {
818            int_backend.push(i).await.unwrap();
819        }
820
821        for i in 0..10 {
822            str_backend.push(i.to_string()).await.unwrap();
823        }
824
825        let monitor: Monitor = Monitor::new();
826
827        assert_send_sync::<Monitor>();
828
829        let monitor = monitor.on_event(|wrk, e| {
830            println!("{:?}, {e:?}", wrk.name());
831        });
832        let monitor = monitor
833            .register(move |index| {
834                WorkerBuilder::new(format!("worker0-{index}"))
835                    .backend(int_backend.clone())
836                    .layer(ConcurrencyLimitLayer::new(1))
837                    .build(
838                        move |request: i32, id: TaskId, w: WorkerContext| async move {
839                            println!("{id:?}, {}", w.name());
840                            tokio::time::sleep(Duration::from_secs(1)).await;
841                            Ok::<_, io::Error>(request)
842                        },
843                    )
844            })
845            .register(move |index| {
846                WorkerBuilder::new(format!("worker1-{index}"))
847                    .backend(str_backend.clone())
848                    .layer(ConcurrencyLimitLayer::new(1))
849                    .build(
850                        move |request: String, id: TaskId, w: WorkerContext| async move {
851                            println!("{id:?}, {}", w.name());
852                            tokio::time::sleep(Duration::from_secs(1)).await;
853                            Ok::<_, io::Error>(request)
854                        },
855                    )
856            });
857        assert_eq!(monitor.workers.len(), 2);
858        let m = monitor.context();
859
860        tokio::spawn(async move {
861            sleep(Duration::from_millis(5000)).await;
862            m.shutdown().unwrap();
863        });
864
865        let result = monitor.run().await;
866        assert!(result.is_ok());
867    }
868
869    /// Regression: shutting down a monitor of idle workers must wake every one of them.
870    ///
871    /// The monitor polls a worker only when its waker fires, and signalling shutdown just
872    /// flips a shared flag, so unless every worker is woken explicitly the idle ones are
873    /// never re-polled and never observe it. Historically this only showed above 30
874    /// workers, because `join_all` re-polled every future while it held 30 or fewer;
875    /// `FuturesUnordered` has no such fast path, so the count here is just the old
876    /// threshold kept for reference.
877    #[tokio::test]
878    async fn shutdown_wakes_idle_workers() {
879        use crate::backend::memory::MemoryStorage;
880
881        const WORKERS: usize = 31;
882
883        let mut monitor = Monitor::new();
884        for index in 0..WORKERS {
885            monitor = monitor.register(move |_| {
886                WorkerBuilder::new(format!("idle-{index}"))
887                    // An empty `MemoryStorage` never yields a task, so the worker parks
888                    // exactly like a cron worker waiting for a distant tick.
889                    .backend(MemoryStorage::<u32>::new())
890                    .build(|_: u32| async {})
891            });
892        }
893
894        let ctx = monitor.context();
895        tokio::spawn(async move {
896            sleep(Duration::from_millis(100)).await;
897            ctx.shutdown().unwrap();
898        });
899
900        let result = tokio::time::timeout(Duration::from_secs(5), monitor.run()).await;
901
902        let exit = result.expect("monitor did not shut down idle workers");
903        exit.unwrap();
904    }
905
906    /// Shutting down many idle workers must not cut short the one worker that is busy.
907    #[tokio::test]
908    async fn signal_shutdown_drains_active_work_with_many_idle_workers() {
909        use crate::backend::memory::MemoryStorage;
910        use std::sync::atomic::{AtomicBool, Ordering};
911
912        const IDLE_WORKERS: usize = 40;
913
914        let mut busy_backend = VecDequeBackend::new();
915        busy_backend.push(1u32).await.unwrap();
916
917        let completed = Arc::new(AtomicBool::new(false));
918        let flag = completed.clone();
919
920        let mut monitor = Monitor::new().register(move |_| {
921            let flag = flag.clone();
922            WorkerBuilder::new("busy")
923                .backend(busy_backend.clone())
924                .build(move |_: u32| {
925                    let flag = flag.clone();
926                    async move {
927                        sleep(Duration::from_millis(300)).await;
928                        flag.store(true, Ordering::SeqCst);
929                    }
930                })
931        });
932
933        for index in 0..IDLE_WORKERS {
934            monitor = monitor.register(move |_| {
935                WorkerBuilder::new(format!("idle-{index}"))
936                    .backend(MemoryStorage::<u32>::new())
937                    .build(|_: u32| async {})
938            });
939        }
940
941        let signal = async {
942            sleep(Duration::from_millis(50)).await;
943            Ok(())
944        };
945
946        let result =
947            tokio::time::timeout(Duration::from_secs(5), monitor.run_with_signal(signal)).await;
948
949        let exit = result.expect("monitor did not shut down idle workers");
950        exit.unwrap();
951        assert!(
952            completed.load(Ordering::SeqCst),
953            "shutdown cut short the in-flight task"
954        );
955    }
956
957    /// With a shutdown timeout set, a worker that exits with an error must still
958    /// surface that error from `run_with_signal`.
959    #[tokio::test]
960    async fn run_with_signal_reports_worker_errors_with_a_timeout() {
961        let mut backend = VecDequeBackend::new();
962        backend.push(1u32).await.unwrap();
963
964        let monitor = Monitor::new()
965            .shutdown_timeout(Duration::from_secs(5))
966            .register(move |_| {
967                WorkerBuilder::new("failing")
968                    .backend(backend.clone())
969                    .build(|r: u32| async move {
970                        if r == 1 {
971                            panic!("task failed");
972                        }
973                    })
974            });
975
976        // A signal that never arrives: the workers must end the run on their own.
977        let signal = std::future::pending::<io::Result<()>>();
978        let result =
979            tokio::time::timeout(Duration::from_secs(5), monitor.run_with_signal(signal)).await;
980
981        let exit = result.expect("monitor did not return after its only worker failed");
982        assert!(
983            matches!(exit, Err(MonitorError::ExitError(_))),
984            "expected the worker error, got {exit:?}"
985        );
986    }
987
988    /// With a shutdown timeout set, a failing shutdown signal must be reported.
989    #[tokio::test]
990    async fn run_with_signal_reports_signal_errors_with_a_timeout() {
991        use crate::backend::memory::MemoryStorage;
992
993        let monitor = Monitor::new()
994            .shutdown_timeout(Duration::from_secs(5))
995            .register(|_| {
996                WorkerBuilder::new("idle")
997                    .backend(MemoryStorage::<u32>::new())
998                    .build(|_: u32| async {})
999            });
1000
1001        let signal = async {
1002            sleep(Duration::from_millis(50)).await;
1003            Err(io::Error::other("signal handler failed"))
1004        };
1005        let result =
1006            tokio::time::timeout(Duration::from_secs(5), monitor.run_with_signal(signal)).await;
1007
1008        let exit = result.expect("monitor did not shut down after the signal");
1009        assert!(
1010            matches!(exit, Err(MonitorError::ShutdownSignal(_))),
1011            "expected the signal error, got {exit:?}"
1012        );
1013    }
1014
1015    /// With a shutdown timeout set, a worker still busy when the timeout fires is a
1016    /// forced exit: `run_with_signal` returns `Ok` rather than waiting on it.
1017    #[tokio::test]
1018    async fn run_with_signal_forces_exit_when_the_timeout_fires_with_work_in_flight() {
1019        let mut backend = VecDequeBackend::new();
1020        backend.push(1u32).await.unwrap();
1021
1022        let monitor = Monitor::new()
1023            .shutdown_timeout(Duration::from_millis(200))
1024            .register(move |_| {
1025                WorkerBuilder::new("stuck")
1026                    .backend(backend.clone())
1027                    .build(|_: u32| std::future::pending::<()>())
1028            });
1029
1030        // Late enough that the worker has picked up its task before shutdown starts.
1031        let signal = async {
1032            sleep(Duration::from_millis(100)).await;
1033            Ok(())
1034        };
1035        let result =
1036            tokio::time::timeout(Duration::from_secs(5), monitor.run_with_signal(signal)).await;
1037
1038        let exit = result.expect("monitor waited on a stuck worker past its shutdown timeout");
1039        assert!(exit.is_ok(), "expected a forced exit, got {exit:?}");
1040    }
1041
1042    /// A restart must hand control back to the executor instead of re-polling the
1043    /// restarted worker inside the same `poll`.
1044    #[tokio::test(flavor = "current_thread")]
1045    async fn restart_yields_to_other_tasks() {
1046        use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
1047
1048        const RESTART_BUDGET: usize = 200;
1049
1050        let mut backend = VecDequeBackend::new();
1051        for i in 0..(RESTART_BUDGET as u32 * 2) {
1052            backend.push(i).await.unwrap();
1053        }
1054
1055        // Set by another task on this single-threaded runtime. It can only run if
1056        // the monitor yields between restarts.
1057        let other_task_ran = Arc::new(AtomicBool::new(false));
1058        let restarts_when_stopped = Arc::new(AtomicUsize::new(0));
1059
1060        let ran = other_task_ran.clone();
1061        tokio::spawn(async move {
1062            ran.store(true, Ordering::SeqCst);
1063        });
1064
1065        let ran = other_task_ran.clone();
1066        let stopped_at = restarts_when_stopped.clone();
1067        let monitor = Monitor::new()
1068            .register(move |_| {
1069                WorkerBuilder::new("fails-at-once")
1070                    .backend(backend.clone())
1071                    .build(|r: u32| async move {
1072                        if r < u32::MAX {
1073                            panic!("task failed");
1074                        }
1075                    })
1076            })
1077            .should_restart(move |worker, _| {
1078                let keep_going = !ran.load(Ordering::SeqCst) && worker.restarts() < RESTART_BUDGET;
1079                if !keep_going {
1080                    stopped_at.store(worker.restarts(), Ordering::SeqCst);
1081                }
1082                keep_going
1083            });
1084
1085        let result = monitor.run().await;
1086
1087        assert!(matches!(result, Err(MonitorError::ExitError(_))));
1088        assert!(
1089            other_task_ran.load(Ordering::SeqCst),
1090            "the monitor never yielded between restarts"
1091        );
1092        assert!(
1093            restarts_when_stopped.load(Ordering::SeqCst) < RESTART_BUDGET,
1094            "the restart budget was spent before any other task ran"
1095        );
1096    }
1097
1098    fn assert_send_sync<T: Send + Sync>() {}
1099}