Skip to main content

TaskRuntime

Struct TaskRuntime 

Source
pub struct TaskRuntime { /* private fields */ }
Expand description

The core runtime for managing supervised tasks.

TaskRuntime is responsible for:

  • Registering tasks and their configurations.
  • Managing task lifecycle (start, stop, pause, resume, restart).
  • Handling global and per-task concurrency limits.
  • Orchestrating task dependencies and prerequisites.
  • Distributing supervisor events to registered listeners.
  • Persisting and restoring task states.

It is typically created by the crate::Supervisor builder and then used to interact with the running supervised system.

Implementations§

Source§

impl TaskRuntime

Source

pub fn new() -> Self

Creates a new, empty TaskRuntime.

Source

pub fn with_global_concurrency_limit(&mut self, limit: usize) -> &mut Self

Sets a global concurrency limit for the supervisor.

This limit applies to all tasks and restricts how many can be actively running their run() method at any given time.

Source

pub fn with_event_channel_capacity(&mut self, capacity: usize) -> &mut Self

Sets the event broadcast channel capacity.

The default is 1024. Increase this if you have many tasks emitting events rapidly and observe EventsDropped warnings.

Source

pub fn register<T: SupervisedTask + 'static>(&mut self, task: T) -> &mut Self

Registers a task for supervision.

This method adds the task to the runtime’s internal registry but does not start its execution. Tasks are started when start_all() is called.

Source

pub fn register_many<T: SupervisedTask + 'static>( &mut self, tasks: Vec<T>, ) -> &mut Self

Registers multiple tasks of the same type at once.

Source

pub fn register_boxed(&mut self, task: Box<dyn SupervisedTask>) -> &mut Self

Registers a task from a boxed trait object.

Useful when managing a heterogeneous collection of tasks.

Source

pub fn register_arc(&mut self, task: Arc<dyn SupervisedTask>) -> &mut Self

Registers a task from an Arc (zero extra allocation).

This is the most efficient way to add a task if you already have an Arc handle.

Source

pub fn add_task<T: SupervisedTask + 'static>( &mut self, task: T, ) -> Result<(), SupervisorError>

Registers and starts a new task at runtime.

This allows adding tasks to an already running supervisor.

§Errors

Returns SupervisorError::ConfigurationError if a task with the same ID already exists. Returns SupervisorError::DependencyValidation if a declared dependency is unknown.

Source

pub fn restart_task(&self, id: &str) -> Result<(), SupervisorError>

Manually restarts a task by its ID.

This sends a Restart control message to the task’s supervision loop.

§Errors

Returns SupervisorError::UnknownTask if no task with the given ID is found.

Source

pub fn pause_task(&self, id: &str) -> Result<(), SupervisorError>

Pauses a task by its ID.

This sends a Pause control message to the task’s supervision loop. A paused task will temporarily stop executing its run() method.

§Errors

Returns SupervisorError::UnknownTask if no task with the given ID is found.

Source

pub fn resume_task(&self, id: &str) -> Result<(), SupervisorError>

Resumes a paused task by its ID.

This sends a Resume control message to the task’s supervision loop, allowing it to continue execution.

§Errors

Returns SupervisorError::UnknownTask if no task with the given ID is found.

Source

pub fn reset_circuit_breaker(&self, id: &str) -> Result<(), SupervisorError>

Resets the circuit breaker for a task by its ID.

§Errors

Returns SupervisorError::UnknownTask if no task with the given ID is found.

Source

pub async fn update_restart_policy( &self, id: &str, new_policy: RestartPolicy, ) -> Result<(), SupervisorError>

Updates the restart policy for a task at runtime.

The new policy will take effect on the next restart attempt. This does not trigger an immediate restart.

§Arguments
  • id - The task ID to update
  • new_policy - The new restart policy to apply
§Errors

Returns SupervisorError::UnknownTask if no task with the given ID is found.

Source

pub async fn update_backoff_strategy( &self, id: &str, new_strategy: BackoffStrategy, ) -> Result<(), SupervisorError>

Updates the backoff strategy for a task at runtime.

The new strategy will take effect on the next restart attempt. This does not trigger an immediate restart.

§Arguments
  • id - The task ID to update
  • new_strategy - The new backoff strategy to apply
§Errors

Returns SupervisorError::UnknownTask if no task with the given ID is found.

Source

pub async fn set_task_enabled( &self, id: &str, enabled: bool, ) -> Result<(), SupervisorError>

Enables or disables a task at runtime.

A disabled task will not restart after failure but will continue running if already executing. To stop a running task, use stop_task() first.

§Arguments
  • id - The task ID to enable/disable
  • enabled - Whether the task should be enabled
§Errors

Returns SupervisorError::UnknownTask if no task with the given ID is found.

Source

pub async fn get_task_config(&self, id: &str) -> Option<TaskConfig>

Gets the current configuration for a task.

§Arguments
  • id - The task ID to query
§Returns

A clone of the current task configuration, or None if task not found.

Source

pub async fn is_task_enabled(&self, id: &str) -> bool

Checks if a task is currently enabled.

§Arguments
  • id - The task ID to check
§Returns

true if the task is enabled, false otherwise.

Source

pub fn start_group(&mut self, group_id: &str) -> usize

Starts all tasks in a specific group.

This is useful for atomic operations where related tasks should be started together. If any task in the group fails to start, the operation continues with other tasks.

§Arguments
  • group_id - The group identifier to start
§Returns

Number of tasks started

Source

pub async fn stop_group(&mut self, group_id: &str) -> usize

Stops all tasks in a specific group.

Sends Stop control messages to all tasks in the group and waits for them to terminate.

§Arguments
  • group_id - The group identifier to stop
§Returns

Number of tasks stopped

Source

pub fn restart_group(&self, group_id: &str) -> usize

Restarts all tasks in a specific group.

Sends Restart control messages to all running tasks in the group.

§Arguments
  • group_id - The group identifier to restart
§Returns

Number of tasks restarted

Source

pub fn list_group_tasks(&self, group_id: &str) -> Vec<String>

Lists all task IDs in a specific group.

§Arguments
  • group_id - The group identifier to query
§Returns

Vector of task IDs belonging to the group

Source

pub async fn get_group_health(&self, group_id: &str) -> HealthStatus

Gets the aggregated health status for a task group.

The group health is determined by the worst health status among all tasks in the group:

  • If any task is Unhealthy, the group is Unhealthy
  • Else if any task is Degraded, the group is Degraded
  • Else if all tasks are Healthy, the group is Healthy
  • If no tasks are in the group, returns Unknown
§Arguments
  • group_id - The group identifier to query
§Returns

Aggregated HealthStatus for the group

Source

pub async fn get_group_health_details(&self, group_id: &str) -> Vec<TaskSummary>

Gets detailed health information for all tasks in a group.

§Arguments
  • group_id - The group identifier to query
§Returns

Vector of TaskSummary for each task in the group

Source

pub async fn remove_task( &mut self, id: &str, ) -> Result<Option<SupervisionResult>, SupervisorError>

Stops and removes a task by its ID.

This sends a Stop control message to the task, waits for it to terminate, and then removes it from the runtime.

§Errors

Returns SupervisorError::UnknownTask if no task with the given ID is found. Returns SupervisorError::TaskPanicked if the task panicked during removal.

Source

pub async fn get_task_info( &self, id: &str, ) -> Result<TaskSummary, SupervisorError>

Retrieves detailed information about a specific task.

This includes its ID, name, and current health status.

§Errors

Returns SupervisorError::UnknownTask if no task with the given ID is found.

Source

pub async fn list_tasks(&self) -> Vec<TaskSummary>

Lists summaries of all currently registered tasks.

Source

pub fn with_state_store(&mut self, store: Arc<dyn TaskStateStore>) -> &mut Self

Sets a custom state store for persisting task states.

This method is typically used by the crate::Supervisor builder.

Source

pub fn subscribe(&self) -> Receiver<SupervisorEvent>

Subscribes to the supervisor’s event stream.

Returns a tokio::sync::broadcast::Receiver that will receive all SupervisorEvents emitted by the runtime.

Source

pub fn add_listener( &mut self, listener: Arc<dyn SupervisorEventListener>, ) -> &mut Self

Registers an event listener.

This method is typically used by the crate::Supervisor builder.

Source

pub fn add_prerequisite( &mut self, name: &'static str, fut: PrerequisiteFuture, ) -> &mut Self

Adds an asynchronous prerequisite gate that must resolve before any task starts.

This method is typically used by the crate::Supervisor builder.

Source

pub fn add_prerequisite_fn<F, Fut>( &mut self, name: &'static str, f: F, ) -> &mut Self
where F: FnOnce() -> Fut + Send + 'static, Fut: Future<Output = SupervisorResult<()>> + Send + 'static,

Adds an asynchronous prerequisite gate using a closure.

This method is typically used by the crate::Supervisor builder.

Source

pub async fn start_all(&mut self) -> Result<(), SupervisorError>

Starts all registered tasks.

This method first runs all prerequisites, then validates dependencies, and finally spawns the supervision loop for each task.

§Errors

Returns SupervisorError if any prerequisite fails or if the dependency graph is invalid.

Source

pub fn start_one<T: SupervisedTask + 'static>( task: T, ) -> JoinHandle<SupervisionResult> ⓘ

Starts a single task with no dependencies (fire and forget).

This is a convenience function for simple, isolated task supervision without needing a full TaskRuntime setup.

Source

pub async fn wait_any(&mut self) -> SupervisionResult

Waits for any one supervised task to terminate.

Returns the SupervisionResult of the first task that finishes.

Source

pub async fn wait_all(&mut self) -> Vec<SupervisionResult>

Waits for all supervised tasks to terminate.

Returns a vector of SupervisionResult for all tasks.

Source

pub async fn shutdown(self)

Initiates a graceful shutdown of all supervised tasks.

This sends a Stop control message to each task and waits for them to complete their on_shutdown() hooks and terminate.

Shutdown is performed in reverse dependency order (leaves first, then roots).

Source

pub fn task_count(&self) -> usize

Returns the number of tasks currently being supervised.

Trait Implementations§

Source§

impl Debug for TaskRuntime

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Default for TaskRuntime

Source§

fn default() -> Self

Returns the “default value” for a type. Read more

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self> ⓘ

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self> ⓘ

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = !

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, !>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self> ⓘ
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self> ⓘ

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more