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