Skip to main content

dope_runtime/process/
control.rs

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