Documentation
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
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
//! Tasks submitted from other threads through [`crate::Handle`].
//!
//! A submission allocates one [`Job`], holding the future and later its
//! output. The owner thread polls the future in place through a [`Runner`]
//! task, the joining [`RemoteJoin`] takes the output from the same allocation.
use std::cell::UnsafeCell;
use std::sync::{Arc, atomic::AtomicU8, atomic::Ordering};
use std::task::{Context, Poll, ready};
use std::{future::Future, mem, pin::Pin};

use atomic_waker::AtomicWaker;

/// The job has finished, its stage is no longer accessed by the owner.
const DONE: u8 = 1;
/// The joiner requested cancellation.
const CANCELLED: u8 = 2;
/// A joiner may cancel the job, the runner registers its waker.
const JOINABLE: u8 = 4;

enum Stage<F: Future> {
    Running(F),
    Done(F::Output),
    Empty,
}

/// A future submitted to an owner thread, and its output.
pub(crate) struct Job<F: Future> {
    state: AtomicU8,
    /// Woken once the job is done.
    join_waker: AtomicWaker,
    /// Woken to let the runner observe a cancellation.
    run_waker: AtomicWaker,
    stage: UnsafeCell<Stage<F>>,
}

// The owner accesses `stage` until it publishes `DONE`, the joiner only after
// observing it. The future is polled and dropped on the owner thread, unless
// the submission is rejected before it is published.
unsafe impl<F: Future + Send> Send for Job<F> where F::Output: Send {}
unsafe impl<F: Future + Send> Sync for Job<F> where F::Output: Send {}

impl<F: Future> Job<F> {
    /// Allocates a job, `joinable` jobs can be cancelled by their joiner.
    pub(crate) fn new(future: F, joinable: bool) -> Arc<Self> {
        Arc::new(Self {
            state: AtomicU8::new(if joinable { JOINABLE } else { 0 }),
            join_waker: AtomicWaker::new(),
            run_waker: AtomicWaker::new(),
            stage: UnsafeCell::new(Stage::Running(future)),
        })
    }

    /// Drops the future without an output and publishes completion.
    ///
    /// Called on the owner thread, or on the submitting thread if the job was
    /// never published.
    pub(crate) fn close(&self) {
        if self.state.load(Ordering::Acquire) & DONE == 0 {
            self.finish(Stage::Empty);
        }
    }

    /// Drops the pinned future in place, then publishes the new stage even on unwind.
    fn finish(&self, stage: Stage<F>) {
        struct Complete<'a, F: Future>(&'a Job<F>);

        impl<F: Future> Drop for Complete<'_, F> {
            fn drop(&mut self) {
                self.0.complete();
            }
        }

        let _complete = Complete(self);
        // SAFETY: before DONE, only the owner (or unpublished submitter) accesses
        // the stage. Assignment drops the future in place and installs the new
        // stage even if its destructor panics, before the guard publishes DONE.
        unsafe { *self.stage.get() = stage };
    }

    fn complete(&self) {
        self.state.fetch_or(DONE, Ordering::AcqRel);
        // the runner's waker must not retain its task
        drop(self.run_waker.take());
        self.join_waker.wake();
    }
}

/// Owner-thread task polling a [`Job`] in place.
pub(crate) struct Runner<F: Future>(pub(crate) Arc<Job<F>>);

impl<F: Future> Future for Runner<F> {
    type Output = ();

    fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<()> {
        let job = &*self.0;
        let state = job.state.load(Ordering::Acquire);
        if state & DONE != 0 {
            return Poll::Ready(());
        }
        if state & CANCELLED != 0 {
            job.close();
            return Poll::Ready(());
        }
        if state & JOINABLE != 0 {
            job.run_waker.register(cx.waker());
            if job.state.load(Ordering::Acquire) & CANCELLED != 0 {
                job.close();
                return Poll::Ready(());
            }
        }
        // SAFETY: not done, only the owner accesses the stage
        let slot = unsafe { &mut *job.stage.get() };
        let Stage::Running(fut) = slot else {
            unreachable!("job polled after completion")
        };
        // SAFETY: the future stays in this allocation until it is dropped in place.
        let out = ready!(unsafe { Pin::new_unchecked(fut) }.poll(cx));
        job.finish(Stage::Done(out));
        Poll::Ready(())
    }
}

impl<F: Future> Drop for Runner<F> {
    /// Drops an unfinished future on the owner thread, the joiner gets an error.
    fn drop(&mut self) {
        self.0.close();
    }
}

trait JoinJob<T>: Send + Sync {
    fn poll_join(&self, cx: &mut Context<'_>) -> Poll<Option<T>>;
    fn cancel(&self);
    fn detach(&self);
    fn is_finished(&self) -> bool;
}

impl<F> JoinJob<F::Output> for Job<F>
where
    F: Future + Send,
    F::Output: Send,
{
    fn poll_join(&self, cx: &mut Context<'_>) -> Poll<Option<F::Output>> {
        if self.state.load(Ordering::Acquire) & DONE == 0 {
            self.join_waker.register(cx.waker());
            if self.state.load(Ordering::Acquire) & DONE == 0 {
                return Poll::Pending;
            }
        }
        // SAFETY: done, the owner no longer accesses the stage and the
        // joiner is unique
        match mem::replace(unsafe { &mut *self.stage.get() }, Stage::Empty) {
            Stage::Done(out) => Poll::Ready(Some(out)),
            _ => Poll::Ready(None),
        }
    }

    fn cancel(&self) {
        self.state.fetch_or(CANCELLED, Ordering::AcqRel);
        self.run_waker.wake();
    }

    fn detach(&self) {
        // no joiner can cancel, the runner stops registering its waker
        self.state.fetch_and(!JOINABLE, Ordering::AcqRel);
    }

    fn is_finished(&self) -> bool {
        self.state.load(Ordering::Acquire) & DONE != 0
    }
}

/// The joining side of a [`Job`].
pub(crate) struct RemoteJoin<T>(Arc<dyn JoinJob<T>>);

impl<T> RemoteJoin<T> {
    pub(crate) fn new<F>(job: Arc<Job<F>>) -> Self
    where
        F: Future<Output = T> + Send + 'static,
        T: Send + 'static,
    {
        Self(job)
    }

    /// Resolves to `None` if the job ended without an output.
    pub(crate) fn poll_join(&self, cx: &mut Context<'_>) -> Poll<Option<T>> {
        self.0.poll_join(cx)
    }

    /// Requests cancellation, the owner drops the future.
    pub(crate) fn cancel(&self) {
        self.0.cancel();
    }

    pub(crate) fn is_finished(&self) -> bool {
        self.0.is_finished()
    }
}

impl<T> Drop for RemoteJoin<T> {
    fn drop(&mut self) {
        self.0.detach();
    }
}

impl<T> std::fmt::Debug for RemoteJoin<T> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("RemoteJoin")
            .field("finished", &self.is_finished())
            .finish()
    }
}

#[cfg(any(feature = "tokio", feature = "compio"))]
pub(crate) use self::spawner::Spawner;

#[cfg(any(feature = "tokio", feature = "compio"))]
mod spawner {
    use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
    use std::task::{Context, Poll};
    use std::{fmt, future::Future, pin::Pin, sync::Arc, thread};

    use atomic_waker::AtomicWaker;
    use crossbeam_queue::SegQueue;

    use super::{Job, Runner};
    use crate::rt::{ThreadId, current_thread_id, try_current_thread_id};

    /// Jobs started per poll of the drain task.
    const BATCH: usize = 128;
    /// The remaining bits count admitted publications.
    const CLOSED: usize = 1 << (usize::BITS - 1);

    trait RunJob: Send + Sync {
        fn spawn_local(self: Arc<Self>);
        fn close(&self);
    }

    impl<F> RunJob for Job<F>
    where
        F: Future + Send + 'static,
        F::Output: Send + 'static,
    {
        fn spawn_local(self: Arc<Self>) {
            crate::spawn_detached(Runner(self));
        }

        fn close(&self) {
            Job::close(self);
        }
    }

    /// FIFO of jobs submitted to an arbiter thread from other threads.
    pub(crate) struct Spawner {
        owner: ThreadId,
        /// Closed bit and count of publications in progress.
        admission: AtomicUsize,
        /// Coalesces drain task wake ups.
        notified: AtomicBool,
        waker: AtomicWaker,
        queue: SegQueue<Arc<dyn RunJob>>,
    }

    impl Spawner {
        /// Creates a spawner owned by the current thread and starts its drain
        /// task on the current runtime.
        pub(crate) fn start() -> Arc<Self> {
            let spawner = Arc::new(Self {
                owner: current_thread_id(),
                admission: AtomicUsize::new(0),
                notified: AtomicBool::new(false),
                waker: AtomicWaker::new(),
                queue: SegQueue::new(),
            });
            crate::spawn_detached(Drain(spawner.clone()));
            spawner
        }

        /// Returns whether the current thread owns the spawner.
        pub(crate) fn is_owner(&self) -> bool {
            Some(self.owner) == try_current_thread_id()
        }

        /// Publishes a job, a rejected job is closed on the current thread.
        pub(crate) fn submit<F>(&self, job: Arc<Job<F>>)
        where
            F: Future + Send + 'static,
            F::Output: Send + 'static,
        {
            if !self.admit() {
                job.close();
                return;
            }
            self.queue.push(job);
            self.admission.fetch_sub(1, Ordering::Release);
            if !self.notified.swap(true, Ordering::AcqRel) {
                self.waker.wake();
            }
        }

        fn admit(&self) -> bool {
            let mut state = self.admission.load(Ordering::Acquire);
            loop {
                if state & CLOSED != 0 {
                    return false;
                }
                match self.admission.compare_exchange_weak(
                    state,
                    state + 1,
                    Ordering::Acquire,
                    Ordering::Acquire,
                ) {
                    Ok(_) => return true,
                    Err(v) => state = v,
                }
            }
        }

        /// Rejects new jobs and closes queued ones on the owner thread.
        fn close(&self) {
            self.admission.fetch_or(CLOSED, Ordering::AcqRel);
            while self.admission.load(Ordering::Acquire) != CLOSED {
                thread::yield_now();
            }
            while let Some(job) = self.queue.pop() {
                job.close();
            }
        }
    }

    impl fmt::Debug for Spawner {
        fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
            f.debug_struct("Spawner")
                .field("owner", &self.owner)
                .finish_non_exhaustive()
        }
    }

    /// Owner-thread task starting submitted jobs as local tasks.
    struct Drain(Arc<Spawner>);

    impl Future for Drain {
        type Output = ();

        fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<()> {
            let spawner = &*self.0;
            spawner.waker.register(cx.waker());
            // a job pushed after this swap notifies again
            spawner.notified.swap(false, Ordering::AcqRel);
            for _ in 0..BATCH {
                match spawner.queue.pop() {
                    Some(job) => job.spawn_local(),
                    None => return Poll::Pending,
                }
            }
            cx.waker().wake_by_ref();
            Poll::Pending
        }
    }

    impl Drop for Drain {
        fn drop(&mut self) {
            self.0.close();
        }
    }
}

#[cfg(test)]
mod tests {
    use std::cell::Cell;
    use std::marker::PhantomPinned;
    use std::panic::{AssertUnwindSafe, catch_unwind};
    use std::sync::atomic::{AtomicBool, AtomicUsize};
    use std::task::{Wake, Waker};

    use super::*;

    #[derive(Default)]
    struct Probe {
        drops: AtomicUsize,
        output_drops: AtomicUsize,
        moved: AtomicBool,
        wakes: AtomicUsize,
        early_wake: AtomicBool,
    }

    impl Wake for Probe {
        fn wake(self: Arc<Self>) {
            self.wakes.fetch_add(1, Ordering::SeqCst);
            self.early_wake
                .fetch_or(self.drops.load(Ordering::SeqCst) == 0, Ordering::SeqCst);
        }
    }

    struct Output(Arc<Probe>);

    impl Drop for Output {
        fn drop(&mut self) {
            self.0.output_drops.fetch_add(1, Ordering::SeqCst);
        }
    }

    struct PinnedFuture {
        address: Cell<usize>,
        probe: Arc<Probe>,
        ready: bool,
        panics: bool,
        _pin: PhantomPinned,
    }

    impl Future for PinnedFuture {
        type Output = Output;

        fn poll(self: Pin<&mut Self>, _: &mut Context<'_>) -> Poll<Output> {
            let this = self.as_ref().get_ref();
            this.address.set(std::ptr::from_ref(this).addr());
            if this.ready {
                Poll::Ready(Output(this.probe.clone()))
            } else {
                Poll::Pending
            }
        }
    }

    impl Drop for PinnedFuture {
        fn drop(&mut self) {
            self.probe.moved.store(
                self.address.get() != std::ptr::from_ref(self).addr(),
                Ordering::SeqCst,
            );
            self.probe.drops.fetch_add(1, Ordering::SeqCst);
            assert!(!self.panics, "future drop");
        }
    }

    fn pinned_job(ready: bool, panics: bool) -> (Arc<Job<PinnedFuture>>, Arc<Probe>) {
        let probe = Arc::new(Probe::default());
        let job = Job::new(
            PinnedFuture {
                address: Cell::new(0),
                probe: probe.clone(),
                ready,
                panics,
                _pin: PhantomPinned,
            },
            true,
        );
        (job, probe)
    }

    #[test]
    fn completion_drops_pinned_future_in_place() {
        for panics in [false, true] {
            let (job, probe) = pinned_job(true, panics);
            let mut runner = Runner(job.clone());
            let join = RemoteJoin::new(job.clone());
            let waker = Waker::from(probe.clone());
            let mut cx = Context::from_waker(&waker);
            assert!(join.poll_join(&mut cx).is_pending());

            let result = catch_unwind(AssertUnwindSafe(|| {
                assert!(
                    Pin::new(&mut runner)
                        .poll(&mut Context::from_waker(Waker::noop()))
                        .is_ready()
                );
            }));
            assert_eq!(result.is_err(), panics);
            assert!(join.is_finished());
            assert!(!probe.moved.load(Ordering::SeqCst));
            assert_eq!(probe.drops.load(Ordering::SeqCst), 1);
            assert_eq!(probe.wakes.load(Ordering::SeqCst), 1);
            assert!(!probe.early_wake.load(Ordering::SeqCst));
            let Poll::Ready(Some(output)) = join.poll_join(&mut cx) else {
                panic!("completed output lost");
            };
            assert!(matches!(join.poll_join(&mut cx), Poll::Ready(None)));
            drop((runner, join, job));
            assert_eq!(probe.drops.load(Ordering::SeqCst), 1);
            assert_eq!(probe.output_drops.load(Ordering::SeqCst), 0);
            drop(output);
            assert_eq!(probe.output_drops.load(Ordering::SeqCst), 1);
        }
    }

    #[test]
    fn cancellation_drops_pinned_future_in_place() {
        for cancel in [false, true] {
            for panics in [false, true] {
                let (job, probe) = pinned_job(false, panics);
                let mut runner = Runner(job.clone());
                let join = RemoteJoin::new(job.clone());
                let waker = Waker::from(probe.clone());
                let mut cx = Context::from_waker(&waker);
                assert!(join.poll_join(&mut cx).is_pending());
                assert!(
                    Pin::new(&mut runner)
                        .poll(&mut Context::from_waker(Waker::noop()))
                        .is_pending()
                );

                let result = catch_unwind(AssertUnwindSafe(|| {
                    if cancel {
                        join.cancel();
                        assert!(
                            Pin::new(&mut runner)
                                .poll(&mut Context::from_waker(Waker::noop()))
                                .is_ready()
                        );
                    }
                    drop(runner);
                }));
                assert_eq!(result.is_err(), panics);
                assert!(join.is_finished());
                assert!(!probe.moved.load(Ordering::SeqCst));
                assert!(matches!(join.poll_join(&mut cx), Poll::Ready(None)));
                assert_eq!(probe.wakes.load(Ordering::SeqCst), 1);
                assert!(!probe.early_wake.load(Ordering::SeqCst));
                job.close();
                drop((join, job));
                assert_eq!(probe.drops.load(Ordering::SeqCst), 1);
                assert_eq!(probe.output_drops.load(Ordering::SeqCst), 0);
            }
        }
    }
}