Skip to main content

dope_runtime/process/runtime/
mod.rs

1use crate::process::{
2    self, control,
3    failure::{config, create, execute},
4    gate, watch,
5};
6use dope_core::{
7    driver::Seed,
8    executor::Requested,
9    platform::{affinity, thread},
10};
11use o3::alloc;
12use std::{convert::Infallible, iter, num::NonZeroUsize};
13
14mod buses;
15mod task;
16
17use task::{Entry, Failure, Gated, Parent, Plain, Task};
18
19type Output<X> = control::Outcome<(), Failure<X>>;
20type Builder<I, E, X> = thread::Builder<Task<I, E, X>, Output<X>, Parent>;
21
22/// Owns workers through cooperative shutdown and joining.
23/// Enter on the original thread during single-threaded startup; entries must observe shutdown and return.
24/// Every started worker is joined. Heartbeats cannot interrupt stalled workers or bound the wait.
25pub struct Runtime {
26    head: affinity::Cpu,
27    tail: Vec<affinity::Cpu>,
28}
29
30impl Runtime {
31    pub fn pinned(cpus: impl IntoIterator<Item = affinity::Cpu>) -> Result<Self, create::Error> {
32        let mut cpus = cpus.into_iter();
33        let Some(head) = cpus.next() else {
34            return Err(create::Error::Config(config::Error::Empty));
35        };
36        let mut tail = Vec::new();
37        alloc::VecExt::try_reserve(&mut tail, cpus.size_hint().0)?;
38        for cpu in cpus {
39            if cpu == head || tail.contains(&cpu) {
40                return Err(create::Error::Config(config::Error::DuplicateCpu(cpu)));
41            }
42            alloc::VecExt::try_vacant(&mut tail)?.insert(cpu);
43        }
44        Ok(Self { head, tail })
45    }
46
47    pub fn count(&self) -> NonZeroUsize {
48        NonZeroUsize::MIN.saturating_add(self.tail.len())
49    }
50
51    /// Runs workers whose application readiness is their executor-install edge.
52    pub fn run<I, R, E, X>(self, items: R, entry: E) -> Result<(), execute::Error<Infallible, X>>
53    where
54        R: IntoIterator<Item = I>,
55        R::IntoIter: ExactSizeIterator,
56        I: Send,
57        E: for<'run> Fn(I, process::Context<'run>) -> Result<Requested<process::Shutdown<'run>>, X>
58            + Clone
59            + Send,
60        X: Send,
61    {
62        let values = self.prepare(items, Plain(entry))?;
63        buses::plain(values)
64    }
65
66    /// Runs workers and supervises an explicit steady-state heartbeat.
67    pub fn run_watched<I, R, N, E, X>(
68        self,
69        items: R,
70        entry: E,
71        notify: N,
72    ) -> Result<(), execute::Error<N::Error, X>>
73    where
74        R: IntoIterator<Item = I>,
75        R::IntoIter: ExactSizeIterator,
76        I: Send,
77        N: watch::Notify,
78        E: for<'run> Fn(I, process::Context<'run>) -> Result<Requested<process::Shutdown<'run>>, X>
79            + Clone
80            + Send,
81        X: Send,
82    {
83        let values = self.prepare(items, Plain(entry))?;
84        buses::watched(values, notify)
85    }
86
87    /// Runs gated workers and supervises an explicit steady-state heartbeat.
88    pub fn watch_gated<I, R, N, E, X>(
89        self,
90        items: R,
91        entry: E,
92        notify: N,
93    ) -> Result<(), execute::Error<N::Error, X>>
94    where
95        R: IntoIterator<Item = I>,
96        R::IntoIter: ExactSizeIterator,
97        I: Send,
98        N: watch::Notify,
99        E: for<'run> Fn(
100                I,
101                process::Context<'run>,
102                gate::Closed<'run>,
103            ) -> Result<Requested<process::Shutdown<'run>>, X>
104            + Clone
105            + Send,
106        X: Send,
107    {
108        let values = self.prepare(items, Gated(entry))?;
109        buses::watched(values, notify)
110    }
111
112    /// Replicates prior inputs and moves the original owner into the final CPU.
113    pub fn fork_gated<O, T, I, F, R, N, E, X>(
114        self,
115        owner: O,
116        items: R,
117        issue: impl Fn(&O, T) -> Result<I, F>,
118        finish: impl FnOnce(O, T) -> I,
119        entry: E,
120        notify: N,
121    ) -> Result<(), execute::Error<N::Error, X, F>>
122    where
123        R: IntoIterator<Item = T>,
124        R::IntoIter: ExactSizeIterator,
125        I: Send,
126        N: watch::Notify,
127        E: for<'run> Fn(
128                I,
129                process::Context<'run>,
130                gate::Closed<'run>,
131            ) -> Result<Requested<process::Shutdown<'run>>, X>
132            + Clone
133            + Send,
134        X: Send,
135    {
136        let count = self.count();
137        let mut items = Input::new(items.into_iter(), count)?;
138        let mut values = Builder::try_new(count.get()).map_err(execute::Cause::Allocation)?;
139        let seed = Seed::acquire().map_err(execute::Cause::Entropy)?;
140        let entry = Gated(entry);
141        let mut last_cpu = self.head;
142        let mut last = items.next(0)?;
143        for (index, cpu) in self.tail.into_iter().enumerate() {
144            let next = items.next(index + 1)?;
145            let input = issue(&owner, last).map_err(|cause| execute::Cause::Replica {
146                cpu: last_cpu,
147                cause,
148            })?;
149            Task::push(&mut values, last_cpu, input, &seed, index, entry.clone())?;
150            last_cpu = cpu;
151            last = next;
152        }
153        items.finish()?;
154        Task::push(
155            &mut values,
156            last_cpu,
157            finish(owner, last),
158            &seed,
159            count.get() - 1,
160            entry,
161        )?;
162        buses::watched(values, notify)
163    }
164
165    fn prepare<I, R, E, X, S>(
166        self,
167        items: R,
168        entry: E,
169    ) -> Result<Builder<I, E, X>, execute::Cause<S>>
170    where
171        R: IntoIterator<Item = I>,
172        R::IntoIter: ExactSizeIterator,
173        E: Entry<I, X>,
174    {
175        let count = self.count();
176        let mut items = Input::new(items.into_iter(), count)?;
177        let mut values = Builder::try_new(count.get())?;
178        let seed = Seed::acquire().map_err(execute::Cause::Entropy)?;
179        let cpus = iter::once(self.head).chain(self.tail);
180        for (index, (cpu, entry)) in cpus.zip(iter::repeat_n(entry, count.get())).enumerate() {
181            Task::push(&mut values, cpu, items.next(index)?, &seed, index, entry)?;
182        }
183        items.finish()?;
184        Ok(values)
185    }
186}
187
188struct Input<I> {
189    source: I,
190    required: NonZeroUsize,
191}
192
193impl<I: ExactSizeIterator> Input<I> {
194    fn new<S, F>(source: I, required: NonZeroUsize) -> Result<Self, execute::Cause<S, F>> {
195        let actual = source.len();
196        if actual != required.get() {
197            return Err(execute::Cause::ResourceCount { actual, required });
198        }
199        Ok(Self { source, required })
200    }
201
202    fn next<S, F>(&mut self, yielded: usize) -> Result<I::Item, execute::Cause<S, F>> {
203        self.source.next().ok_or(execute::Cause::ResourceIterator {
204            yielded,
205            required: self.required,
206        })
207    }
208
209    fn finish<S, F>(&mut self) -> Result<(), execute::Cause<S, F>> {
210        if self.source.next().is_some() {
211            return Err(execute::Cause::ResourceIterator {
212                yielded: self.required.get().saturating_add(1),
213                required: self.required,
214            });
215        }
216        Ok(())
217    }
218}