task_supervisor/
lib.rs

1//! # Task Supervisor for Tokio
2//!
3//! The `task-supervisor` crate provides a smol framework for managing and monitoring asynchronous tasks
4//! in Rust using the Tokio runtime. It ensures tasks remain operational by monitoring their health
5//! via heartbeats and automatically restarting them if they fail or become unresponsive.
6//!
7//! ## Key Components
8//!
9//! - **[`SupervisedTask`] Trait**: Defines the interface for tasks to be supervised. Tasks must
10//!   implement the `run_forever` method with their core logic and may optionally provide a `name`.
11//!
12//! - **[`Supervisor`] Struct**: Manages a collection of tasks, monitors their health using heartbeats,
13//!   and restarts them if they crash or exceed a configurable timeout threshold. It uses a message-passing
14//!   system to coordinate task supervision.
15//!
16//! - **[`SupervisorBuilder`]**: Implements the builder to construct a `Supervisor` instance,
17//!   allowing tasks to be added.
18//!
19//! - **[`TaskStatus`] Enum**: Represents the lifecycle states of a supervised task, such as `Created`,
20//!   `Healthy`, `Failed`, or `Dead`.
21//!
22//! ## Usage Example
23//!
24//! Below is a simple example demonstrating how to define and supervise a task:
25//!
26//! ```rust
27//! use supervisor::{SupervisedTask, SupervisorBuilder};
28//! use async_trait::async_trait;
29//! use std::time::Duration;
30//!
31//! #[derive(Clone)]
32//! struct MyTask;
33//!
34//! #[async_trait]
35//! impl SupervisedTask for MyTask {
36//!     type Error = std::io::Error;
37//!
38//!     fn name(&self) -> Option<&str> {
39//!         Some("my_task")
40//!     }
41//!
42//!     async fn run_forever(&mut self) -> Result<(), Self::Error> {
43//!         loop {
44//!             tokio::time::sleep(Duration::from_secs(1)).await;
45//!             println!("Task is running");
46//!         }
47//!     }
48//! }
49//!
50//! #[tokio::main]
51//! async fn main() {
52//!     let mut supervisor = SupervisorBuilder::default()
53//!         .with_task(MyTask)
54//!         .build();
55//!
56//!     supervisor.run_and_supervise().await;
57//! }
58//! ```
59//!
60pub use supervisor::{Supervisor, SupervisorBuilder};
61pub use task::{SupervisedTask, TaskStatus};
62
63mod messaging;
64mod supervisor;
65mod task;
66mod task_group;