1use dope_core::executor::{self, create};
2use std::{
3 cell, 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},
14 },
15 driver::{
16 life::{creation, domain},
17 settings,
18 },
19};
20use o3::base::marker::ThreadBound;
21
22use crate::{
23 process::{self, failure::bus},
24};
25
26
27#[derive(Debug)]
28pub enum WaitError {
29 Poll(Errno),
30 Read(bus::Read),
31 Event(bus::Event),
32 Timeout {
33 timeout: time::Duration,
34 elapsed: time::Duration,
35 },
36}
37
38#[derive(Clone, Copy, Debug)]
39pub struct Control<'a> {
40 fd: fd::BorrowedFd<'a>,
41 _thread: ThreadBound,
42}
43
44pub(crate) fn pair() -> Result<(Main, fd::OwnedFd), bus::Create> {
45 let (left, right) = Backend::pair()?;
46 Ok((Main(left, marker::PhantomData), right))
47}
48
49#[derive(Debug)]
50pub struct Main(fd::OwnedFd, marker::PhantomData<cell::Cell<()>>);
51
52pub struct Worker {
53 socket: fd::OwnedFd,
54 failure: cell::Cell<Option<bus::Fault>>,
55 phase: cell::Cell<Phase>,
56}
57
58#[derive(Debug)]
59pub enum Outcome<T, E> {
60 Done(T),
61 Failed {
62 output: Result<T, E>,
63 report: bus::Report,
64 },
65}
66
67#[derive(Clone, Copy)]
68enum Phase {
69 New,
70 Installed,
71 Failed,
72}
73
74#[derive(Clone, Copy)]
75#[repr(transparent)]
76pub(in crate::process) struct Tx<'a>(&'a Worker, marker::PhantomData<fn(&'a ()) -> &'a ()>);
77
78pub(in crate::process) trait Mode {
80 const GATED: bool;
82}
83
84#[derive(Clone, Copy)]
86pub(in crate::process) enum Readiness {
87 Required,
88 Cancelled,
89}
90
91impl Main {
92 pub fn try_pair() -> Result<(Self, Worker), bus::Create> {
93 let (main, right) = pair()?;
94 Ok((
95 main,
96 Worker {
97 socket: right,
98 failure: cell::Cell::new(None),
99 phase: cell::Cell::new(Phase::New),
100 },
101 ))
102 }
103
104 pub(in crate::process) fn recv(&self) -> Result<bus::Event, bus::Read> {
105 let mut byte = [0];
106 loop {
107 match Backend::recv::<0, Errno>(self.0.as_fd(), &mut byte) {
108 Ok(bytes) => {
109 return match bytes.first() {
110 Some(value) => bus::Event::decode(*value).map_err(bus::Read::Event),
111 None => Err(bus::Read::Closed),
112 };
113 }
114 Err(error) if error.is_intr() => {}
115 Err(error) => return Err(bus::Read::Syscall(error)),
116 }
117 }
118 }
119
120 pub(in crate::process) fn handoff<M: Mode>(&self, readiness: Readiness) -> Option<bus::Read> {
121 use bus::Event;
122
123 let mut failure = None;
124 let mut previous = None;
125 loop {
126 match self.recv() {
127 Err(bus::Read::Closed) => return failure,
128 Ok(event) => {
129 if failure.is_none() {
130 let valid = match (previous, event) {
131 (None, _) if M::GATED => true,
132 (None, Event::Installed | Event::Done | Event::Failed) => true,
133 (None, Event::Ready | Event::Drain) => false,
134 (Some(Event::Installed), Event::Ready) => M::GATED,
135 (Some(Event::Installed), Event::Done) => {
136 !M::GATED || matches!(readiness, Readiness::Cancelled)
137 }
138 (Some(Event::Installed), Event::Failed) => true,
139 (Some(Event::Installed), Event::Installed | Event::Drain) => false,
140 (Some(Event::Ready), Event::Drain | Event::Failed) => M::GATED,
141 (Some(Event::Ready), Event::Installed | Event::Ready | Event::Done) => {
142 false
143 }
144 (Some(Event::Drain), Event::Done | Event::Failed) => M::GATED,
145 (
146 Some(Event::Drain),
147 Event::Installed | Event::Ready | Event::Drain,
148 ) => false,
149 (Some(Event::Done | Event::Failed), _) => false,
150 };
151 if !valid {
152 failure = Some(bus::Read::Sequence(bus::Sequence {
153 gated: M::GATED,
154 previous,
155 event,
156 }));
157 }
158 }
159 previous = Some(event);
160 }
161 Err(source) => {
162 let terminal = matches!(&source, bus::Read::Syscall(_));
163 if failure.is_none() {
164 failure = Some(source);
165 }
166 if terminal {
167 return failure;
168 }
169 }
170 }
171 }
172 }
173
174 pub(crate) fn duplicate(&self) -> Result<Self, Errno> {
175 Backend::duplicate(self.0.as_fd()).map(|fd| Self(fd, marker::PhantomData))
176 }
177
178 pub fn request(&self) -> Result<(), Errno> {
179 shutdown(self.0.as_fd()).map_or(Ok(()), Err)
180 }
181
182 pub fn stop(self) -> Result<Self, Errno> {
183 self.request()?;
184 Ok(self)
185 }
186
187 pub fn wait_ready(&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::Installed => Ok(()),
191 event => Err(WaitError::Event(event)),
192 }
193 }
194
195 pub fn wait_done(&self, timeout: time::Duration) -> Result<(), WaitError> {
196 wait(self.0.as_fd(), time::Instant::now(), timeout)?;
197 match self.recv().map_err(WaitError::Read)? {
198 bus::Event::Done | bus::Event::Failed => Ok(()),
199 event => Err(WaitError::Event(event)),
200 }
201 }
202
203 pub fn run<R>(
204 self,
205 timeout: time::Duration,
206 run: impl FnOnce() -> R,
207 ) -> (Result<R, WaitError>, Result<Self, Errno>) {
208 let output = self.wait_ready(timeout).map(|()| run());
209 (output, self.stop())
210 }
211}
212
213impl fd::AsFd for Main {
214 fn as_fd(&self) -> fd::BorrowedFd<'_> {
215 self.0.as_fd()
216 }
217}
218
219impl executor::Startup for &Main {
220 type Error = std::convert::Infallible;
221
222 const INTEREST: dope_core::dope_sys::engine::register::Interest =
223 dope_core::dope_sys::engine::register::Interest::Closed;
224}
225
226impl executor::Build for &Main {
228 type Shutdown = Self;
229
230 fn try_build(
231 self,
232 attempt: &mut creation::Attempt,
233 config: settings::Config,
234 ) -> Result<domain::Generation<Self::Shutdown>, create::Error<'_>> {
235 domain::Generation::new(attempt.try_driver(config)?)
236 .poll(self, <Self as executor::Startup>::INTEREST)
237 .map_err(create::Error::from)
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_stop_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 if let Some(failure) = self.failure.get() {
342 return Err(failure);
343 }
344 if matches!(self.phase.get(), Phase::Failed) {
345 return Ok(());
346 }
347 if event == bus::Event::Failed {
348 self.phase.set(Phase::Failed);
349 }
350 let result = loop {
351 match Backend::send_quiet::<Errno>(self.socket.as_fd(), &[event.encode()]) {
352 Ok([_]) => break Ok(()),
353 Ok(bytes) => {
354 break Err(bus::Write::Record(bus::RecordSize {
355 expected: 1,
356 actual: bytes.len(),
357 }));
358 }
359 Err(error) if error.is_intr() => {}
360 Err(error) => break Err(bus::Write::Syscall(error)),
361 }
362 };
363 let shutdown = if result.is_err() || event == bus::Event::Failed {
364 shutdown(self.socket.as_fd())
365 } else {
366 None
367 };
368 let (failure, shutdown) = match (result, shutdown) {
369 (Ok(()), None) => return Ok(()),
370 (Ok(()), Some(error)) => (bus::Write::Shutdown(error), None),
371 (Err(failure), shutdown) => (failure, shutdown),
372 };
373 let fault = bus::Fault {
374 event,
375 failure,
376 shutdown,
377 };
378 self.failure.set(Some(fault));
379 Err(fault)
380 }
381
382 fn report(&self) -> bus::Report {
383 match self.failure.get() {
384 Some(failure) => bus::Report::Failed(failure),
385 None => bus::Report::Clean,
386 }
387 }
388}
389
390impl<'a> Tx<'a> {
391 pub(in crate::process) fn installed(self) -> Result<(), bus::Fault> {
393 let peer = self.0;
394 if !matches!(peer.phase.get(), Phase::New) {
395 return peer.failure.get().map_or(Ok(()), Err);
396 }
397 peer.send(bus::Event::Installed)?;
398 peer.phase.set(Phase::Installed);
399 Ok(())
400 }
401
402 pub(in crate::process) fn send(self, event: bus::Event) -> Result<(), bus::Fault> {
403 self.0.send(event)
404 }
405
406 pub(in crate::process) fn report(self) -> bus::Report {
407 self.0.report()
408 }
409
410 pub(in crate::process) fn terminal(
411 self,
412 _: dope_core::executor::Requested<process::Shutdown<'a>>,
413 ) -> Result<bus::Event, bus::Fault> {
414 match self.report() {
415 bus::Report::Failed(failure) => Err(failure),
416 bus::Report::Clean => Ok(if matches!(self.0.phase.get(), Phase::Failed) {
417 bus::Event::Failed
418 } else {
419 bus::Event::Done
420 }),
421 }
422 }
423
424 pub(in crate::process) fn as_fd(&self) -> fd::BorrowedFd<'a> {
425 self.0.socket.as_fd()
426 }
427}
428
429const _: () = {
430 assert!(mem::size_of::<Tx<'static>>() == mem::size_of::<usize>());
431 assert!(mem::align_of::<Tx<'static>>() == mem::align_of::<usize>());
432};