use std::sync::Arc;
use std::time::Duration;
use taskvisor::prelude::*;
use taskvisor::{ControllerConfig, ControllerSpec, RejectionKind};
use tokio::sync::Notify;
fn job(name: &'static str, duration: Duration) -> TaskSpec {
let task: TaskRef = TaskFn::arc(name, move |ctx| async move {
ctx.run_until_cancelled(tokio::time::sleep(duration))
.await?;
Ok(())
});
TaskSpec::once(task)
}
fn gated_job(name: &'static str, started: Arc<Notify>, release: Arc<Notify>) -> TaskSpec {
let task: TaskRef = TaskFn::arc(name, move |ctx| {
let started = Arc::clone(&started);
let release = Arc::clone(&release);
async move {
started.notify_one();
ctx.run_until_cancelled(release.notified()).await?;
Ok(())
}
});
TaskSpec::once(task)
}
#[tokio::main(flavor = "current_thread")]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let supervisor = Supervisor::builder(SupervisorConfig::default())
.with_controller(ControllerConfig::default())
.build();
let handle = supervisor.serve();
println!("Slot 'deploy' admits at most one task at a time.\n");
println!("1) submit deploy-v1 (Queue) to the idle slot");
let started = Arc::new(Notify::new());
let release = Arc::new(Notify::new());
let (_id, v1) = handle
.submit_and_watch(
ControllerSpec::queue(gated_job(
"deploy-v1",
Arc::clone(&started),
Arc::clone(&release),
))
.with_slot("deploy"),
)
.await?;
started.notified().await;
println!(" deploy-v1 admitted, now running\n");
if let Some(snap) = handle.controller_snapshot().await {
let deploy = snap.slot("deploy");
println!(
" controller: {} running, {} queued; deploy status={:?} depth={}\n",
snap.running_count(),
snap.total_queued(),
deploy.map(|s| s.status),
deploy.map_or(0, |s| s.queue_depth),
);
}
println!("2) submit deploy-v2 (DropIfRunning) while the slot is busy");
let (_id, v2) = handle
.submit_and_watch(
ControllerSpec::drop_if_running(job("deploy-v2", Duration::from_millis(200)))
.with_slot("deploy"),
)
.await?;
match v2.wait().await? {
TaskOutcome::Rejected {
kind: RejectionKind::SlotBusy,
reason,
..
} => {
println!(" deploy-v2 -> Rejected ({reason}) - never ran\n");
}
other => println!(" deploy-v2 -> {other:?} (unexpected)\n"),
}
println!("3) await the admitted task");
release.notify_one();
println!(" deploy-v1 -> {:?}", v1.wait().await?);
handle.shutdown().await?;
Ok(())
}