1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
//! Signal subscription for handling OS signals.
//!
//! This module provides subscription sources for handling operating system signals
//! such as SIGINT, SIGTERM, etc. The implementation is platform-specific, with
//! different APIs for Unix and Windows systems.
#[cfg(unix)]
mod unix_signal {
use std::{
hash::{DefaultHasher, Hash, Hasher},
io,
};
use futures::stream::BoxStream;
use futures::{StreamExt as _, stream};
use tokio::signal::unix::{Signal as TokioSignal, SignalKind, signal};
use crate::subscription::{SubscriptionId, SubscriptionSource};
/// A subscription source for Unix signals.
///
/// This provides a stream of signal events for the specified signal kind.
/// Each time the signal is received, the subscription emits a unit value `()`.
///
/// # Platform
///
/// This is only available on Unix platforms (Linux, macOS, BSD, etc.).
///
/// # Example
///
/// ```rust,no_run
/// use tears::subscription::{Subscription, signal::Signal};
/// use tokio::signal::unix::SignalKind;
///
/// enum Message {
/// Interrupt,
/// Terminate,
/// SignalError(std::io::Error),
/// }
///
/// // Create a subscription for SIGINT (Ctrl+C)
/// let sigint = Subscription::new(Signal::new(SignalKind::interrupt()))
/// .map(|result| match result {
/// Ok(()) => Message::Interrupt,
/// Err(e) => Message::SignalError(e),
/// });
///
/// // Create a subscription for SIGTERM
/// let sigterm = Subscription::new(Signal::new(SignalKind::terminate()))
/// .map(|result| match result {
/// Ok(()) => Message::Terminate,
/// Err(e) => Message::SignalError(e),
/// });
/// ```
///
/// # Error Handling
///
/// This subscription yields `Result<(), io::Error>` values. The error case occurs
/// when the signal handler cannot be installed (typically only at subscription
/// creation time). Once the signal handler is successfully installed, it will
/// yield `Ok(())` each time the signal is received.
///
/// Common error scenarios:
/// - **Signal handler installation failure**: Usually due to system limitations
/// or permission issues
///
/// # Available Signals
///
/// The `SignalKind` type from tokio supports many Unix signals including:
/// - `SignalKind::interrupt()` - SIGINT (Ctrl+C)
/// - `SignalKind::terminate()` - SIGTERM (termination request)
/// - `SignalKind::hangup()` - SIGHUP (hangup)
/// - `SignalKind::quit()` - SIGQUIT (quit with core dump)
/// - `SignalKind::user_defined1()` - SIGUSR1 (user-defined signal 1)
/// - `SignalKind::user_defined2()` - SIGUSR2 (user-defined signal 2)
///
/// And many more. See the [`tokio::signal::unix::SignalKind`] documentation
/// for the complete list.
///
/// # Note
///
/// Multiple subscriptions for the same signal kind are allowed. Each subscription
/// will independently receive the signal.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct Signal {
kind: SignalKind,
}
impl Signal {
/// Create a new signal subscription for the specified signal kind.
///
/// # Arguments
///
/// * `kind` - The kind of signal to subscribe to
///
/// # Example
///
/// ```rust
/// use tears::subscription::signal::Signal;
/// use tokio::signal::unix::SignalKind;
///
/// // Subscribe to SIGINT
/// let sigint = Signal::new(SignalKind::interrupt());
///
/// // Subscribe to SIGTERM
/// let sigterm = Signal::new(SignalKind::terminate());
/// ```
#[must_use]
pub const fn new(kind: SignalKind) -> Self {
Self { kind }
}
}
impl SubscriptionSource for Signal {
type Output = Result<(), io::Error>;
fn stream(&self) -> BoxStream<'static, Self::Output> {
let kind = self.kind;
// Create a stream that yields () each time the signal is received
// NOTE: signal() returns Result<Signal, io::Error>
// If it fails, try_unfold yields a single error and ends the stream
// If it succeeds, it yields Ok(()) for each signal received
stream::try_unfold(None, move |state: Option<TokioSignal>| async move {
let mut sig = match state {
None => {
// First call: initialize the signal handler
signal(kind)?
}
Some(sig) => sig,
};
// Wait for signals
match sig.recv().await {
Some(()) => Ok(Some(((), Some(sig)))),
None => Ok(None), // End the stream
}
})
.boxed()
}
fn id(&self) -> SubscriptionId {
let mut hasher = DefaultHasher::new();
self.hash(&mut hasher);
SubscriptionId::of::<Self>(hasher.finish())
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_signal_new() {
let sig = Signal::new(SignalKind::interrupt());
assert_eq!(sig.kind, SignalKind::interrupt());
}
#[test]
fn test_signal_id_consistency() {
let sig1 = Signal::new(SignalKind::interrupt());
let sig2 = Signal::new(SignalKind::interrupt());
// Same signal kind should produce the same ID
assert_eq!(sig1.id(), sig2.id());
}
#[test]
fn test_signal_id_different_kinds() {
let sig1 = Signal::new(SignalKind::interrupt());
let sig2 = Signal::new(SignalKind::terminate());
// Different signal kinds should produce different IDs
assert_ne!(sig1.id(), sig2.id());
}
}
}
#[cfg(unix)]
pub use unix_signal::Signal;
#[cfg(windows)]
mod windows_signal {
use std::{
hash::{DefaultHasher, Hash, Hasher},
io,
};
use futures::StreamExt as _;
use futures::stream::{self, BoxStream};
use tokio::signal::windows::{
CtrlBreak as TokioCtrlBreak, CtrlC as TokioCtrlC, ctrl_break, ctrl_c,
};
use crate::subscription::{SubscriptionId, SubscriptionSource};
/// A subscription source for Windows Ctrl+C events.
///
/// This provides a stream of Ctrl+C events. Each time Ctrl+C is pressed,
/// the subscription emits a unit value `()`.
///
/// # Platform
///
/// This is only available on Windows platforms.
///
/// # Example
///
/// ```rust,no_run
/// use tears::subscription::{Subscription, signal::CtrlC};
///
/// enum Message {
/// CtrlC,
/// SignalError(std::io::Error),
/// }
///
/// // Create a subscription for Ctrl+C
/// let ctrl_c = Subscription::new(CtrlC::new())
/// .map(|result| match result {
/// Ok(()) => Message::CtrlC,
/// Err(e) => Message::SignalError(e),
/// });
/// ```
///
/// # Error Handling
///
/// This subscription yields `Result<(), io::Error>` values. The error case occurs
/// when the signal handler cannot be installed (typically only at subscription
/// creation time). Once the signal handler is successfully installed, it will
/// yield `Ok(())` each time Ctrl+C is pressed.
///
/// # Note
///
/// This is a singleton subscription - all instances are considered identical
/// and only one Ctrl+C handler will be active at a time.
#[derive(Debug, Clone, PartialEq, Eq, Default, Hash)]
pub struct CtrlC;
impl CtrlC {
/// Create a new Ctrl+C subscription.
///
/// # Example
///
/// ```rust
/// use tears::subscription::signal::CtrlC;
///
/// let ctrl_c = CtrlC::new();
/// ```
#[must_use]
pub const fn new() -> Self {
Self
}
}
impl SubscriptionSource for CtrlC {
type Output = Result<(), io::Error>;
fn stream(&self) -> BoxStream<'static, Self::Output> {
// Create a stream that yields () each time Ctrl+C is pressed
// NOTE: tokio::signal::windows::ctrl_c() returns Result<CtrlC, io::Error>
// If it fails, try_unfold yields a single error and ends the stream
// If it succeeds, it yields Ok(()) for each event received
stream::try_unfold(None, move |state: Option<TokioCtrlC>| async move {
let mut sig = match state {
None => {
// First call: initialize the signal handler
ctrl_c()?
}
Some(sig) => sig,
};
// Wait for signals
match sig.recv().await {
Some(()) => Ok(Some(((), Some(sig)))),
None => Ok(None), // End the stream
}
})
.boxed()
}
fn id(&self) -> SubscriptionId {
let mut hasher = DefaultHasher::new();
self.hash(&mut hasher);
SubscriptionId::of::<Self>(hasher.finish())
}
}
/// A subscription source for Windows Ctrl+Break events.
///
/// This provides a stream of Ctrl+Break events. Each time Ctrl+Break is pressed,
/// the subscription emits a unit value `()`.
///
/// # Platform
///
/// This is only available on Windows platforms.
///
/// # Example
///
/// ```rust,no_run
/// use tears::subscription::{Subscription, signal::CtrlBreak};
///
/// enum Message {
/// CtrlBreak,
/// SignalError(std::io::Error),
/// }
///
/// // Create a subscription for Ctrl+Break
/// let ctrl_break = Subscription::new(CtrlBreak::new())
/// .map(|result| match result {
/// Ok(()) => Message::CtrlBreak,
/// Err(e) => Message::SignalError(e),
/// });
/// ```
///
/// # Error Handling
///
/// This subscription yields `Result<(), io::Error>` values. The error case occurs
/// when the signal handler cannot be installed (typically only at subscription
/// creation time). Once the signal handler is successfully installed, it will
/// yield `Ok(())` each time Ctrl+Break is pressed.
///
/// # Note
///
/// This is a singleton subscription - all instances are considered identical
/// and only one Ctrl+Break handler will be active at a time.
#[derive(Debug, Clone, PartialEq, Eq, Default, Hash)]
pub struct CtrlBreak;
impl CtrlBreak {
/// Create a new Ctrl+Break subscription.
///
/// # Example
///
/// ```rust
/// use tears::subscription::signal::CtrlBreak;
///
/// let ctrl_break = CtrlBreak::new();
/// ```
#[must_use]
pub const fn new() -> Self {
Self
}
}
impl SubscriptionSource for CtrlBreak {
type Output = Result<(), io::Error>;
fn stream(&self) -> BoxStream<'static, Self::Output> {
// Create a stream that yields () each time Ctrl+Break is pressed
// NOTE: tokio::signal::windows::ctrl_break() returns Result<CtrlBreak, io::Error>
// If it fails, try_unfold yields a single error and ends the stream
// If it succeeds, it yields Ok(()) for each event received
stream::try_unfold(None, move |state: Option<TokioCtrlBreak>| async move {
let mut sig = match state {
None => {
// First call: initialize the signal handler
ctrl_break()?
}
Some(sig) => sig,
};
// Wait for signals
match sig.recv().await {
Some(()) => Ok(Some(((), Some(sig)))),
None => Ok(None), // End the stream
}
})
.boxed()
}
fn id(&self) -> SubscriptionId {
let mut hasher = DefaultHasher::new();
self.hash(&mut hasher);
SubscriptionId::of::<Self>(hasher.finish())
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_ctrl_c_id_consistency() {
let ctrl_c1 = CtrlC::new();
let ctrl_c2 = CtrlC::new();
// Same subscription should have the same ID
assert_eq!(ctrl_c1.id(), ctrl_c2.id());
}
#[test]
fn test_ctrl_break_id_consistency() {
let ctrl_break1 = CtrlBreak::new();
let ctrl_break2 = CtrlBreak::new();
// Same subscription should have the same ID
assert_eq!(ctrl_break1.id(), ctrl_break2.id());
}
#[test]
fn test_ctrl_c_and_ctrl_break_different_ids() {
let ctrl_c = CtrlC::new();
let ctrl_break = CtrlBreak::new();
// Different signal types should have different IDs
assert_ne!(ctrl_c.id(), ctrl_break.id());
}
}
}
#[cfg(windows)]
pub use windows_signal::{CtrlBreak, CtrlC};