Standalone executions
Running a job or a command with no server: execute, per-execution data, deadlines and close.
A transport opens one execution for each request or call. A job, a CLI command or a test has no transport, so it opens an execution itself. This gives it the same per-execution scope, cancellation and drain behaviour a handler has.
This page follows examples/12-standalone.
Running a job
The application stops after connect(). execute opens an execution, runs an async closure in it and ends the execution when the closure returns. close runs the shutdown sequence with no sockets to close.
/// Opens one execution on the app, hands it `tenant`, and runs the report in it.
pub async fn report(app: &App<Connected>, tenant: &'static str) -> Result<Result<String, LookupError>, Closed> {
app.execute(ExecOptions::new(), async |exec| {
exec.extensions().insert(Tenant(tenant));
Ok(exec.get::<ReportJob>().await?.run())
})
.await
}#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let app = builder().runtime(Tokio::current()).wire()?.connect().await?;
println!("{}", report(&app, "acme").await??);
let shutdown = app.close(Signal::new("done")).await?;
println!("closed on {}", shutdown.signal);
Ok(())
}execute returns Result<R, Closed>. The outer Result is whether the execution could open; the inner is the closure's own. Closed means the app has begun draining.
Per-execution data
ReportJob is #[injectable(execution)]. It reads Ext<Tenant>, a typed view of the execution's extension bag, and the singleton Ledger:
/// Execution-scoped: one `ReportJob` per `execute`, reading what the caller put in the
/// execution's extensions and the singleton `Ledger`.
#[injectable(execution)]
pub struct ReportJob {
tenant: Ext<Tenant>,
ledger: Dep<Ledger>,
}The caller writes Tenant with exec.extensions().insert(..) before asking for the job. Each execute has its own bag, so two calls do not see each other's tenant:
assert_eq!(report(&app, "acme").await.unwrap().unwrap(), "acme: 4 rows");
assert_eq!(report(&app, "globex").await.unwrap().unwrap(), "globex: 6 rows", "each execution has its own Tenant");A read of data that nothing wrote is a LookupError::NotFound with LookupKind::Extension, or None through Option<Ext<T>>. An execution input that a transport would seed, such as an HTTP request head, is not seeded in a standalone execution: a non-optional read fails at runtime with NotFound and LookupKind::Input, naming the key.
Extensions is a shared handle: insert, get, contains and remove take &self.
Deadlines and cancellation
ExecOptions::new().deadline(instant) cancels the execution on the app's clock when the instant passes. The closure sees it through exec.cancelled(). Cancellation does not stop the closure: it runs on to its end, and the closure decides what to do with the signal.
let options = ExecOptions::new().deadline((started + deadline).into_std());
let ran = app
.execute(options, async |exec| {
exec.extensions().insert(Tenant("acme"));
let job = exec.get::<ReportJob>().await?;
exec.cancelled().await;
Ok::<_, LookupError>(job.run())
})
.await;
assert_eq!(ran.unwrap().unwrap(), "acme: 4 rows", "the job outlives the cancellation of its execution");
assert_eq!(started.elapsed(), deadline);A deadline already past fires before the closure first runs. An app with no Timer stores the deadline, reports it through deadline(), and never fires cancellation from it. Completion of execute fires no cancellation.
What closes the execution
execute owns the execution. When the closure's future completes, execute drops the execution, which ends it and drops its execution-scoped instances. A subtask that outlives the call takes exec.handle(). The handle is a clone that reads what the execution recorded, and its get then answers LookupError::ExecutionEnded. A stream built from the execution is consumed inside the closure.
Close
After close, the same handle refuses new executions:
let handle = app.handle();
let shutdown = app.close(Signal::new("done")).await.unwrap();
assert_eq!(shutdown.signal.name(), "done");
assert_eq!((shutdown.abandoned, shutdown.terminal_skipped), (0, 0));
// After the close the same handle refuses new executions.
let late = handle.execute(ExecOptions::new(), async |_| ()).await;
assert!(matches!(late, Err(Closed { .. })));The drain covers live standalone executions: an execute still running, or an Execution opened with Execution::open and not yet dropped. A detached subtask's handle() is not one.
Where execute is available
execute exists on App<Connected>, on AppHandle and on ModuleRef. The first two resolve with the root module's visibility. ModuleRef::execute, reached through app.module::<M>()?, resolves with M's, so a job that belongs to a subtree runs through that module.
A background loop in a served app holds an AppHandle and runs each unit of work through handle.execute(..), so that shutdown waits for it.
Running the example
cargo run -p ex-12-standalone