melodium_engine/
interruption.rs1use crate::engine::Engine;
12use core::time::Duration;
13use std::sync::{Arc, Mutex};
14
15static LAST_INTERRUPTION: Mutex<Option<Interruption>> = Mutex::new(None);
16
17pub fn last_interruption() -> Option<Interruption> {
19 *LAST_INTERRUPTION.lock().unwrap()
20}
21
22#[derive(Clone, Copy, Debug, PartialEq, Eq)]
24pub enum Interruption {
25 Ended(i32),
27 Stopped(i32),
29}
30
31impl Interruption {
32 pub fn signal(&self) -> i32 {
34 match self {
35 Interruption::Ended(signal) | Interruption::Stopped(signal) => *signal,
36 }
37 }
38
39 pub fn exit_code(&self) -> i32 {
42 #[cfg(windows)]
43 {
44 console::STATUS_CONTROL_C_EXIT
45 }
46 #[cfg(not(windows))]
47 {
48 128 + self.signal()
49 }
50 }
51}
52
53pub fn signal_name(signal: i32) -> String {
55 #[cfg(unix)]
56 {
57 use async_signal::Signal;
58 for (known, name) in [
59 (Signal::Int, "SIGINT"),
60 (Signal::Term, "SIGTERM"),
61 (Signal::Hup, "SIGHUP"),
62 ] {
63 if signal == known as i32 {
64 return name.to_string();
65 }
66 }
67 }
68 #[cfg(windows)]
69 {
70 if let Some(name) = console::event_name(signal) {
71 return name.to_string();
72 }
73 }
74 format!("signal {signal}")
75}
76
77pub async fn live_until_interrupted(
87 engine: &Arc<dyn Engine>,
88 grace: Duration,
89) -> Option<Interruption> {
90 #[cfg(any(unix, windows))]
91 {
92 let mut interruptions = match Interruptions::listen() {
93 Some(interruptions) => interruptions,
94 None => {
95 engine.live().await;
96 return None;
97 }
98 };
99 let interruption = live_interruptible(engine, grace, &mut interruptions).await;
100 interruptions.close();
101 if interruption.is_some() {
102 *LAST_INTERRUPTION.lock().unwrap() = interruption;
103 }
104 interruption
105 }
106 #[cfg(not(any(unix, windows)))]
107 {
108 let _ = grace;
109 engine.live().await;
110 None
111 }
112}
113
114#[cfg(any(unix, windows))]
115async fn live_interruptible(
116 engine: &Arc<dyn Engine>,
117 grace: Duration,
118 interruptions: &mut Interruptions,
119) -> Option<Interruption> {
120 use futures::{pin_mut, select, FutureExt};
121 use melodium_common::executive::Level;
122
123 let live = engine.live().fuse();
124 pin_mut!(live);
125
126 let signal = {
127 let next = interruptions.next().fuse();
128 pin_mut!(next);
129 select! {
130 _ = live => return None,
131 signal = next => signal,
132 }
133 };
134 let signal = match signal {
135 Some(signal) => signal,
136 None => {
137 live.await;
138 return None;
139 }
140 };
141
142 let grace = Interruptions::grace(signal, grace);
143 engine
144 .log(
145 Level::Warning,
146 "melodium".to_string(),
147 format!(
148 "interrupted by {}, ending within {} seconds",
149 signal_name(signal),
150 grace.as_secs()
151 ),
152 )
153 .await;
154 engine.end().await;
155
156 let grace_end = smol::Timer::after(grace).fuse();
157 pin_mut!(grace_end);
158 let second = interruptions.next().fuse();
159 pin_mut!(second);
160 select! {
161 _ = live => return Some(Interruption::Ended(signal)),
162 _ = grace_end => {
163 engine
164 .log(
165 Level::Error,
166 "melodium".to_string(),
167 "still running at the end of the grace period, stopping".to_string(),
168 )
169 .await;
170 },
171 second = second => {
172 engine
173 .log(
174 Level::Error,
175 "melodium".to_string(),
176 format!(
177 "interrupted again by {}, stopping",
178 second.map(signal_name).unwrap_or_default()
179 ),
180 )
181 .await;
182 },
183 }
184
185 engine.stop().await;
188 smol::future::or(live, async {
189 smol::Timer::after(STOP_TIMEOUT).await;
190 })
191 .await;
192 Some(Interruption::Stopped(signal))
193}
194
195#[cfg(any(unix, windows))]
197const STOP_TIMEOUT: Duration = Duration::from_secs(2);
198
199#[cfg(unix)]
200struct Interruptions {
201 signals: async_signal::Signals,
202}
203
204#[cfg(unix)]
205impl Interruptions {
206 fn listen() -> Option<Self> {
207 use async_signal::{Signal, Signals};
208
209 let signals = Signals::new([Signal::Int, Signal::Term, Signal::Hup]).ok()?;
210 Some(Self { signals })
211 }
212
213 async fn next(&mut self) -> Option<i32> {
214 use futures::StreamExt;
215 while let Some(signal) = self.signals.next().await {
216 if let Ok(signal) = signal {
217 return Some(signal as i32);
218 }
219 }
220 None
221 }
222
223 fn grace(_signal: i32, grace: Duration) -> Duration {
224 grace
225 }
226
227 fn close(self) {}
229}
230
231#[cfg(windows)]
232struct Interruptions {
233 events: async_channel::Receiver<i32>,
234}
235
236#[cfg(windows)]
237impl Interruptions {
238 fn listen() -> Option<Self> {
239 console::listen().map(|events| Self { events })
240 }
241
242 async fn next(&mut self) -> Option<i32> {
243 self.events.recv().await.ok()
244 }
245
246 fn grace(signal: i32, grace: Duration) -> Duration {
247 if console::terminates(signal) {
248 grace.min(console::TERMINATION_GRACE)
249 } else {
250 grace
251 }
252 }
253
254 fn close(self) {
255 console::close();
256 }
257}
258
259#[cfg(windows)]
260mod console {
261 use async_channel::{unbounded, Receiver, Sender};
264 use core::time::Duration;
265 use std::sync::Mutex;
266 use windows_sys::core::BOOL;
267 use windows_sys::Win32::System::Console::{
268 SetConsoleCtrlHandler, CTRL_BREAK_EVENT, CTRL_CLOSE_EVENT, CTRL_C_EVENT, CTRL_LOGOFF_EVENT,
269 CTRL_SHUTDOWN_EVENT,
270 };
271
272 pub const STATUS_CONTROL_C_EXIT: i32 = 0xC000013Au32 as i32;
274
275 pub const TERMINATION_GRACE: Duration = Duration::from_secs(2);
278
279 static EVENTS: Mutex<Option<Sender<i32>>> = Mutex::new(None);
280
281 pub fn terminates(event: i32) -> bool {
283 matches!(
284 event as u32,
285 CTRL_CLOSE_EVENT | CTRL_LOGOFF_EVENT | CTRL_SHUTDOWN_EVENT
286 )
287 }
288
289 pub fn event_name(event: i32) -> Option<&'static str> {
290 match event as u32 {
291 CTRL_C_EVENT => Some("Ctrl+C"),
292 CTRL_BREAK_EVENT => Some("Ctrl+Break"),
293 CTRL_CLOSE_EVENT => Some("console close"),
294 CTRL_LOGOFF_EVENT => Some("logoff"),
295 CTRL_SHUTDOWN_EVENT => Some("shutdown"),
296 _ => None,
297 }
298 }
299
300 unsafe extern "system" fn handler(event: u32) -> BOOL {
301 let events = EVENTS.lock().ok().and_then(|events| events.clone());
302 match events {
303 Some(events) => {
304 let _ = events.try_send(event as i32);
305 if terminates(event as i32) {
306 loop {
309 std::thread::park();
310 }
311 }
312 1
313 }
314 None => 0,
315 }
316 }
317
318 pub fn listen() -> Option<Receiver<i32>> {
319 let (sender, receiver) = unbounded();
320 *EVENTS.lock().ok()? = Some(sender);
321 if unsafe { SetConsoleCtrlHandler(Some(handler), 1) } == 0 {
322 close();
323 return None;
324 }
325 Some(receiver)
326 }
327
328 pub fn close() {
329 unsafe { SetConsoleCtrlHandler(Some(handler), 0) };
330 if let Ok(mut events) = EVENTS.lock() {
331 *events = None;
332 }
333 }
334}