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
use std::{
    any::Any,
    io,
    os::raw::c_int,
    pin::Pin,
    task::{self, Poll},
};

use pin_project::pin_project;
use sealed::sealed;
use tokio::signal;
#[cfg(unix)]
use tokio::signal::unix;
#[cfg(windows)]
use tokio::signal::windows;

use crate::{
    envelope::{Envelope, MessageKind},
    message::Message,
    source::{SourceArc, SourceStream, UnattachedSource},
    tracing::TraceId,
    Addr,
};

/// A source that emits a message once a signal is received.
/// Clones the message on every tick.
///
/// It's based on the tokio implementation, so it should be useful to read
/// about [caveats](https://docs.rs/tokio/latest/tokio/signal/unix/struct.Signal.html).
///
/// # Tracing
///
/// Every message starts a new trace, thus a new trace id is generated and
/// assigned to the current scope.
///
/// # Example
///
/// ```
/// # use std::time::Duration;
/// # use elfo_core as elfo;
/// # async fn exec(mut ctx: elfo::Context) {
/// # use elfo::{message, msg};
/// use elfo::signal::{Signal, SignalKind};
///
/// #[message]
/// struct ReloadFile;
///
/// ctx.attach(Signal::new(SignalKind::UnixHangup, ReloadFile));
///
/// while let Some(envelope) = ctx.recv().await {
///     msg!(match envelope {
///         ReloadFile => { /* ... */ },
///     });
/// }
/// # }
/// ```
pub struct Signal<M> {
    source: SourceArc<SignalSource<M>>,
}

#[sealed]
impl<M: Message> crate::source::SourceHandle for Signal<M> {
    fn is_terminated(&self) -> bool {
        self.source.lock().is_none()
    }

    fn terminate(self) {
        ward!(self.source.lock()).terminate();
    }
}

#[pin_project]
struct SignalSource<M> {
    message: M,
    inner: SignalInner,
}

enum SignalInner {
    Disabled,
    #[cfg(windows)]
    WindowsCtrlC(windows::CtrlC),
    #[cfg(unix)]
    Unix(unix::Signal),
}

/// A kind of signal to listen to.
///
/// * `Unix*` variants are available only on UNIX systems and produce nothing
/// on other systems.
/// * `Windows*` variants are available only on Windows and produce nothing
/// on other systems.
///
/// It helps to avoid writing `#[cfg(_)]` everywhere around signals.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum SignalKind {
    /// The "ctrl-c" notification.
    WindowsCtrlC,

    /// Any valid OS signal.
    UnixRaw(c_int),
    /// SIGALRM
    UnixAlarm,
    /// SIGCHLD
    UnixChild,
    /// SIGHUP
    UnixHangup,
    /// SIGINT
    UnixInterrupt,
    /// SIGIO
    UnixIo,
    /// SIGPIPE
    UnixPipe,
    /// SIGQUIT
    UnixQuit,
    /// SIGTERM
    UnixTerminate,
    /// SIGUSR1
    UnixUser1,
    /// SIGUSR2
    UnixUser2,
    /// SIGWINCH
    UnixWindowChange,
}

impl<M: Message> Signal<M> {
    /// Creates an unattached instance of [`Signal`].
    pub fn new(kind: SignalKind, message: M) -> UnattachedSource<Self> {
        let inner = SignalInner::new(kind).unwrap_or_else(|err| {
            tracing::warn!(kind = ?kind, error = %err, "failed to create a signal handler");
            SignalInner::Disabled
        });

        let source = SourceArc::new(SignalSource { message, inner }, false);
        UnattachedSource::new(source, |source| Self { source })
    }

    /// Replaces a stored message with the provided one.
    pub fn set_message(&self, message: M) {
        let mut guard = ward!(self.source.lock());
        *guard.stream().project().message = message;
    }
}

impl SignalInner {
    #[cfg(unix)]
    fn new(kind: SignalKind) -> io::Result<SignalInner> {
        use signal::unix::SignalKind as U;

        let kind = match kind {
            SignalKind::UnixRaw(signum) => U::from_raw(signum),
            SignalKind::UnixAlarm => U::alarm(),
            SignalKind::UnixChild => U::child(),
            SignalKind::UnixHangup => U::hangup(),
            SignalKind::UnixInterrupt => U::interrupt(),
            SignalKind::UnixIo => U::io(),
            SignalKind::UnixPipe => U::pipe(),
            SignalKind::UnixQuit => U::quit(),
            SignalKind::UnixTerminate => U::terminate(),
            SignalKind::UnixUser1 => U::user_defined1(),
            SignalKind::UnixUser2 => U::user_defined2(),
            SignalKind::UnixWindowChange => U::window_change(),
            _ => return Ok(SignalInner::Disabled),
        };

        unix::signal(kind).map(SignalInner::Unix)
    }

    #[cfg(windows)]
    fn new(kind: SignalKind) -> io::Result<SignalInner> {
        match kind {
            SignalKind::WindowsCtrlC => windows::ctrl_c().map(SignalInner::WindowsCtrlC),
            _ => Ok(SignalInner::Disabled),
        }
    }

    fn poll_recv(&mut self, cx: &mut task::Context<'_>) -> Poll<Option<()>> {
        match self {
            SignalInner::Disabled => Poll::Ready(None),
            #[cfg(windows)]
            SignalInner::WindowsCtrlC(inner) => inner.poll_recv(cx),
            #[cfg(unix)]
            SignalInner::Unix(inner) => inner.poll_recv(cx),
        }
    }
}

impl<M: Message> SourceStream for SignalSource<M> {
    fn as_any_mut(self: Pin<&mut Self>) -> Pin<&mut dyn Any> {
        // SAFETY: we only cast here, it cannot move data.
        unsafe { self.map_unchecked_mut(|s| s) }
    }

    fn poll_recv(self: Pin<&mut Self>, cx: &mut task::Context<'_>) -> Poll<Option<Envelope>> {
        let this = self.project();

        match this.inner.poll_recv(cx) {
            Poll::Ready(Some(())) => {}
            Poll::Ready(None) => return Poll::Ready(None),
            Poll::Pending => return Poll::Pending,
        }

        let message = this.message.clone();
        let kind = MessageKind::Regular { sender: Addr::NULL };
        let trace_id = TraceId::generate();
        let envelope = Envelope::with_trace_id(message, kind, trace_id).upcast();
        Poll::Ready(Some(envelope))
    }
}