use crate::util::UnwrapPoison;
use std::sync::{Mutex, OnceLock};
use std::time::{Duration, Instant};
use tokio_util::sync::CancellationToken;
use tracing::info;
static GLOBAL_SHUTDOWN: OnceLock<CancellationToken> = OnceLock::new();
fn global_shutdown() -> &'static CancellationToken {
GLOBAL_SHUTDOWN.get_or_init(CancellationToken::new)
}
static DRAIN: OnceLock<tokio::sync::watch::Sender<bool>> = OnceLock::new();
fn drain_sender() -> &'static tokio::sync::watch::Sender<bool> {
DRAIN.get_or_init(|| tokio::sync::watch::channel(false).0)
}
fn drain_receiver() -> tokio::sync::watch::Receiver<bool> {
drain_sender().subscribe()
}
pub fn drain_begin() {
drain_sender().send_replace(true);
info!("Draining: in-flight work completes before exit");
}
#[must_use]
pub fn is_draining() -> bool {
*drain_sender().borrow()
}
#[must_use]
pub fn aborting() -> bool {
shutdown_token().is_cancelled() || is_draining()
}
pub fn force_cancel() {
global_shutdown().cancel();
}
pub fn drain_clear() {
drain_sender().send_replace(false);
}
#[must_use]
pub fn shutdown_token() -> CancellationToken {
global_shutdown().clone()
}
pub fn shutdown() {
global_shutdown().cancel();
}
pub struct Shutdown;
pub async fn race_shutdown<F, T>(fut: F) -> Result<T, Shutdown>
where
F: std::future::Future<Output = T>,
{
let token = shutdown_token();
tokio::select! {
result = fut => Ok(result),
() = token.cancelled() => Err(Shutdown),
}
}
#[must_use]
pub async fn sleep_or_shutdown(duration: Duration) -> bool {
race_shutdown(tokio::time::sleep(duration)).await.is_ok()
}
#[must_use]
pub async fn sleep_or_shutdown_or_drain(duration: Duration) -> bool {
let token = shutdown_token();
let drain = drain_wait();
tokio::pin!(drain);
tokio::select! {
() = token.cancelled() => false,
() = &mut drain => false,
() = tokio::time::sleep(duration) => true,
}
}
pub(crate) async fn drain_wait() {
let mut rx = drain_receiver();
while !*rx.borrow_and_update() {
if rx.changed().await.is_err() {
return; }
}
}
#[cfg(any(windows, test))]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum StopRequest {
Interrupt,
Break,
ConsoleClose,
}
#[cfg(windows)]
impl StopRequest {
#[must_use]
fn label(self) -> &'static str {
match self {
Self::Interrupt => "Ctrl+C",
Self::Break => "Ctrl+Break",
Self::ConsoleClose => "console close",
}
}
}
#[cfg(any(windows, test))]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum StopAction {
Drain,
ForceCancel,
}
#[cfg(any(windows, test))]
#[must_use]
fn stop_action(request: StopRequest, draining: bool) -> StopAction {
if request == StopRequest::Interrupt && !draining {
StopAction::Drain
} else {
StopAction::ForceCancel
}
}
static STOP_DEADLINE: Mutex<Option<Instant>> = Mutex::new(None);
#[cfg(windows)]
const DEFAULT_STOP_GRACE: Duration = Duration::from_secs(5);
#[cfg(windows)]
fn record_stop_deadline(deadline: Instant) {
let mut recorded = STOP_DEADLINE.lock().unwrap_poison();
if recorded.is_none_or(|current| deadline < current) {
*recorded = Some(deadline);
}
}
#[must_use]
fn stage_budget(deadline: Instant, now: Instant) -> Duration {
deadline.saturating_duration_since(now) / 2
}
#[must_use]
pub fn urgent_release_budget() -> Option<Duration> {
STOP_DEADLINE
.lock()
.unwrap_poison()
.map(|deadline| stage_budget(deadline, Instant::now()))
}
static EXIT_TRIGGER: Mutex<Option<&'static str>> = Mutex::new(None);
pub(crate) fn record_exit_trigger(label: &'static str) {
*EXIT_TRIGGER.lock().unwrap_poison() = Some(label);
}
#[must_use]
pub fn exit_trigger() -> Option<&'static str> {
*EXIT_TRIGGER.lock().unwrap_poison()
}
#[cfg(any(windows, test))]
#[must_use]
fn session_end_label(ending: bool, closes_app_only: bool, log_off: bool) -> Option<&'static str> {
if !ending || closes_app_only {
return None;
}
Some(if log_off {
"Windows log-off"
} else {
"Windows shutdown/restart"
})
}
#[cfg(windows)]
fn stop_for_session_end(label: &'static str) {
record_exit_trigger(label);
record_stop_deadline(Instant::now() + DEFAULT_STOP_GRACE);
info!("{label} — forcing the stop: the platform's seconds cannot hold a drain");
force_cancel();
}
pub async fn wait_for_shutdown_signal() -> anyhow::Result<Option<&'static str>> {
#[cfg(unix)]
{
use tokio::signal::unix::{SignalKind, signal};
use tracing::debug;
let mut sigint = signal(SignalKind::interrupt())?;
let mut sigterm = signal(SignalKind::terminate())?;
let mut sighup = signal(SignalKind::hangup())?;
let mut first = true;
loop {
let signal = tokio::select! {
_ = sigint.recv() => "SIGINT",
_ = sigterm.recv() => "SIGTERM",
_ = sighup.recv() => {
debug!("Received SIGHUP, ignoring (daemon stays running)");
continue;
}
};
if first {
info!("Received {signal} — draining (second signal force-cancels)");
record_exit_trigger(signal);
drain_begin();
first = false;
} else {
info!("Received second {signal} — force-cancelling drain");
return Ok(None);
}
}
}
#[cfg(windows)]
{
loop {
let request = console::next_request().await?;
let label = request.label();
record_exit_trigger(label);
match stop_action(request, is_draining()) {
StopAction::Drain => {
info!("Received {label} — draining (a second request force-cancels)");
drain_begin();
}
StopAction::ForceCancel => return Ok(Some(label)),
}
}
}
}
pub fn install_ignored_signals() {
#[cfg(unix)]
{
extern "C" fn ignore(_signal: libc::c_int) {}
use std::sync::Once;
static INSTALLED: Once = Once::new();
INSTALLED.call_once(|| {
unsafe {
for kind in [libc::SIGHUP, libc::SIGTSTP, libc::SIGTTIN, libc::SIGTTOU] {
libc::signal(kind, ignore as *const () as libc::sighandler_t);
}
}
});
}
}
pub fn install_stop_request_sources(window: crate::service::WindowMode) {
install_console_stop_handler();
install_session_end_listener();
install_quit_requests(window);
}
fn install_console_stop_handler() {
#[cfg(windows)]
console::install();
}
fn install_session_end_listener() {
#[cfg(windows)]
session_end::install();
}
#[cfg(windows)]
mod console {
use super::{DEFAULT_STOP_GRACE, StopRequest, record_stop_deadline};
use crate::util::UnwrapPoison;
use std::collections::VecDeque;
use std::sync::Mutex;
use std::sync::atomic::{AtomicBool, Ordering};
use std::time::{Duration, Instant};
use tokio::sync::Notify;
use windows_sys::Win32::Foundation::{FALSE, TRUE};
use windows_sys::Win32::System::Console::{
CTRL_BREAK_EVENT, CTRL_C_EVENT, CTRL_CLOSE_EVENT, GetConsoleCP, SetConsoleCtrlHandler,
};
use windows_sys::Win32::UI::WindowsAndMessaging::{
SPI_GETHUNGAPPTIMEOUT, SystemParametersInfoW,
};
static REQUESTS: Mutex<VecDeque<StopRequest>> = Mutex::new(VecDeque::new());
static QUEUED: Notify = Notify::const_new();
static INSTALLED: AtomicBool = AtomicBool::new(false);
static LOOP_RUNNING: AtomicBool = AtomicBool::new(false);
fn attached_to_console() -> bool {
unsafe { GetConsoleCP() != 0 }
}
pub(super) fn install() {
let installed = unsafe { SetConsoleCtrlHandler(Some(handler), TRUE) != 0 };
INSTALLED.store(installed, Ordering::SeqCst);
if !installed && attached_to_console() {
crate::boot::boot_diagnostic(
"console control handler not registered — Ctrl+C still stops the daemon \
through tokio's own handler; a console close and Ctrl+Break will kill \
the process without a shutdown."
.to_string(),
);
}
}
extern "system" fn handler(event: u32) -> i32 {
let Some(request) = request_for(event) else {
return FALSE;
};
let close = request == StopRequest::ConsoleClose;
let deadline = close.then(close_deadline);
if !close && !LOOP_RUNNING.load(Ordering::SeqCst) {
return FALSE;
}
REQUESTS.lock().unwrap_poison().push_back(request);
QUEUED.notify_one();
if let Some(deadline) = deadline {
std::thread::sleep(deadline.saturating_duration_since(Instant::now()));
}
TRUE
}
pub(super) async fn next_request() -> anyhow::Result<StopRequest> {
LOOP_RUNNING.store(true, Ordering::SeqCst);
if !INSTALLED.load(Ordering::SeqCst) {
if !attached_to_console() {
return std::future::pending().await;
}
tokio::signal::ctrl_c().await?;
return Ok(StopRequest::Interrupt);
}
loop {
let queued = REQUESTS.lock().unwrap_poison().pop_front();
if let Some(request) = queued {
return Ok(request);
}
QUEUED.notified().await;
}
}
fn request_for(event: u32) -> Option<StopRequest> {
match event {
CTRL_C_EVENT => Some(StopRequest::Interrupt),
CTRL_BREAK_EVENT => Some(StopRequest::Break),
CTRL_CLOSE_EVENT => Some(StopRequest::ConsoleClose),
_ => None,
}
}
fn close_deadline() -> Instant {
let deadline = Instant::now() + close_grace();
record_stop_deadline(deadline);
deadline
}
fn close_grace() -> Duration {
let mut millis: u32 = 0;
let read =
unsafe { SystemParametersInfoW(SPI_GETHUNGAPPTIMEOUT, 0, (&raw mut millis).cast(), 0) };
if read == 0 {
DEFAULT_STOP_GRACE
} else {
Duration::from_millis(u64::from(millis))
}
}
}
#[cfg(windows)]
mod session_end {
use super::{session_end_label, stop_for_session_end};
use std::io::Error;
use std::mem::{size_of, zeroed};
use windows_sys::Win32::Foundation::{HWND, LPARAM, LRESULT, WPARAM};
use windows_sys::Win32::System::LibraryLoader::GetModuleHandleW;
use windows_sys::Win32::UI::WindowsAndMessaging::{
CreateWindowExW, DefWindowProcW, DispatchMessageW, ENDSESSION_CLOSEAPP, ENDSESSION_LOGOFF,
GetMessageW, MSG, RegisterClassExW, WM_ENDSESSION, WM_QUERYENDSESSION, WNDCLASSEXW,
};
use windows_sys::w;
const WINDOW_CLASS: windows_sys::core::PCWSTR = w!("MahBotSessionEnd");
pub(super) fn install() {
if let Err(e) = std::thread::Builder::new()
.name("session-end-listener".to_string())
.spawn(listen)
{
report("thread not spawned", &e);
}
}
fn listen() {
let instance = unsafe { GetModuleHandleW(std::ptr::null()) };
let mut class: WNDCLASSEXW = unsafe { zeroed() };
#[allow(clippy::cast_possible_truncation)]
let class_size = size_of::<WNDCLASSEXW>() as u32;
class.cbSize = class_size;
class.lpfnWndProc = Some(window_proc);
class.hInstance = instance;
class.lpszClassName = WINDOW_CLASS;
if unsafe { RegisterClassExW(&raw const class) } == 0 {
report("window class not registered", &Error::last_os_error());
return;
}
let window = unsafe {
CreateWindowExW(
0,
WINDOW_CLASS,
std::ptr::null(),
0,
0,
0,
0,
0,
std::ptr::null_mut(),
std::ptr::null_mut(),
instance,
std::ptr::null(),
)
};
if window.is_null() {
report("window not created", &Error::last_os_error());
return;
}
let mut message: MSG = unsafe { zeroed() };
loop {
let retrieved = unsafe { GetMessageW(&raw mut message, std::ptr::null_mut(), 0, 0) };
if retrieved == 0 {
break;
}
if retrieved < 0 {
report("message loop failed", &Error::last_os_error());
break;
}
unsafe { DispatchMessageW(&raw const message) };
}
}
extern "system" fn window_proc(
window: HWND,
message: u32,
wparam: WPARAM,
lparam: LPARAM,
) -> LRESULT {
match message {
WM_QUERYENDSESSION => LRESULT::from(true),
WM_ENDSESSION => {
#[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)]
let flags = lparam as u32;
let ending = wparam != 0;
let closes_app_only = flags & ENDSESSION_CLOSEAPP != 0;
let log_off = flags & ENDSESSION_LOGOFF != 0;
if let Some(label) = session_end_label(ending, closes_app_only, log_off) {
stop_for_session_end(label);
}
0
}
_ => unsafe { DefWindowProcW(window, message, wparam, lparam) },
}
}
fn report(what: &str, detail: &Error) {
crate::boot::boot_diagnostic(format!(
"session-end listener: {what}: {detail} — a Windows log-off, shutdown or restart \
will end the daemon without its stop steps"
));
}
}
pub(crate) const MACOS_QUIT_TRIGGER: &str = "macOS quit";
#[cfg(any(target_os = "macos", target_os = "windows"))]
pub(crate) const TRAY_QUIT_TRIGGER: &str = "tray quit";
fn install_quit_requests(window: crate::service::WindowMode) {
let (tx, rx) = tokio::sync::mpsc::unbounded_channel();
*QUIT_REQUESTS.lock().unwrap_poison() = Some(rx);
#[cfg(target_os = "macos")]
{
if !window.is_headless() {
macos_quit::install(tx);
}
}
#[cfg(not(target_os = "macos"))]
{
let _ = window;
drop(tx);
}
}
static QUIT_REQUESTS: Mutex<Option<tokio::sync::mpsc::UnboundedReceiver<()>>> = Mutex::new(None);
pub(crate) fn take_quit_requests() -> Option<tokio::sync::mpsc::UnboundedReceiver<()>> {
QUIT_REQUESTS.lock().unwrap_poison().take()
}
#[cfg(target_os = "macos")]
mod macos_quit {
use objc2::ffi::class_addMethod;
use objc2::runtime::{AnyClass, AnyObject, Imp, Sel};
use objc2::sel;
use objc2_app_kit::NSApplicationTerminateReply;
use objc2_core_services::{
kAEQuitAll, kAEQuitReason, kAEReallyLogOut, kAERestart, kAEShutDown,
};
use objc2_foundation::NSAppleEventManager;
use std::ffi::CStr;
use std::sync::OnceLock;
use std::sync::atomic::{AtomicBool, Ordering};
use std::time::{Duration, Instant};
use tracing::{info, warn};
static QUIT_TX: OnceLock<tokio::sync::mpsc::UnboundedSender<()>> = OnceLock::new();
fn queue_quit() -> bool {
QUIT_TX.get().is_some_and(|tx| tx.send(()).is_ok())
}
const DELEGATE_CLASS: &CStr = c"WinitApplicationDelegate";
const SHOULD_TERMINATE_TYPES: &CStr = c"Q@:@";
const SHOULD_REOPEN_TYPES: &CStr = c"c@:@c";
const INSTALL_WAIT: Duration = Duration::from_secs(60);
const INSTALL_POLL: Duration = Duration::from_millis(5);
const EXIT_BOUND: Duration = Duration::from_secs(crate::jobs::DRAIN_CAP_SECS + 300);
pub(super) fn install(tx: tokio::sync::mpsc::UnboundedSender<()>) {
let _ = QUIT_TX.set(tx);
if let Err(e) = std::thread::Builder::new()
.name("quit-interception".to_string())
.spawn(install_when_registered)
{
report(&format!("thread not spawned: {e}"));
}
}
fn install_when_registered() {
let give_up = Instant::now() + INSTALL_WAIT;
loop {
if let Some(class) = AnyClass::get(DELEGATE_CLASS) {
let added = unsafe {
class_addMethod(
std::ptr::from_ref(class).cast_mut(),
sel!(applicationShouldTerminate:),
std::mem::transmute::<
unsafe extern "C-unwind" fn(
*mut AnyObject,
Sel,
*mut AnyObject,
)
-> NSApplicationTerminateReply,
Imp,
>(should_terminate),
SHOULD_TERMINATE_TYPES.as_ptr(),
)
};
if !added.as_bool() {
report(
"winit's delegate already implements applicationShouldTerminate: — \
the platform's own termination stands",
);
}
let reopened = unsafe {
class_addMethod(
std::ptr::from_ref(class).cast_mut(),
sel!(applicationShouldHandleReopen:hasVisibleWindows:),
std::mem::transmute::<
unsafe extern "C-unwind" fn(
*mut AnyObject,
Sel,
*mut AnyObject,
i8,
) -> i8,
Imp,
>(should_reopen),
SHOULD_REOPEN_TYPES.as_ptr(),
)
};
if !reopened.as_bool() {
report(
"winit's delegate already answers a reopen — the platform's own answer \
stands",
);
}
return;
}
if Instant::now() >= give_up {
report(
"winit's delegate class was not registered in time — the platform's own \
termination stands",
);
return;
}
std::thread::sleep(INSTALL_POLL);
}
}
unsafe extern "C-unwind" fn should_terminate(
_this: *mut AnyObject,
_cmd: Sel,
_sender: *mut AnyObject,
) -> NSApplicationTerminateReply {
if is_session_end() {
return NSApplicationTerminateReply::TerminateNow;
}
if !queue_quit() {
warn!("the dashboard is past its exit — the platform ends the process");
return NSApplicationTerminateReply::TerminateNow;
}
info!("macOS quit — the platform asked the product to quit");
arm_exit_bound();
NSApplicationTerminateReply::TerminateCancel
}
unsafe extern "C-unwind" fn should_reopen(
_this: *mut AnyObject,
_cmd: Sel,
_sender: *mut AnyObject,
_has_visible_windows: i8,
) -> i8 {
0
}
fn is_session_end() -> bool {
const SESSION_ENDS: [u32; 4] = [kAEShutDown, kAERestart, kAEReallyLogOut, kAEQuitAll];
NSAppleEventManager::sharedAppleEventManager()
.currentAppleEvent()
.and_then(|event| event.attributeDescriptorForKeyword(kAEQuitReason))
.is_some_and(|reason| SESSION_ENDS.contains(&reason.typeCodeValue()))
}
fn arm_exit_bound() {
static ARMED: AtomicBool = AtomicBool::new(false);
if ARMED.swap(true, Ordering::SeqCst) {
return;
}
if let Err(e) = std::thread::Builder::new()
.name("quit-exit-bound".to_string())
.spawn(|| {
std::thread::sleep(EXIT_BOUND);
report(&format!(
"the closing path did not finish within {EXIT_BOUND:?} of a quit — ending \
the process"
));
unsafe { libc::_exit(1) }
})
{
report(&format!("exit bound not armed: {e}"));
}
}
fn report(what: &str) {
crate::boot::boot_diagnostic(format!("macOS delegate hooks: {what}"));
}
}
#[cfg(unix)]
pub fn install_fatal_signal_handlers() {
use std::sync::Once;
static INSTALLED: Once = Once::new();
INSTALLED.call_once(|| {
unsafe {
libc::signal(
libc::SIGBUS,
fatal_signal_handler as *const () as libc::sighandler_t,
);
libc::signal(
libc::SIGABRT,
fatal_signal_handler as *const () as libc::sighandler_t,
);
}
});
}
#[cfg(unix)]
const SIGBUS_MSG: &str = "mahbot: caught SIGBUS (bus error), terminating\n";
#[cfg(unix)]
const SIGABRT_MSG: &str = "mahbot: caught SIGABRT (abort), terminating\n";
#[cfg(unix)]
extern "C" fn fatal_signal_handler(sig: i32) {
let msg = match sig {
libc::SIGBUS => SIGBUS_MSG,
libc::SIGABRT => SIGABRT_MSG,
_ => "mahbot: caught unknown fatal signal, terminating\n",
};
unsafe {
let _ = libc::write(
libc::STDERR_FILENO,
msg.as_ptr().cast::<libc::c_void>(),
msg.len(),
);
libc::_exit(1);
}
}
#[cfg(not(unix))]
pub fn install_fatal_signal_handlers() {
}
thread_local! {
static CONTAINED_PANIC: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
}
pub fn contain_panics<T>(f: impl FnOnce() -> T) -> std::thread::Result<T> {
let previous = CONTAINED_PANIC.with(|flag| flag.replace(true));
let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(f));
CONTAINED_PANIC.with(|flag| flag.set(previous));
result
}
pub fn install_panic_hook() {
let default_hook = std::panic::take_hook();
std::panic::set_hook(Box::new(move |info| {
if CONTAINED_PANIC.with(std::cell::Cell::get) {
return;
}
crate::boot::timestamped_stderr(&info.to_string());
default_hook(info);
}));
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn only_the_first_interrupt_drains() {
for (request, draining, expected) in [
(StopRequest::Interrupt, false, StopAction::Drain),
(StopRequest::Interrupt, true, StopAction::ForceCancel),
(StopRequest::Break, false, StopAction::ForceCancel),
(StopRequest::ConsoleClose, false, StopAction::ForceCancel),
] {
assert_eq!(
stop_action(request, draining),
expected,
"{request:?}, draining={draining}"
);
}
}
#[test]
fn only_the_final_session_end_notification_stops_the_daemon() {
assert_eq!(
session_end_label(true, false, true),
Some("Windows log-off")
);
assert_eq!(
session_end_label(true, false, false),
Some("Windows shutdown/restart")
);
assert_eq!(session_end_label(false, false, false), None);
assert_eq!(session_end_label(true, true, false), None);
}
#[test]
fn the_release_budget_samples_half_the_remaining_grace() {
let now = Instant::now();
let deadline = now + Duration::from_secs(5);
assert_eq!(stage_budget(deadline, now), Duration::from_millis(2500));
assert_eq!(
stage_budget(deadline, now + Duration::from_secs(4)),
Duration::from_millis(500)
);
assert_eq!(stage_budget(now, now), Duration::ZERO);
}
#[test]
fn a_contained_panic_is_not_reported() {
const MARKER: &str = "mahbot: contained-panic test marker";
static REPORTED: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
type PanicHook = Box<dyn Fn(&std::panic::PanicHookInfo<'_>) + Send + Sync>;
struct RestoreHook(Option<std::sync::Arc<PanicHook>>);
impl Drop for RestoreHook {
fn drop(&mut self) {
if let Some(hook) = self.0.take() {
std::panic::set_hook(Box::new(move |info| hook.as_ref()(info)));
}
}
}
let previous = std::sync::Arc::new(std::panic::take_hook());
let _restore = RestoreHook(Some(std::sync::Arc::clone(&previous)));
std::panic::set_hook(Box::new(move |info| {
let payload = info.payload();
let text = payload
.downcast_ref::<&str>()
.copied()
.or_else(|| payload.downcast_ref::<String>().map(String::as_str));
if text == Some(MARKER) {
REPORTED.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
} else {
previous.as_ref()(info);
}
}));
install_panic_hook();
assert!(
contain_panics(|| panic!("{MARKER}")).is_err(),
"the panic is still returned to the caller"
);
assert_eq!(
REPORTED.load(std::sync::atomic::Ordering::Relaxed),
0,
"a contained panic must not reach the hook: one document conversion \
cannot report once per failing page"
);
let _ = std::panic::catch_unwind(|| panic!("{MARKER}"));
assert_eq!(
REPORTED.load(std::sync::atomic::Ordering::Relaxed),
1,
"every other panic is reported as before"
);
}
}