Crate taskvisor

Crate taskvisor 

Source
Expand description

§taskvisor

Taskvisor is a lightweight task orchestration library.

It provides primitives to define, supervise, and restart async tasks with configurable policies. The crate is designed as a building block for higher-level orchestrators and agents.

§Architecture

§High-level

     ┌──────────────┐   ┌──────────────┐   ┌──────────────┐
     │   TaskSpec   │ … │   TaskSpec   │ … │   TaskSpec   │
     │(user task #1)│ … │(user task #2)│ … │(user task #3)│
     └──────┬───────┘   └──────┬───────┘   └──────┬───────┘
            ▼                  ▼                  ▼
 ┌───────────────────────────────────────────────────────────────────┐
 │              supervisor (create actor, handles OS signals)        │
 └──────┬──────────────────┬──────────────────┬───────────────┬──────┘
        ▼                  ▼                  ▼               │
     ┌──────────────┐   ┌──────────────┐   ┌──────────────┐   │
     │  TaskActor   │   │  TaskActor   │   │  TaskActor   │   │
     │ (retry loop) │   │ (retry loop) │   │ (retry loop) │   │
     └┬─────────────┘   └┬─────────────┘   └┬─────────────┘   │
      │ Publishes        │ Publishes        │ Publishes       │
      │ Events           │ Events           │ Events          │
      │                  │                  │                 │
      │·TaskStarting     │ (…same kinds…)   │ (…same kinds…)  │
      │·TaskFailed       │                  │                 │
      │·TaskStopped      │                  │                 │
      │·TimeoutHit       │                  │                 │
      │·BackoffScheduled │                  │                 │
      │                  │                  │         graceful shutdown
      ▼                  ▼                  ▼                 ▼
 ┌───────────────────────────────────────────────────────────────────┐
 │                                bus                                │
 │                          broadcast<Event>                         │
 └─────────────────────────────────┬─────────────────────────────────┘
                      broadcasts to all subscribers
                                   ▼
     ┌───────────────────────┐           ┌───────────────────────┐
     │      Subscriber       │           │      AliveTracker     │
     │   on_event(&Event)    │           │  maintains alive set  │
     │    (user-defined)     │           │   (Starting/Stopped)  │
     └───────────────────────┘           └───────────────────────┘

§Attempt flow

 ┌────────────────────────────────────────┐
 │               TaskSpec                 │
 │  {                                     │
 │    task: TaskRef,                      │
 │    restart: RestartPolicy,             │
 │    backoff: BackoffPolicy,             │
 │    timeout: Option<Duration>           │
 │  }                                     │
 └────┬───────────────────────────────────┘
      │  (constructed directly or via Config::from_task)
      ▼
 ┌────────────────────────────────────────┐
 │               TaskActor                │
 │  { restart, backoff, timeout }         │
 └────┬───────────────────────────────────┘
      │ (1) optional: acquire global Semaphore permit (cancellable)
      │ (2) publish Event::TaskStarting{ task, attempt }
      │ (3) run_once(task, parent_token, timeout, bus)
      │         ├─ Ok  ──► publish TaskStopped
      │         │          └─ apply RestartPolicy from TaskSpec:
      │         │                - Never        ⇒ exit
      │         │                - OnFailure    ⇒ exit
      │         │                - Always       ⇒ continue
      │         └─ Err ──► publish TaskFailed
      │                    decide retry using RestartPolicy:
      │                      - Never        ⇒ exit
      │                      - OnFailure    ⇒ retry
      │                      - Always       ⇒ retry
      │ (4) if retry:
      │       delay = backoff.next(prev_delay) // BackoffPolicy from TaskSpec
      │       publish BackoffScheduled{ task, delay, attempt, error }
      │       sleep(delay)  (cancellable via runtime token)
      │       prev_delay = Some(delay)
      │       attempt += 1
      │       goto (1)
      └─ stop conditions:
              - runtime token cancelled (OS signal → graceful shutdown)
              - RestartPolicy (from TaskSpec) disallows further runs
              - semaphore closed / join end

§Features

AreaDescriptionKey types / traits
Subscriber APIHook into task lifecycle events (logging, metrics, custom subscribers).Subscriber
PoliciesConfigure restart/backoff strategies for tasks.RestartPolicy, BackoffPolicy
SupervisionManage groups of tasks and their lifecycle.Supervisor
ErrorsTyped errors for orchestration and task execution.TaskError, RuntimeError
TasksDefine tasks as functions or specs, easy to compose and run.TaskRef, TaskFn, TaskSpec
ConfigurationCentralize runtime settings.Config

§Optional features

  • logging: exports a simple built-in LogWriter (demo/reference only).
  • events: exports Event and EventKind for advanced integrations.
use std::time::Duration;
use tokio_util::sync::CancellationToken;
use taskvisor::{
    BackoffPolicy, Config, RestartPolicy, Supervisor, TaskFn, TaskRef, TaskSpec, LogWriter
};

#[tokio::main(flavor = "current_thread")]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let mut cfg = Config::default();
    cfg.timeout = Duration::from_secs(5);

    // Use the built-in logger subscriber (enabled via --features "logging").
    let s = Supervisor::new(cfg.clone(), LogWriter);

    // Define a simple task with a cancellation token.
    let hello: TaskRef = TaskFn::arc("hello", |ctx: CancellationToken| async move {
        if ctx.is_cancelled() { return Ok(()); }
        println!("Hello from task!");
        Ok(())
    });

    // Build a specification for the task.
    let spec = TaskSpec::new(
        hello,
        RestartPolicy::Never,
        BackoffPolicy::default(),
        Some(Duration::from_secs(5)),
    );

    s.run(vec![spec]).await?;
    Ok(())
}

Structs§

BackoffPolicy
Retry backoff policy.
Config
Global configuration for the runtime and supervisor.
Event
Runtime event with optional metadata.
LogWriter
Simple stdout logging subscriber.
Supervisor
Coordinates task actors, event delivery, and graceful shutdown.
TaskFn
Function-backed task implementation.
TaskSpec
Specification for running a task under supervision.

Enums§

EventKind
Classification of runtime events.
RestartPolicy
Policy controlling whether a task is restarted after completion or failure.
RuntimeError
Errors produced by the taskvisor runtime.
TaskError
Errors produced by task execution.

Traits§

Subscriber
Trait for subscribing to runtime events from the bus.
Task
Asynchronous, cancelable unit.

Type Aliases§

TaskRef
Shared handle to a task object.