Skip to main content

dope_core/executor/task/batch/
join.rs

1use core::{convert, pin, task::Poll};
2
3use o3::depot::array;
4
5use crate::{
6    driver::schedule::{
7        app,
8        ready::task::{self, Index, pool},
9    },
10    executor::task::context,
11    executor::task::{Fiber, Ready},
12    executor::task::{
13        batch::{Completed, Error, Pool, RootError, Running, Vacant, state},
14        storage::slots,
15    },
16};
17
18/// One ordered, fixed-capacity group of homogeneous fibers.
19#[pin_project::pin_project(PinnedDrop)]
20#[must_use = "a fiber does nothing unless it is driven"]
21pub struct Join<'pool, 'd, F, const N: usize>
22where
23    F: Fiber<'d>,
24{
25    #[pin]
26    entries: [slots::raw::Entry<F, F::Output>; N],
27    bindings: task::raw::Bindings<'d, &'pool task::raw::Scheduler<'d, N>, N>,
28    state: state::State<N>,
29    root: Option<pool::Root<'d>>,
30}
31
32impl<'pool, 'd, F, const N: usize> Join<'pool, 'd, F, N>
33where
34    F: Fiber<'d>,
35{
36    /// Builds an empty fixed-capacity batch.
37    pub fn new(pool: &'pool mut Pool<'d, N>) -> Self {
38        Self::from_table(
39            pool,
40            [const { slots::raw::Entry::vacant() }; N],
41            array::Len::ZERO,
42        )
43    }
44
45    /// Builds a batch containing every fiber in array order.
46    pub fn from_array(pool: &'pool mut Pool<'d, N>, fibers: [F; N]) -> Self {
47        Self::from_map(pool, fibers, convert::identity)
48    }
49
50    /// Consumes each input in array order, constructing every fiber before returning.
51    pub fn from_map<P>(
52        pool: &'pool mut Pool<'d, N>,
53        input: [P; N],
54        mut make: impl FnMut(P) -> F,
55    ) -> Self {
56        Self::from_table(
57            pool,
58            input.map(|value| slots::raw::Entry::new(make(value))),
59            array::Len::MAX,
60        )
61    }
62
63    /// Builds a full batch without materializing an intermediate fiber array.
64    pub fn from_fn(pool: &'pool mut Pool<'d, N>, mut make: impl FnMut(Index<N>) -> F) -> Self {
65        Self::from_table(
66            pool,
67            task::raw::map(|index| slots::raw::Entry::new(make(index))),
68            array::Len::MAX,
69        )
70    }
71
72    fn from_table(
73        pool: &'pool mut Pool<'d, N>,
74        entries: [slots::raw::Entry<F, F::Output>; N],
75        len: array::Len<N>,
76    ) -> Self {
77        Self {
78            entries,
79            bindings: pool.0.borrow_slots(),
80            state: state::State::new(len),
81            root: None,
82        }
83    }
84
85    pub fn try_push(&mut self, fiber: F) -> Result<(), F> {
86        let Some(state) = self.state.vacancy() else {
87            return Err(fiber);
88        };
89        let entry = state.slot().get_mut(&mut self.entries);
90        slots::raw::insert(Vacant(entry), fiber);
91        state.commit();
92        Ok(())
93    }
94
95    fn fail(
96        mut self: pin::Pin<&mut Self>,
97        error: Error,
98    ) -> Poll<Result<array::IntoIter<F::Output, N>, Error>> {
99        if self.as_mut().project().root.take().is_some() {
100            self.cancel();
101        }
102        Poll::Ready(Err(error))
103    }
104
105    fn cancel(self: pin::Pin<&mut Self>) {
106        let this = self.project();
107        let end = this.state.next();
108        let (_, bindings) = this.bindings.split();
109        for (slot, claim) in slots::raw::prefix(this.entries, end).zip(bindings.drain(end)) {
110            if claim.is_some() {
111                slots::raw::live(Running(slot)).discard();
112            }
113        }
114    }
115}
116
117fn poll_slot<'d, F: Fiber<'d>>(
118    slot: Running<'_, F, F::Output>,
119    context: &mut context::Context<'_, 'd>,
120    binding: impl task::raw::Binding<'d>,
121) -> state::Completion {
122    let mut live = slots::raw::live(slot);
123    match slots::poll(live.fiber(), context, binding) {
124        Poll::Pending => state::Completion::Pending,
125        Poll::Ready((output, _reclaim)) => {
126            live.complete(output);
127            state::Completion::Ready
128        }
129    }
130}
131
132impl<'pool, 'd, F, const N: usize> Fiber<'d> for Join<'pool, 'd, F, N>
133where
134    F: Fiber<'d>,
135{
136    type Output = Result<array::IntoIter<F::Output, N>, Error>;
137
138    fn poll(call: context::PollCall<'_, '_, 'd, Self>) -> Poll<Self::Output> {
139        let (mut owner, context) = call.into_parts();
140        let done = 'complete: {
141            let mut this = owner.as_mut().project();
142            if let Some(done) = this.state.completed() {
143                break 'complete Ok(done);
144            }
145
146            let (sched, mut bindings) = this.bindings.split();
147            let root = match pool::Root::try_new(context.waker().0) {
148                Ok(root) => root,
149                Err(error) => break 'complete Err(Error::Root(RootError::Invalid(error))),
150            };
151            match *this.root {
152                None => *this.root = Some(root),
153                Some(active) if active == root => {}
154                Some(active) => {
155                    break 'complete Err(Error::Root(RootError::Changed {
156                        active: active.id(),
157                        observed: root.id(),
158                    }));
159                }
160            }
161
162            let mut initial = true;
163            while let Some(fresh) = this.state.fresh() {
164                let index = task::raw::from_vacant(fresh.slot());
165                if initial {
166                    initial = false;
167                } else if matches!(context.try_continue(), context::Continue::Exhausted) {
168                    return Poll::Pending;
169                }
170                let binding = match bindings.start(root, index) {
171                    Ok(binding) => binding,
172                    Err(error) => break 'complete Err(Error::Task(error)),
173                };
174                let complete = poll_slot(
175                    Running(task::raw::project(index, this.entries.as_mut())),
176                    context,
177                    binding,
178                );
179                if let state::Status::Done(done) = fresh.commit(complete) {
180                    break 'complete Ok(done);
181                }
182            }
183
184            let Some(mut drain) = sched.ready.drain() else {
185                return Poll::Pending;
186            };
187            loop {
188                let pending = match this.state.pending() {
189                    state::PendingState::Live(pending) => pending,
190                    state::PendingState::Done(done) => break 'complete Ok(done),
191                };
192                let wake = if initial {
193                    let Some(index) = drain.pop() else {
194                        break;
195                    };
196                    initial = false;
197                    index
198                } else {
199                    match drain.next(context.work()) {
200                        app::Next::Item(index, _permit) => index,
201                        app::Next::Empty => break,
202                        app::Next::Exhausted(_) => {
203                            drop(drain);
204                            context.requeue();
205                            return Poll::Pending;
206                        }
207                    }
208                };
209                let index = wake.local();
210                let Some(binding) = bindings.resume(wake) else {
211                    continue;
212                };
213                let complete = poll_slot(
214                    Running(task::raw::project(index, this.entries.as_mut())),
215                    context,
216                    binding,
217                );
218                if let state::Status::Done(done) = pending.commit(complete) {
219                    break 'complete Ok(done);
220                }
221            }
222            if !sched.ready.is_empty() {
223                drop(drain);
224                context.requeue();
225            }
226            return Poll::Pending;
227        };
228        let done = match done {
229            Ok(done) => done,
230            Err(error) => return owner.fail(error),
231        };
232        let this = owner.project();
233        *this.root = None;
234        let output = slots::raw::outputs(Completed {
235            entries: this.entries,
236            len: done,
237        });
238        Poll::Ready(Ok(output))
239    }
240}
241
242#[pin_project::pinned_drop]
243impl<'d, F, const N: usize> PinnedDrop for Join<'_, 'd, F, N>
244where
245    F: Fiber<'d>,
246{
247    fn drop(self: pin::Pin<&mut Self>) {
248        if self.root.is_some() {
249            self.cancel();
250        }
251    }
252}
253
254const _: () = {
255    use core::mem;
256
257    let word = mem::size_of::<usize>();
258    assert!(mem::size_of::<Vacant<'static, (), ()>>() == word);
259    assert!(mem::size_of::<Option<Vacant<'static, (), ()>>>() == word);
260    assert!(mem::size_of::<Join<'static, 'static, Ready<()>, 0>>() == 4 * word);
261    assert!(mem::align_of::<Join<'static, 'static, Ready<()>, 0>>() == word);
262    assert!(mem::size_of::<Option<Join<'static, 'static, Ready<()>, 0>>>() == 4 * word);
263};