1use std::{convert::Infallible, iter, num::NonZeroUsize};
2
3use dope_core::{
4 platform::{affinity, signal},
5 random,
6};
7use o3::{alloc, mem::slot};
8
9use crate::process::{
10 self,
11 failure::{config, create, execute},
12 gate, watch,
13};
14
15pub(in crate::process) use crate::process::lifecycle as bus;
16mod control;
17pub(in crate::process) mod worker;
18
19pub struct Process {
26 head: affinity::Cpu,
27 tail: Vec<affinity::Cpu>,
28}
29
30impl Process {
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::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 pub fn run<'r, I, R, E, X>(
53 self,
54 storage: slot::Vacant<'r, signal::Receiver>,
55 items: R,
56 entry: E,
57 ) -> Result<(), execute::Error<'r, Infallible, X>>
58 where
59 R: IntoIterator<Item = I>,
60 R::IntoIter: ExactSizeIterator,
61 I: Send,
62 E: for<'run> Fn(I, process::Context<'run>)
63 -> Result<dope_core::executor::Requested<process::Shutdown<'run>>, X>
64 + Clone
65 + Send,
66 X: Send,
67 {
68 let values = self.prepare(items, worker::Plain::new(entry))?;
69 signal::Source::scope(storage, move |signal| {
70 let control = control::Control::signal(signal);
71 worker::scope(values, |running| {
72 let outcome = control.ready(running.count(), &running);
73 let stopped = running.stop();
74 match outcome {
75 Ok(()) => stopped.clean(bus::Readiness::Required),
76 Err(error) => Err(stopped.fail(error)),
77 }
78 })
79 })
80 .map_err(execute::Error::from)
81 }
82
83 pub fn run_watched<'r, I, R, N, E, X>(
85 self,
86 storage: slot::Vacant<'r, signal::Receiver>,
87 items: R,
88 entry: E,
89 notify: N,
90 ) -> Result<(), execute::Error<'r, N::Error, X>>
91 where
92 R: IntoIterator<Item = I>,
93 R::IntoIter: ExactSizeIterator,
94 I: Send,
95 N: watch::Notify,
96 E: for<'run> Fn(I, process::Context<'run>)
97 -> Result<dope_core::executor::Requested<process::Shutdown<'run>>, X>
98 + Clone
99 + Send,
100 X: Send,
101 {
102 let values = self.prepare(items, worker::Plain::new(entry))?;
103 run_watched(storage, values, notify)
104 }
105
106 pub fn watch_gated<'r, I, R, N, E, X>(
108 self,
109 storage: slot::Vacant<'r, signal::Receiver>,
110 items: R,
111 entry: E,
112 notify: N,
113 ) -> Result<(), execute::Error<'r, N::Error, X>>
114 where
115 R: IntoIterator<Item = I>,
116 R::IntoIter: ExactSizeIterator,
117 I: Send,
118 N: watch::Notify,
119 E: for<'run> Fn(I, process::Context<'run>, gate::Closed<'run>)
120 -> Result<dope_core::executor::Requested<process::Shutdown<'run>>, X>
121 + Clone
122 + Send,
123 X: Send,
124 {
125 let values = self.prepare(items, worker::Gated::new(entry))?;
126 run_watched(storage, values, notify)
127 }
128
129 pub fn fork_gated<'r, O, T, I, F, R, N, E, X>(
131 self,
132 storage: slot::Vacant<'r, signal::Receiver>,
133 owner: O,
134 items: R,
135 issue: impl Fn(&O, T) -> Result<I, F>,
136 finish: impl FnOnce(O, T) -> I,
137 entry: E,
138 notify: N,
139 ) -> Result<(), execute::Error<'r, N::Error, X, F>>
140 where
141 R: IntoIterator<Item = T>,
142 R::IntoIter: ExactSizeIterator,
143 I: Send,
144 N: watch::Notify,
145 E: for<'run> Fn(I, process::Context<'run>, gate::Closed<'run>)
146 -> Result<dope_core::executor::Requested<process::Shutdown<'run>>, X>
147 + Clone
148 + Send,
149 X: Send,
150 {
151 let count = self.count();
152 let mut items = Input::new(items.into_iter(), count)?;
153 let mut values = worker::Builder::try_new(count.get())
154 .map_err(execute::Cause::Allocation)?;
155 let seed = random::Seed::acquire().map_err(execute::Cause::Entropy)?;
156 let entry = worker::Gated::new(entry);
157 let mut last_cpu = self.head;
158 let mut last = items.next(0)?;
159 for (index, cpu) in self.tail.into_iter().enumerate() {
160 let next = items.next(index + 1)?;
161 let input = issue(&owner, last)
162 .map_err(|cause| execute::Cause::Replica { cpu: last_cpu, cause })?;
163 worker::task::Task::push(
164 &mut values, last_cpu, input, &seed, index, entry.clone(),
165 )?;
166 last_cpu = cpu;
167 last = next;
168 }
169 items.finish()?;
170 worker::task::Task::push(
171 &mut values, last_cpu, finish(owner, last), &seed, count.get() - 1, entry,
172 )?;
173 run_watched(storage, values, notify)
174 }
175
176 fn prepare<I, R, E, X, S>(
177 self,
178 items: R,
179 entry: E,
180 ) -> Result<worker::Builder<I, E, X>, execute::Cause<S>>
181 where
182 R: IntoIterator<Item = I>,
183 R::IntoIter: ExactSizeIterator,
184 E: worker::Entry<I, X>,
185 {
186 let count = self.count();
187 let mut items = Input::new(items.into_iter(), count)?;
188 let mut values = worker::Builder::try_new(count.get())?;
189 let seed = random::Seed::acquire().map_err(execute::Cause::Entropy)?;
190 let cpus = iter::once(self.head).chain(self.tail);
191 for (index, (cpu, entry)) in cpus.zip(iter::repeat_n(entry, count.get())).enumerate() {
192 worker::task::Task::push(
193 &mut values, cpu, items.next(index)?, &seed, index, entry,
194 )?;
195 }
196 items.finish()?;
197 Ok(values)
198 }
199}
200
201fn run_watched<'r, I, N, E, X, F>(
202 storage: slot::Vacant<'r, signal::Receiver>,
203 values: worker::Builder<I, E, X>,
204 notify: N,
205) -> Result<(), execute::Error<'r, N::Error, X, F>>
206where
207 I: Send,
208 N: watch::Notify,
209 E: worker::Entry<I, X>,
210 X: Send,
211{
212 signal::Source::scope(storage, move |signal| {
213 let control = control::Control::signal(signal);
214 worker::scope(values, |running| {
215 let count = running.count();
216 let outcome = control.watch(count, notify, &running);
217 let stopped = running.stop();
218 let outcome = outcome.and_then(|clock| match clock {
219 Some(clock) => control::drain(&stopped, count, clock)
220 .map(|()| bus::Readiness::Required),
221 None => Ok(bus::Readiness::Cancelled),
222 });
223 match outcome {
224 Ok(readiness) => stopped.clean(readiness),
225 Err(error) => Err(stopped.fail(error)),
226 }
227 })
228 })
229 .map_err(execute::Error::from)
230}
231
232struct Input<I> {
233 source: I,
234 required: NonZeroUsize,
235}
236
237impl<I: ExactSizeIterator> Input<I> {
238 fn new<S, F>(source: I, required: NonZeroUsize) -> Result<Self, execute::Cause<S, F>> {
239 let actual = source.len();
240 if actual != required.get() {
241 return Err(execute::Cause::Config(config::Error::ResourceCount {
242 actual,
243 required: required.get(),
244 }));
245 }
246 Ok(Self { source, required })
247 }
248
249 fn next<S, F>(&mut self, yielded: usize) -> Result<I::Item, execute::Cause<S, F>> {
250 self.source.next().ok_or(execute::Cause::Config(config::Error::ResourceIterator {
251 yielded,
252 required: self.required.get(),
253 }))
254 }
255
256 fn finish<S, F>(&mut self) -> Result<(), execute::Cause<S, F>> {
257 if self.source.next().is_some() {
258 return Err(execute::Cause::Config(config::Error::ResourceIterator {
259 yielded: self.required.get().saturating_add(1),
260 required: self.required.get(),
261 }));
262 }
263 Ok(())
264 }
265}