1use dope_core::{dope_sys::engine::register, executor};
2use std::{
3 cell, convert, marker, mem,
4 os::fd::{self, AsFd as _},
5 time,
6};
7
8use dope_core::{
9 Backend, Errno,
10 dope_sys::io::{
11 fd::Fd as _,
12 poll::{self, Poll as _},
13 socket::{How, Socket, record},
14 },
15};
16use o3::base::marker::ThreadBound;
17
18use crate::process::{self, failure::bus};
19
20#[derive(Debug)]
21pub enum WaitError {
22 Poll(Errno),
23 Read(bus::Read),
24 Event(bus::Event),
25 Timeout {
26 timeout: time::Duration,
27 elapsed: time::Duration,
28 },
29}
30
31#[derive(Clone, Copy, Debug)]
32pub struct Control<'a> {
33 fd: fd::BorrowedFd<'a>,
34 _thread: ThreadBound,
35}
36
37pub(crate) fn pair() -> Result<(Main, fd::OwnedFd), record::Error> {
38 let (left, right) = Backend::pair()?;
39 Ok((Main(left, marker::PhantomData), right))
40}
41
42#[derive(Debug)]
43pub struct Main(fd::OwnedFd, marker::PhantomData<cell::Cell<()>>);
44
45pub struct Worker {
46 socket: fd::OwnedFd,
47 phase: cell::Cell<Phase>,
48}
49
50#[derive(Debug)]
51pub enum Outcome<T, E> {
52 Done(T),
53 Failed {
54 output: Result<T, E>,
55 report: bus::Report,
56 },
57}
58
59#[derive(Clone, Copy)]
60enum Phase {
61 New,
62 Installed,
63 Failed,
64 Fault(bus::Fault),
65}
66
67#[derive(Clone, Copy)]
68#[repr(transparent)]
69pub(in crate::process) struct Tx<'a>(&'a Worker, marker::PhantomData<fn(&'a ()) -> &'a ()>);
70
71pub(in crate::process) trait Mode {
73 const GATED: bool;
75}
76
77#[derive(Clone, Copy)]
79pub(in crate::process) enum Readiness {
80 Required,
81 Cancelled,
82}
83
84impl Main {
85 pub fn try_pair() -> Result<(Self, Worker), record::Error> {
86 let (main, right) = pair()?;
87 Ok((
88 main,
89 Worker {
90 socket: right,
91 phase: cell::Cell::new(Phase::New),
92 },
93 ))
94 }
95
96 pub(in crate::process) fn recv(&self) -> Result<bus::Event, bus::Read> {
97 let mut byte = [0];
98 loop {
99 match Backend::recv::<0, Errno>(self.0.as_fd(), &mut byte) {
100 Ok(bytes) => {
101 return match bytes.first() {
102 Some(value) => bus::Event::decode(*value).map_err(bus::Read::Event),
103 None => Err(bus::Read::Closed),
104 };
105 }
106 Err(error) if error.is_intr() => {}
107 Err(error) => return Err(bus::Read::Syscall(error)),
108 }
109 }
110 }
111
112 pub(in crate::process) fn handoff<M: Mode>(&self, ready: Readiness) -> Option<bus::Read> {
113 use bus::Event;
114
115 let mut failure = None;
116 let mut previous = None;
117 loop {
118 match self.recv() {
119 Err(bus::Read::Closed) => return failure,
120 Ok(event) => {
121 if failure.is_none() {
122 let valid = match (previous, event) {
123 (None, _) if M::GATED => true,
124 (None, Event::Installed | Event::Done | Event::Failed) => true,
125 (None, Event::Ready | Event::Drain) => false,
126 (Some(Event::Installed), Event::Ready) => M::GATED,
127 (Some(Event::Installed), Event::Done) => {
128 !M::GATED || matches!(ready, Readiness::Cancelled)
129 }
130 (Some(Event::Installed), Event::Failed) => true,
131 (Some(Event::Installed), Event::Installed | Event::Drain) => false,
132 (Some(Event::Ready), Event::Drain | Event::Failed) => M::GATED,
133 (Some(Event::Ready), Event::Installed | Event::Ready | Event::Done) => {
134 false
135 }
136 (Some(Event::Drain), Event::Done | Event::Failed) => M::GATED,
137 (
138 Some(Event::Drain),
139 Event::Installed | Event::Ready | Event::Drain,
140 ) => false,
141 (Some(Event::Done | Event::Failed), _) => false,
142 };
143 if !valid {
144 failure = Some(bus::Read::Sequence(bus::Sequence {
145 gated: M::GATED,
146 previous,
147 event,
148 }));
149 }
150 }
151 previous = Some(event);
152 }
153 Err(source) => {
154 let terminal = matches!(&source, bus::Read::Syscall(_));
155 if failure.is_none() {
156 failure = Some(source);
157 }
158 if terminal {
159 return failure;
160 }
161 }
162 }
163 }
164 }
165
166 pub(crate) fn duplicate(&self) -> Result<Self, Errno> {
167 Backend::duplicate(self.0.as_fd()).map(|fd| Self(fd, marker::PhantomData))
168 }
169
170 pub fn request(&self) -> Result<(), Errno> {
171 shutdown(self.0.as_fd()).map_or(Ok(()), Err)
172 }
173
174 pub fn stop(self) -> Result<Self, Errno> {
175 self.request()?;
176 Ok(self)
177 }
178
179 pub fn wait_ready(&self, timeout: time::Duration) -> Result<(), WaitError> {
180 wait(self.0.as_fd(), time::Instant::now(), timeout)?;
181 match self.recv().map_err(WaitError::Read)? {
182 bus::Event::Installed => Ok(()),
183 event => Err(WaitError::Event(event)),
184 }
185 }
186
187 pub fn wait_done(&self, timeout: time::Duration) -> Result<(), WaitError> {
188 wait(self.0.as_fd(), time::Instant::now(), timeout)?;
189 match self.recv().map_err(WaitError::Read)? {
190 bus::Event::Done | bus::Event::Failed => Ok(()),
191 event => Err(WaitError::Event(event)),
192 }
193 }
194
195 pub fn run<R>(
196 self,
197 timeout: time::Duration,
198 run: impl FnOnce() -> R,
199 ) -> (Result<R, WaitError>, Result<Self, Errno>) {
200 let output = self.wait_ready(timeout).map(|()| run());
201 (output, self.stop())
202 }
203}
204
205impl fd::AsFd for Main {
206 fn as_fd(&self) -> fd::BorrowedFd<'_> {
207 self.0.as_fd()
208 }
209}
210
211impl executor::Startup for &Main {
212 type Error = convert::Infallible;
213 type Target = convert::Infallible;
214
215 fn failed(target: &Self::Target) {
216 match *target {}
217 }
218}
219
220impl executor::Source for &Main {
222 const INTEREST: register::Interest = register::Interest::Closed;
223}
224
225fn wait(
226 fd: fd::BorrowedFd<'_>,
227 started: time::Instant,
228 timeout: time::Duration,
229) -> Result<(), WaitError> {
230 loop {
231 let left = timeout.saturating_sub(started.elapsed());
232 let millis = left.as_millis() + u128::from(!left.subsec_nanos().is_multiple_of(1_000_000));
233 let mut entries = [poll::Entry::readable(fd)];
234 match Backend::wait::<_, Errno>(&mut entries, millis.min(i32::MAX as u128) as i32) {
235 Ok(events) if events.count() != 0 => return Ok(()),
236 Ok(_) => {}
237 Err(error) if error.is_intr() => {}
238 Err(error) => return Err(WaitError::Poll(error)),
239 }
240 let elapsed = started.elapsed();
241 if elapsed >= timeout {
242 return Err(WaitError::Timeout { timeout, elapsed });
243 }
244 }
245}
246
247impl<'a> Control<'a> {
248 pub(in crate::process) const fn new(fd: fd::BorrowedFd<'a>) -> Self {
249 Self {
250 fd,
251 _thread: ThreadBound::NEW,
252 }
253 }
254
255 pub fn stopped(&self) -> Result<bool, Errno> {
256 match Backend::recv_now::<Errno>(self.fd, &mut [0]) {
257 Ok(_) => Ok(true),
258 Err(error) if error.is_block() => Ok(false),
259 Err(error) if error.is_intr() => {
260 let mut entries = [poll::Entry::readable(self.fd)];
261 match Backend::wait::<_, Errno>(&mut entries, 0) {
262 Ok(events) => Ok(events.count() != 0),
263 Err(error) if error.is_intr() => Ok(false),
264 Err(error) => Err(error),
265 }
266 }
267 Err(error) => Err(error),
268 }
269 }
270
271 pub fn wait_until(&self, deadline: time::Instant) -> Result<(), WaitError> {
272 let started = time::Instant::now();
273 wait(
274 self.fd,
275 started,
276 deadline.saturating_duration_since(started),
277 )
278 }
279}
280
281impl fd::AsFd for Control<'_> {
282 fn as_fd(&self) -> fd::BorrowedFd<'_> {
283 self.fd
284 }
285}
286
287fn shutdown(socket: fd::BorrowedFd<'_>) -> Option<dope_core::Errno> {
288 loop {
289 match Backend::shutdown::<Errno>(socket, How::WRITE) {
290 Ok(()) => return None,
291 Err(errno) if errno.is_intr() => {}
292 Err(errno) => return Some(errno),
293 }
294 }
295}
296
297impl Worker {
298 pub fn run<T, E>(
299 self,
300 run: impl for<'a> FnOnce(process::Shutdown<'a>) -> Result<T, E>,
301 ) -> Outcome<T, E> {
302 let output = run(process::Shutdown::new(self.tx()));
303 let event = if output.is_ok() {
304 bus::Event::Done
305 } else {
306 bus::Event::Failed
307 };
308 let report = match self.send(event) {
309 Ok(()) => bus::Report::Clean,
310 Err(fault) => bus::Report::Failed(fault),
311 };
312 match (output, report) {
313 (Ok(value), bus::Report::Clean) if !matches!(self.phase.get(), Phase::Failed) => {
314 Outcome::Done(value)
315 }
316 (output, report) => Outcome::Failed { output, report },
317 }
318 }
319
320 pub(in crate::process) const fn tx(&self) -> Tx<'_> {
321 Tx(self, marker::PhantomData)
322 }
323
324 fn send(&self, event: bus::Event) -> Result<(), bus::Fault> {
325 match self.phase.get() {
326 Phase::Fault(failure) => return Err(failure),
327 Phase::Failed => return Ok(()),
328 Phase::New | Phase::Installed => {}
329 }
330 if event == bus::Event::Failed {
331 self.phase.set(Phase::Failed);
332 }
333 let result = loop {
334 match Backend::send_quiet::<Errno>(self.socket.as_fd(), &[event.encode()]) {
335 Ok([_]) => break Ok(()),
336 Ok(bytes) => {
337 break Err(bus::Write::Record(bus::RecordSize {
338 expected: 1,
339 actual: bytes.len(),
340 }));
341 }
342 Err(error) if error.is_intr() => {}
343 Err(error) => break Err(bus::Write::Syscall(error)),
344 }
345 };
346 let shutdown = if result.is_err() || event == bus::Event::Failed {
347 shutdown(self.socket.as_fd())
348 } else {
349 None
350 };
351 let (failure, shutdown) = match (result, shutdown) {
352 (Ok(()), None) => return Ok(()),
353 (Ok(()), Some(error)) => (bus::Write::Shutdown(error), None),
354 (Err(failure), shutdown) => (failure, shutdown),
355 };
356 let fault = bus::Fault {
357 event,
358 failure,
359 shutdown,
360 };
361 self.phase.set(Phase::Fault(fault));
362 Err(fault)
363 }
364}
365
366impl<'a> Tx<'a> {
367 pub(in crate::process) fn installed(self) -> Result<(), bus::Fault> {
369 let peer = self.0;
370 match peer.phase.get() {
371 Phase::Fault(failure) => return Err(failure),
372 Phase::Installed | Phase::Failed => return Ok(()),
373 Phase::New => {}
374 }
375 peer.send(bus::Event::Installed)?;
376 peer.phase.set(Phase::Installed);
377 Ok(())
378 }
379
380 pub(in crate::process) fn send(self, event: bus::Event) -> Result<(), bus::Fault> {
381 self.0.send(event)
382 }
383
384 pub(in crate::process) fn terminal(
385 self,
386 _: executor::Requested<process::Shutdown<'a>>,
387 ) -> Result<bus::Event, bus::Fault> {
388 match self.0.phase.get() {
389 Phase::Fault(failure) => Err(failure),
390 Phase::Failed => Ok(bus::Event::Failed),
391 Phase::New | Phase::Installed => Ok(bus::Event::Done),
392 }
393 }
394
395 pub(in crate::process) fn as_fd(&self) -> fd::BorrowedFd<'a> {
396 self.0.socket.as_fd()
397 }
398}
399
400const _: () = {
401 assert!(mem::size_of::<Tx<'static>>() == mem::size_of::<usize>());
402 assert!(mem::align_of::<Tx<'static>>() == mem::align_of::<usize>());
403};