use std::sync::{mpsc, Arc, Mutex};
use tracing::{debug, trace};
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum SignalType {
Reload,
Shutdown,
}
pub struct SignalManager {
tx: mpsc::Sender<SignalType>,
rx: Arc<Mutex<mpsc::Receiver<SignalType>>>,
}
impl SignalManager {
pub fn new() -> Self {
debug!("Creating signal manager");
let (tx, rx) = mpsc::channel();
Self {
tx,
rx: Arc::new(Mutex::new(rx)),
}
}
pub fn sender(&self) -> mpsc::Sender<SignalType> {
trace!("Cloning signal sender for handler");
self.tx.clone()
}
pub fn recv_blocking(&self) -> Option<SignalType> {
trace!("Waiting for signal (blocking)");
let signal = self.rx.lock().ok()?.recv().ok();
if let Some(ref s) = signal {
debug!(signal = ?s, "Received signal");
}
signal
}
pub fn try_recv(&self) -> Option<SignalType> {
let signal = self.rx.lock().ok()?.try_recv().ok();
if let Some(ref s) = signal {
debug!(signal = ?s, "Received signal (non-blocking)");
}
signal
}
}
impl Default for SignalManager {
fn default() -> Self {
Self::new()
}
}