scuffle_context/
lib.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
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
#![doc = include_str!("../README.md")]

use std::future::{Future, IntoFuture};
use std::pin::Pin;
use std::sync::atomic::{AtomicBool, AtomicUsize};
use std::sync::Arc;
use std::task::Poll;

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

#[derive(Debug)]
struct ContextTracker(Arc<ContextTrackerInner>);

impl Drop for ContextTracker {
	fn drop(&mut self) {
		let remaining = self.0.active_count.fetch_sub(1, std::sync::atomic::Ordering::Relaxed);
		if remaining == 1 && self.0.stopped.load(std::sync::atomic::Ordering::Relaxed) {
			self.0.notify.notify_waiters();
		}
	}
}

#[derive(Debug)]
struct ContextTrackerInner {
	stopped: AtomicBool,
	active_count: AtomicUsize,
	notify: tokio::sync::Notify,
}

impl ContextTrackerInner {
	fn new() -> Arc<Self> {
		Arc::new(Self {
			stopped: AtomicBool::new(false),
			active_count: AtomicUsize::new(0),
			notify: tokio::sync::Notify::new(),
		})
	}

	fn child(self: &Arc<Self>) -> ContextTracker {
		self.active_count.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
		ContextTracker(self.clone())
	}

	fn stop(&self) {
		self.stopped.store(true, std::sync::atomic::Ordering::Relaxed);
	}

	async fn wait(&self) {
		let notify = self.notify.notified();

		// If there are no active children, then the notify will never be called
		if self.active_count.load(std::sync::atomic::Ordering::Relaxed) == 0 {
			return;
		}

		notify.await;
	}
}

/// A context for cancelling futures and waiting for shutdown
///
/// A context can be created from a handler or another context so to have a
/// hierarchy of contexts
///
/// Contexts can then be attached to futures or streams in order to
/// automatically cancel them when the context is done, when invoking
/// `Handler::cancel`. The `Handler::shutdown` method will block until all
/// contexts have been dropped allowing for a graceful shutdown.
#[derive(Debug)]
pub struct Context {
	token: CancellationToken,
	tracker: ContextTracker,
}

impl Clone for Context {
	fn clone(&self) -> Self {
		Self {
			token: self.token.clone(),
			tracker: self.tracker.0.child(),
		}
	}
}

impl Context {
	#[must_use]
	/// Create a new context using the global handler
	/// Returns a tuple and a child handler
	pub fn new() -> (Self, Handler) {
		Handler::global().new_child()
	}

	#[must_use]
	/// Create a new child context from this context
	/// Returns a tuple and a child handler
	pub fn new_child(&self) -> (Self, Handler) {
		let token = self.token.child_token();
		let tracker = ContextTrackerInner::new();

		(
			Self {
				tracker: tracker.child(),
				token: token.clone(),
			},
			Handler {
				token: Arc::new(TokenDropGuard(token)),
				tracker,
			},
		)
	}

	#[must_use]
	/// Returns the global context
	pub fn global() -> Self {
		Handler::global().context()
	}

	/// Waits for the context to be done (the handler to be shutdown)
	pub async fn done(&self) {
		self.token.cancelled().await;
	}

	/// The same as done but takes ownership of the context
	pub async fn into_done(self) {
		self.done().await;
	}

	/// Returns true if the context is done
	#[must_use]
	pub fn is_done(&self) -> bool {
		self.token.is_cancelled()
	}
}

#[derive(Debug)]
struct TokenDropGuard(CancellationToken);

impl TokenDropGuard {
	#[must_use]
	fn child(&self) -> CancellationToken {
		self.0.child_token()
	}

	fn cancel(&self) {
		self.0.cancel();
	}
}

impl Drop for TokenDropGuard {
	fn drop(&mut self) {
		self.cancel();
	}
}

#[derive(Debug, Clone)]
pub struct Handler {
	token: Arc<TokenDropGuard>,
	tracker: Arc<ContextTrackerInner>,
}

impl Default for Handler {
	fn default() -> Self {
		Self::new()
	}
}

impl Handler {
	#[must_use]
	/// Create a new handler
	pub fn new() -> Handler {
		let token = CancellationToken::new();
		let tracker = ContextTrackerInner::new();

		Handler {
			token: Arc::new(TokenDropGuard(token)),
			tracker,
		}
	}

	#[must_use]
	/// Returns the global handler
	pub fn global() -> &'static Self {
		static GLOBAL: std::sync::OnceLock<Handler> = std::sync::OnceLock::new();

		GLOBAL.get_or_init(Handler::new)
	}

	/// Shutdown the handler and wait for all contexts to be done
	pub async fn shutdown(&self) {
		self.cancel();
		self.done().await;
	}

	/// Waits for the handler to be done (waiting for all contexts to be done)
	pub async fn done(&self) {
		self.token.0.cancelled().await;
		self.tracker.wait().await;
	}

	/// Waits for the handler to be done (waiting for all contexts to be done)
	/// Returns once all contexts are done, even if the handler is not done and
	/// contexts can be created after this call.
	pub async fn wait(&self) {
		self.tracker.wait().await;
	}

	#[must_use]
	/// Create a new context from this handler
	pub fn context(&self) -> Context {
		Context {
			token: self.token.child(),
			tracker: self.tracker.child(),
		}
	}

	#[must_use]
	/// Create a new child context from this handler
	pub fn new_child(&self) -> (Context, Handler) {
		self.context().new_child()
	}

	/// Cancel the handler
	pub fn cancel(&self) {
		self.tracker.stop();
		self.token.cancel();
	}

	pub fn is_done(&self) -> bool {
		self.token.0.is_cancelled()
	}
}

pin_project_lite::pin_project! {
	/// A reference to a context
	/// Can either be owned or borrowed
	pub struct ContextRef<'a> {
		#[pin]
		inner: ContextRefInner<'a>,
	}
}

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 ContextRef<'_> {
	type Output = ();

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

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(),
			},
		}
	}
}

pub trait ContextFutExt<Fut> {
	/// Wraps a future with a context, allowing the future to be cancelled when
	/// the context is done
	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(),
			_marker: std::marker::PhantomData,
		}
	}
}

pub trait ContextStreamExt<Stream> {
	/// Wraps a stream with a context, allowing the stream to be stopped when
	/// the context is done
	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(),
			_marker: std::marker::PhantomData,
		}
	}
}

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: ContextRef<'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),
			_ => std::task::Poll::Pending,
		}
	}
}

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: ContextRef<'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(v)) => std::task::Poll::Ready(v),
			(Poll::Ready(_), Poll::Pending) => std::task::Poll::Ready(None),
			_ => std::task::Poll::Pending,
		}
	}

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