relay_system/service/
status.rs

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
use std::fmt::{self, Debug};
use std::future::Future;
use std::pin::Pin;
use std::task::{Context, Poll};

use tokio::task::JoinHandle;

use futures::future::{FutureExt as _, Shared};

/// The service failed.
#[derive(Debug)]
pub struct ServiceError(tokio::task::JoinError);

impl ServiceError {
    /// Returns true if the error was caused by a panic.
    pub fn is_panic(&self) -> bool {
        self.0.is_panic()
    }

    /// Consumes the error and returns the panic that caused it.
    ///
    /// Returns `None` if the error was not caused by a panic.
    pub fn into_panic(self) -> Option<Box<dyn std::any::Any + Send + 'static>> {
        self.0.try_into_panic().ok()
    }
}

impl fmt::Display for ServiceError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}", &self.0)
    }
}

impl std::error::Error for ServiceError {}

/// An owned handle to await the termination of a service.
///
/// This is very similar to a [`std::thread::JoinHandle`] or [`tokio::task::JoinHandle`].
///
/// The handle does not need to be awaited or polled for the service to start execution.
/// On drop, the join handle will detach from the service and the service will continue execution.
pub struct ServiceJoinHandle {
    fut: Option<Shared<MapJoinResult>>,
    error_rx: tokio::sync::oneshot::Receiver<tokio::task::JoinError>,
    handle: tokio::task::AbortHandle,
}

impl ServiceJoinHandle {
    /// Returns `true` if the service has finished.
    pub fn is_finished(&self) -> bool {
        self.handle.is_finished()
    }
}

impl Future for ServiceJoinHandle {
    type Output = Result<(), ServiceError>;

    fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
        if let Some(fut) = &mut self.fut {
            if let Ok(()) = futures::ready!(fut.poll_unpin(cx)) {
                return Poll::Ready(Ok(()));
            }
        }
        self.fut = None;

        match futures::ready!(self.error_rx.poll_unpin(cx)) {
            Ok(error) => Poll::Ready(Err(ServiceError(error))),
            Err(_) => Poll::Ready(Ok(())),
        }
    }
}

/// A [`ServiceError`] without the service error/panic.
///
/// It does not contain the original error, just the status.
#[derive(Debug, Clone)]
pub struct ServiceStatusError {
    is_panic: bool,
}

impl ServiceStatusError {
    /// Returns true if the error was caused by a panic.
    pub fn is_panic(&self) -> bool {
        self.is_panic
    }
}

impl fmt::Display for ServiceStatusError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self.is_panic() {
            true => write!(f, "service panic"),
            false => write!(f, "service failed"),
        }
    }
}

impl std::error::Error for ServiceStatusError {}

/// A companion handle to [`ServiceJoinHandle`].
///
/// The handle can also be awaited and queried for the termination status of a service,
/// but unlike the [`ServiceJoinHandle`] it only reports an error status and not
/// the original error/panic.
///
/// This handle can also be freely cloned and therefor awaited multiple times.
#[derive(Debug, Clone)]
pub struct ServiceStatusJoinHandle {
    fut: Shared<MapJoinResult>,
    handle: tokio::task::AbortHandle,
}

impl ServiceStatusJoinHandle {
    /// Returns `true` if the service has finished.
    pub fn is_finished(&self) -> bool {
        self.handle.is_finished()
    }
}

impl Future for ServiceStatusJoinHandle {
    type Output = Result<(), ServiceStatusError>;

    fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
        self.fut.poll_unpin(cx)
    }
}

/// Turns a [`tokio::task::JoinHandle<()>`] from a service task into two separate handles.
///
/// Each returned handle can be awaited for the termination of a service
/// and be queried for early termination synchronously using `is_terminated`,
/// but only the [`ServiceJoinHandle`] yields the original error/panic.
pub(crate) fn split(
    handle: tokio::task::JoinHandle<()>,
) -> (ServiceStatusJoinHandle, ServiceJoinHandle) {
    let (tx, rx) = tokio::sync::oneshot::channel();

    let handle1 = handle.abort_handle();
    let handle2 = handle.abort_handle();

    let shared = MapJoinResult {
        handle,
        error: Some(tx),
    }
    .shared();

    (
        ServiceStatusJoinHandle {
            handle: handle1,
            fut: shared.clone(),
        },
        ServiceJoinHandle {
            error_rx: rx,
            handle: handle2,
            fut: Some(shared),
        },
    )
}

/// Utility future which detaches the error/panic of a [`JoinHandle`].
#[derive(Debug)]
struct MapJoinResult {
    handle: JoinHandle<()>,
    error: Option<tokio::sync::oneshot::Sender<tokio::task::JoinError>>,
}

impl Future for MapJoinResult {
    type Output = Result<(), ServiceStatusError>;

    fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
        let ret = match futures::ready!(self.handle.poll_unpin(cx)) {
            Ok(()) => Ok(()),
            Err(error) => {
                let status = ServiceStatusError {
                    is_panic: error.is_panic(),
                };

                let _ = self
                    .error
                    .take()
                    .expect("shared future to not be ready multiple times")
                    .send(error);

                Err(status)
            }
        };

        Poll::Ready(ret)
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    macro_rules! assert_pending {
        ($fut:expr) => {
            match &mut $fut {
                fut => {
                    for _ in 0..30 {
                        assert!(matches!(futures::poll!(&mut *fut), Poll::Pending));
                    }
                }
            }
        };
    }

    #[tokio::test]
    async fn test_split_no_error() {
        let (tx, rx) = tokio::sync::oneshot::channel();

        let (mut status, mut error) = split(crate::spawn!(async move {
            rx.await.unwrap();
        }));

        assert_pending!(status);
        assert_pending!(error);

        assert!(!status.is_finished());
        assert!(!error.is_finished());

        tx.send(()).unwrap();

        assert!(status.await.is_ok());
        assert!(error.is_finished());
        assert!(error.await.is_ok());
    }

    #[tokio::test]
    async fn test_split_with_error_await_status_first() {
        let (tx, rx) = tokio::sync::oneshot::channel();

        let (mut status, mut error) = split(crate::spawn!(async move {
            rx.await.unwrap();
            panic!("test panic");
        }));

        assert_pending!(status);
        assert_pending!(error);

        assert!(!status.is_finished());
        assert!(!error.is_finished());

        tx.send(()).unwrap();

        let status = status.await.unwrap_err();
        assert!(status.is_panic());

        assert!(error.is_finished());

        let error = error.await.unwrap_err();
        assert!(error.is_panic());
        assert!(error.into_panic().unwrap().downcast_ref() == Some(&"test panic"));
    }

    #[tokio::test]
    async fn test_split_with_error_await_error_first() {
        let (tx, rx) = tokio::sync::oneshot::channel();

        let (mut status, mut error) = split(crate::spawn!(async move {
            rx.await.unwrap();
            panic!("test panic");
        }));

        assert_pending!(status);
        assert_pending!(error);

        assert!(!status.is_finished());
        assert!(!error.is_finished());

        tx.send(()).unwrap();

        let error = error.await.unwrap_err();
        assert!(error.is_panic());
        assert!(error.into_panic().unwrap().downcast_ref() == Some(&"test panic"));

        assert!(status.is_finished());

        let status = status.await.unwrap_err();
        assert!(status.is_panic());
    }
}