soft_cycle/global.rs
1//! Global [`SoftCycleController`] instance and convenience functions.
2//!
3//! This module is only available when the `global_instance` feature is enabled (default).
4
5use tokio::sync::OnceCell;
6
7use crate::{SoftCycleController, SoftCycleListener};
8
9/// Global [`SoftCycleController`] instance, lazily initialized on first use.
10static SHUTDOWN_CONTROLLER: OnceCell<SoftCycleController> = OnceCell::const_new();
11
12/// Returns a reference to the global [`SoftCycleController`], initializing it on first call.
13pub async fn get_lifetime_controller() -> &'static SoftCycleController {
14 SHUTDOWN_CONTROLLER
15 .get_or_init(|| async { SoftCycleController::new() })
16 .await
17}
18
19/// Attempts to trigger a shutdown on the global [`SoftCycleController`]
20/// instance.
21///
22/// Returns true if successful, and false if a shutdown or restart has already
23/// been triggered.
24#[must_use = "Caller must check if the operation was successful"]
25pub async fn try_shutdown() -> bool {
26 get_lifetime_controller().await.try_shutdown().await
27}
28
29/// Attempts to trigger a restart on the global [`SoftCycleController`]
30/// instance.
31///
32/// Returns true if successful, and false if a shutdown or restart has already
33/// been triggered.
34#[must_use = "Caller must check if the operation was successful"]
35pub async fn try_restart() -> bool {
36 get_lifetime_controller().await.try_restart().await
37}
38
39/// Listener that resolves when a restart or shutdown is triggered on the
40/// global [`SoftCycleController`] instance.
41///
42/// Returns true if a shutdown was triggered, and false if a restart was
43/// triggered.
44#[must_use = "Caller must await the listener to receive the signal"]
45pub async fn listener() -> SoftCycleListener<'static> {
46 get_lifetime_controller().await.listener()
47}
48
49/// Clears the triggered state on the global [`SoftCycleController`]
50/// instance.
51pub async fn clear() {
52 get_lifetime_controller().await.clear();
53}