Async command handler trait, shutdown-signal listeners, and CLI value parsers.
command_handler bundles the small, reusable pieces that almost every async
command-line program needs:
- a
Handlertrait for units of work that run until aCancellationTokenis triggered, - cross-platform shutdown signals that resolve on
SIGTERM/SIGINT/SIGHUP(or the Windows console control events) and convert into a cancellation token, clap-compatible value parsers for socket addresses and filesystem paths.
Handler is a single-method trait for work that runs until it is cancelled. It
takes self by value and receives the cancellation token to observe:
use anyhow::Result;
use async_trait::async_trait;
use command_handler::handler::Handler;
use command_handler::shutdown_signal::register_shutdown_signals;
use tokio_util::sync::CancellationToken;
struct Server;
#[async_trait(?Send)]
impl Handler for Server {
async fn handle(self, cancellation_token: CancellationToken) -> Result<()> {
cancellation_token.cancelled().await;
Ok(())
}
}
#[tokio::main]
async fn main() -> Result<()> {
let shutdown_token: CancellationToken = register_shutdown_signals()?.into();
Server.handle(shutdown_token).await
}Licensed under the Apache License, Version 2.0.