use super::*;
impl Default for ShutdownConfig {
fn default() -> Self {
Self {
drain_timeout_ms: DEFAULT_SHUTDOWN_DRAIN_TIMEOUT_MS,
callback_timeout_ms: DEFAULT_SHUTDOWN_CALLBACK_TIMEOUT_MS,
handle_sigint: true,
handle_sigterm: true,
}
}
}
impl ShutdownConfig {
pub fn with_drain_timeout_ms(mut self, drain_timeout_ms: u64) -> Self {
self.set_drain_timeout_ms(drain_timeout_ms);
self
}
pub fn with_callback_timeout_ms(mut self, callback_timeout_ms: u64) -> Self {
self.set_callback_timeout_ms(callback_timeout_ms);
self
}
}
impl Drop for ShutdownGuard {
#[inline]
fn drop(&mut self) {
let Self { inner } = self;
let prev: usize = inner.state.fetch_sub(1, Ordering::Release);
if prev == (SHUTDOWN_BIT | 1) {
fence(Ordering::Acquire);
inner.drained_notify.notify_waiters();
}
}
}
impl Default for ShutdownCoordinator {
fn default() -> Self {
Self::new(ShutdownConfig::default())
}
}
impl ShutdownCoordinator {
pub fn new(config: ShutdownConfig) -> Self {
Self {
inner: Arc::new(ShutdownCoordinatorInner {
state: AtomicUsize::new(0),
config,
shutdown_notify: Notify::new(),
drained_notify: Notify::new(),
callbacks: Vec::new(),
}),
}
}
pub fn with_callback<C>(self, callback: C) -> Self
where
C: ShutdownCallback,
{
let Self { inner } = self;
let mut callbacks: Vec<SharedShutdownCallback> = inner.callbacks.clone();
callbacks.push(Arc::new(callback));
Self {
inner: Arc::new(ShutdownCoordinatorInner {
state: AtomicUsize::new(inner.state.load(Ordering::Acquire)),
config: inner.config.clone(),
shutdown_notify: Notify::new(),
drained_notify: Notify::new(),
callbacks,
}),
}
}
#[inline]
pub fn get_config(&self) -> &ShutdownConfig {
let Self { inner } = self;
&inner.config
}
#[inline]
pub fn is_shutting_down(&self) -> bool {
let Self { inner } = self;
(inner.state.load(Ordering::Acquire) & SHUTDOWN_BIT) != 0
}
#[inline]
pub fn in_flight(&self) -> usize {
let Self { inner } = self;
inner.state.load(Ordering::Acquire) & IN_FLIGHT_MASK
}
#[inline]
pub fn enter(&self) -> Option<ShutdownGuard> {
let Self { inner } = self;
let prev: usize = inner.state.fetch_add(1, Ordering::Acquire);
if (prev & SHUTDOWN_BIT) != 0 {
let undo: usize = inner.state.fetch_sub(1, Ordering::Release);
if undo == (SHUTDOWN_BIT | 1) {
fence(Ordering::Acquire);
inner.drained_notify.notify_waiters();
}
return None;
}
Some(ShutdownGuard {
inner: Arc::clone(inner),
})
}
pub fn trigger(&self) {
let Self { inner } = self;
let prev: usize = inner.state.fetch_or(SHUTDOWN_BIT, Ordering::AcqRel);
if (prev & SHUTDOWN_BIT) == 0 {
inner.shutdown_notify.notify_waiters();
if prev == 0 {
inner.drained_notify.notify_waiters();
}
}
}
pub async fn wait_triggered(&self) {
let Self { inner } = self;
if (inner.state.load(Ordering::Acquire) & SHUTDOWN_BIT) != 0 {
return;
}
let mut notified: Pin<&mut Notified<'_>> = pin!(inner.shutdown_notify.notified());
notified.as_mut().enable();
if (inner.state.load(Ordering::Acquire) & SHUTDOWN_BIT) != 0 {
return;
}
notified.await;
}
pub async fn execute_shutdown(&self, control: Option<ServerControlHook>) -> ShutdownReport {
let Self { inner } = self;
let started: Instant = Instant::now();
self.trigger();
let drain_budget: Duration = Duration::from_millis(inner.config.get_drain_timeout_ms());
let drained_cleanly: bool = if (inner.state.load(Ordering::Acquire) & IN_FLIGHT_MASK) == 0 {
true
} else {
timeout(drain_budget, async {
loop {
let mut notified: Pin<&mut Notified<'_>> =
pin!(inner.drained_notify.notified());
notified.as_mut().enable();
if (inner.state.load(Ordering::Acquire) & IN_FLIGHT_MASK) == 0 {
break;
}
notified.await;
}
})
.await
.is_ok()
};
let remaining_in_flight: usize = inner.state.load(Ordering::Acquire) & IN_FLIGHT_MASK;
let cb_budget: Duration =
Duration::from_millis(inner.config.get_callback_timeout_ms().max(1));
let mut completed_callbacks: Vec<String> = Vec::with_capacity(inner.callbacks.len());
let mut timed_out_callbacks: Vec<String> = Vec::new();
for callback in inner.callbacks.iter().rev() {
let name: String = callback.name().to_owned();
if timeout(cb_budget, callback.on_shutdown()).await.is_ok() {
completed_callbacks.push(name);
} else {
timed_out_callbacks.push(name);
}
}
if let Some(hook) = control {
hook.shutdown().await;
}
ShutdownReport {
drained_cleanly,
remaining_in_flight,
completed_callbacks,
timed_out_callbacks,
elapsed_ms: started.elapsed().as_millis() as u64,
}
}
pub fn arm_signals(&self, control: ServerControlHook) -> JoinHandle<ShutdownReport> {
let coordinator: Self = self.clone();
spawn(async move {
let handle_sigint: bool = coordinator.get_config().get_handle_sigint();
let handle_sigterm: bool = coordinator.get_config().get_handle_sigterm();
select! {
_ = coordinator.wait_triggered() => {}
_ = async {
if handle_sigint {
let _: io::Result<()> = ctrl_c().await;
} else {
pending::<()>().await;
}
} => {}
_ = wait_sigterm(handle_sigterm) => {}
}
coordinator.execute_shutdown(Some(control)).await
})
}
}
impl ShutdownPlugin {
pub fn init(coordinator: ShutdownCoordinator) -> &'static Self {
SHUTDOWN_PLUGIN.get_or_init(|| Self { coordinator })
}
pub fn get() -> Option<&'static Self> {
SHUTDOWN_PLUGIN.get()
}
pub fn get_coordinator(&self) -> &ShutdownCoordinator {
&self.coordinator
}
}