scuffle_context/
ext.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
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
use std::future::{Future, IntoFuture};
use std::pin::Pin;
use std::task::Poll;

use futures_lite::Stream;
use tokio_util::sync::{WaitForCancellationFuture, WaitForCancellationFutureOwned};

use crate::{Context, ContextTracker};

/// A reference to a context which implements [`Future`] and can be polled.
/// Can either be owned or borrowed.
///
/// Create by using the [`From`] implementations.
pub struct ContextRef<'a> {
    inner: ContextRefInner<'a>,
}

impl From<Context> for ContextRef<'_> {
    fn from(ctx: Context) -> Self {
        ContextRef {
            inner: ContextRefInner::Owned {
                fut: ctx.token.cancelled_owned(),
                tracker: ctx.tracker,
            },
        }
    }
}

impl<'a> From<&'a Context> for ContextRef<'a> {
    fn from(ctx: &'a Context) -> Self {
        ContextRef {
            inner: ContextRefInner::Ref {
                fut: ctx.token.cancelled(),
            },
        }
    }
}

pin_project_lite::pin_project! {
    #[project = ContextRefInnerProj]
    enum ContextRefInner<'a> {
        Owned {
            #[pin] fut: WaitForCancellationFutureOwned,
            tracker: ContextTracker,
        },
        Ref {
            #[pin] fut: WaitForCancellationFuture<'a>,
        },
    }
}

impl std::future::Future for ContextRefInner<'_> {
    type Output = ();

    fn poll(self: Pin<&mut Self>, cx: &mut std::task::Context<'_>) -> Poll<Self::Output> {
        match self.project() {
            ContextRefInnerProj::Owned { fut, .. } => fut.poll(cx),
            ContextRefInnerProj::Ref { fut } => fut.poll(cx),
        }
    }
}

pin_project_lite::pin_project! {
    /// A future with a context attached to it.
    ///
    /// This future will be cancelled when the context is done.
    pub struct FutureWithContext<'a, F> {
        #[pin]
        future: F,
        #[pin]
        ctx: ContextRefInner<'a>,
        _marker: std::marker::PhantomData<&'a ()>,
    }
}

impl<F: Future> Future for FutureWithContext<'_, F> {
    type Output = Option<F::Output>;

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

        match (this.ctx.poll(cx), this.future.poll(cx)) {
            (_, Poll::Ready(v)) => std::task::Poll::Ready(Some(v)),
            (Poll::Ready(_), Poll::Pending) => std::task::Poll::Ready(None),
            (Poll::Pending, Poll::Pending) => std::task::Poll::Pending,
        }
    }
}

pub trait ContextFutExt<Fut> {
    /// Wraps a future with a context and cancels the future when the context is
    /// done.
    ///
    /// # Example
    ///
    /// ```rust
    /// # use scuffle_context::{Context, ContextFutExt};
    /// # tokio_test::block_on(async {
    /// let (ctx, handler) = Context::new();
    ///
    /// tokio::spawn(async {
    ///    // Do some work
    ///    tokio::time::sleep(std::time::Duration::from_secs(10)).await;
    /// }.with_context(ctx));
    ///
    /// // Will stop the spawned task and cancel all associated futures.
    /// handler.cancel();
    /// # });
    /// ```
    fn with_context<'a>(self, ctx: impl Into<ContextRef<'a>>) -> FutureWithContext<'a, Fut>
    where
        Self: Sized;
}

impl<F: IntoFuture> ContextFutExt<F::IntoFuture> for F {
    fn with_context<'a>(self, ctx: impl Into<ContextRef<'a>>) -> FutureWithContext<'a, F::IntoFuture>
    where
        F: IntoFuture,
    {
        FutureWithContext {
            future: self.into_future(),
            ctx: ctx.into().inner,
            _marker: std::marker::PhantomData,
        }
    }
}

pin_project_lite::pin_project! {
    /// A stream with a context attached to it.
    ///
    /// This stream will be cancelled when the context is done.
    pub struct StreamWithContext<'a, F> {
        #[pin]
        stream: F,
        #[pin]
        ctx: ContextRefInner<'a>,
        _marker: std::marker::PhantomData<&'a ()>,
    }
}

impl<F: Stream> Stream for StreamWithContext<'_, F> {
    type Item = F::Item;

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

        match (this.ctx.poll(cx), this.stream.poll_next(cx)) {
            (Poll::Ready(_), _) => std::task::Poll::Ready(None),
            (Poll::Pending, Poll::Ready(v)) => std::task::Poll::Ready(v),
            (Poll::Pending, Poll::Pending) => std::task::Poll::Pending,
        }
    }

    fn size_hint(&self) -> (usize, Option<usize>) {
        self.stream.size_hint()
    }
}

pub trait ContextStreamExt<Stream> {
    /// Wraps a stream with a context and stops the stream when the context is
    /// done.
    ///
    /// # Example
    ///
    /// ```rust
    /// # use scuffle_context::{Context, ContextStreamExt};
    /// # use futures_lite as futures;
    /// # use futures_lite::StreamExt;
    /// # tokio_test::block_on(async {
    /// let (ctx, handler) = Context::new();
    ///
    /// tokio::spawn(async {
    ///     futures::stream::iter(1..=10).then(|d| async move {
    ///         // Do some work
    ///         tokio::time::sleep(std::time::Duration::from_secs(d)).await;
    ///     }).with_context(ctx);
    /// });
    ///
    /// // Will stop the spawned task and cancel all associated streams.
    /// handler.cancel();
    /// # });
    /// ```
    fn with_context<'a>(self, ctx: impl Into<ContextRef<'a>>) -> StreamWithContext<'a, Stream>
    where
        Self: Sized;
}

impl<F: Stream> ContextStreamExt<F> for F {
    fn with_context<'a>(self, ctx: impl Into<ContextRef<'a>>) -> StreamWithContext<'a, F> {
        StreamWithContext {
            stream: self,
            ctx: ctx.into().inner,
            _marker: std::marker::PhantomData,
        }
    }
}

#[cfg_attr(all(coverage_nightly, test), coverage(off))]
#[cfg(test)]
mod tests {
    use std::pin::pin;

    use futures_lite::{Stream, StreamExt};
    use scuffle_future_ext::FutureExt;

    use super::{Context, ContextFutExt, ContextStreamExt};

    #[tokio::test]
    async fn future() {
        let (ctx, handler) = Context::new();

        let task = tokio::spawn(
            async {
                // Do some work
                tokio::time::sleep(std::time::Duration::from_secs(10)).await;
            }
            .with_context(ctx),
        );

        // Sleep for a bit to make sure the future is polled at least once.
        tokio::time::sleep(std::time::Duration::from_millis(10)).await;

        // Will stop the spawned task and cancel all associated futures.
        handler.shutdown().await;

        task.await.unwrap();
    }

    #[tokio::test]
    async fn future_result() {
        let (ctx, handler) = Context::new();

        let task = tokio::spawn(async { 1 }.with_context(ctx));

        // Will stop the spawned task and cancel all associated futures.
        handler.shutdown().await;

        assert_eq!(task.await.unwrap(), Some(1));
    }

    #[tokio::test]
    async fn future_ctx_by_ref() {
        let (ctx, handler) = Context::new();

        let task = tokio::spawn(async move {
            async {
                // Do some work
                tokio::time::sleep(std::time::Duration::from_secs(10)).await;
            }
            .with_context(&ctx)
            .await;

            drop(ctx);
        });

        // Will stop the spawned task and cancel all associated futures.
        handler.shutdown().await;

        task.await.unwrap();
    }

    #[tokio::test]
    async fn stream() {
        let (ctx, handler) = Context::new();

        {
            let mut stream = pin!(futures_lite::stream::iter(0..10).with_context(ctx));

            assert_eq!(stream.size_hint(), (10, Some(10)));

            assert_eq!(stream.next().await, Some(0));
            assert_eq!(stream.next().await, Some(1));
            assert_eq!(stream.next().await, Some(2));
            assert_eq!(stream.next().await, Some(3));

            // Will stop the spawned task and cancel all associated streams.
            handler.cancel();

            assert_eq!(stream.next().await, None);
        }

        handler.shutdown().await;
    }

    #[tokio::test]
    async fn pending_stream() {
        let (ctx, handler) = Context::new();

        {
            let mut stream = pin!(futures_lite::stream::pending::<()>().with_context(ctx));

            // This is expected to timeout
            assert!(stream
                .next()
                .with_timeout(std::time::Duration::from_millis(200))
                .await
                .is_err());
        }

        handler.shutdown().await;
    }
}