servlet 1.2.0

A small application runtime with an explicit operational contract
Documentation
//! Readiness acknowledgement and observation-only cancellation.

use std::sync::atomic::{AtomicBool, Ordering};

use tokio::sync::mpsc;
use tokio_util::sync::CancellationToken;

/// Read-only notification that the application has stopped admitting work.
#[derive(Clone, Debug)]
pub struct Shutdown {
    pub(crate) token: CancellationToken,
}

impl Shutdown {
    /// Wait until shutdown is requested. Repeated waits complete immediately.
    pub async fn cancelled(&self) {
        self.token.cancelled().await;
    }

    /// Whether shutdown has already been requested.
    pub fn is_requested(&self) -> bool {
        self.token.is_cancelled()
    }
}

/// Startup readiness and shutdown notification for a worker or service.
pub struct WorkerContext {
    name: String,
    ready: AtomicBool,
    acknowledgements: mpsc::Sender<String>,
    shutdown: Shutdown,
}

impl WorkerContext {
    pub(crate) fn new(
        name: String,
        acknowledgements: mpsc::Sender<String>,
        token: CancellationToken,
    ) -> Self {
        Self {
            name,
            ready: AtomicBool::new(false),
            acknowledgements,
            shutdown: Shutdown { token },
        }
    }

    /// The registered name of this task.
    pub fn name(&self) -> &str {
        &self.name
    }

    /// Announce readiness once. Repeated calls have no additional effect.
    pub fn ready(&self) {
        if !self.ready.swap(true, Ordering::AcqRel) {
            // Capacity is one message per registered worker; repeats are suppressed.
            let _ = self.acknowledgements.try_send(self.name.clone());
        }
    }

    /// Obtain a notification handle with no ability to cancel sibling workers.
    pub fn shutdown(&self) -> Shutdown {
        self.shutdown.clone()
    }
}