pub struct Controller;
Expand description
Service to start and gracefully stop the system runtime.
This service offers a static API to wait for a shutdown signal or manually initiate the Relay
shutdown. To use this functionality, it first needs to be started with Controller::start
.
To shut down gracefully, other services can register with Controller::shutdown_handle
. When
a shutdown signal is sent to the process, every service will receive a Shutdown
message with
an optional timeout. To wait for the entire shutdown sequence including the shutdown timeout
instead, use finished
. It resolves when the shutdown has
completed.
§Signals
By default, the controller watches for process signals and converts them into graceful or immediate shutdown messages. These signals are platform-dependent:
- Unix:
SIGINT
andSIGQUIT
trigger an immediate shutdown,SIGTERM
a graceful one. - Windows:
CTRL-C
,CTRL-BREAK
,CTRL-CLOSE
all trigger an immediate shutdown.
§Example
use relay_system::{Controller, Service, ServiceRunner, Shutdown, ShutdownMode};
use std::time::Duration;
struct MyService;
impl Service for MyService {
type Interface = ();
async fn run(self, mut rx: relay_system::Receiver<Self::Interface>) {
let mut shutdown = Controller::shutdown_handle();
loop {
tokio::select! {
shutdown = shutdown.notified() => break, // Handle shutdown here
Some(message) = rx.recv() => (), // Process incoming message
}
}
}
}
#[tokio::main(flavor = "current_thread")]
async fn main() {
// Start the controller near the beginning of application bootstrap. This allows other
// services to register for shutdown messages.
Controller::start(Duration::from_millis(10));
// Start all other services. Controller::shutdown_handle will use the same controller
// instance and receives the configured shutdown timeout.
let addr = ServiceRunner::new().start(MyService);
// By triggering a shutdown, all subscribed services will be notified. This happens
// automatically when a signal is sent to the process (e.g. SIGINT or SIGTERM).
Controller::shutdown(ShutdownMode::Graceful);
// Wait for the system to shut down before winding down the application.
Controller::shutdown_handle().finished().await;
}
Implementations§
source§impl Controller
impl Controller
sourcepub fn shutdown(mode: ShutdownMode)
pub fn shutdown(mode: ShutdownMode)
Manually initiates the shutdown process of the system.
sourcepub fn shutdown_handle() -> ShutdownHandle
pub fn shutdown_handle() -> ShutdownHandle
Returns a handle to receive shutdown notifications.