1use std::io;
2use std::os::fd::{AsFd, AsRawFd, BorrowedFd};
3use std::process::ExitStatus;
4use std::time::{Duration, Instant};
5
6use lune_pty::{ChildExit, Pty};
7
8use super::Session;
9
10#[derive(Clone, Copy, Debug)]
11pub struct PtyInterest<'a> {
12 pub fd: BorrowedFd<'a>,
13 pub read: bool,
14 pub write: bool,
15}
16
17#[derive(Clone, Copy, Debug)]
18pub struct SessionInterests<'a> {
19 pub pty: Option<PtyInterest<'a>>,
20 pub child_exit: Option<BorrowedFd<'a>>,
21 pub presentation_deadline: Option<Instant>,
22 pub immediate: bool,
24}
25
26#[derive(Clone, Copy, Debug, Default)]
27pub struct SessionReady {
28 pub pty: bool,
30 pub child_exit: bool,
31}
32
33#[derive(Clone, Copy, Debug, PartialEq, Eq)]
34pub enum WaitOutcome {
35 Pumped,
36 ChildExited(ExitStatus),
37 TimedOut,
38 Finished,
39}
40
41impl Session<Pty> {
42 pub fn interests(&self) -> SessionInterests<'_> {
44 let output_finished = self.is_finished();
45 SessionInterests {
46 pty: (!output_finished).then(|| PtyInterest {
47 fd: self.as_fd(),
48 read: self.wants_read(),
49 write: self.wants_write(),
50 }),
51 child_exit: match &self.child_exit {
52 Some(ChildExit::Pending(fd)) => Some(fd.as_fd()),
53 _ => None,
54 },
55 presentation_deadline: self.presentation_deadline(),
56 immediate: matches!(self.child_exit, Some(ChildExit::Exited(_)))
57 || (output_finished && self.child_exit.is_none())
58 || self.needs_pump(),
59 }
60 }
61
62 pub fn dispatch_ready(&mut self, ready: SessionReady) -> io::Result<Option<WaitOutcome>> {
65 let status = match self.child_exit {
66 Some(ChildExit::Exited(status)) => Some(status),
67 Some(ChildExit::Pending(_)) if ready.child_exit => self.try_wait()?,
68 _ => None,
69 };
70 if let Some(status) = status {
71 self.child_exit = None;
72 return Ok(Some(WaitOutcome::ChildExited(status)));
73 }
74 if self.is_finished() {
75 return Ok(self.child_exit.is_none().then_some(WaitOutcome::Finished));
76 }
77 if ready.pty
78 || self.needs_pump()
79 || self
80 .presentation_deadline()
81 .is_some_and(|deadline| Instant::now() >= deadline)
82 {
83 return self.pump_ready().map(Some);
84 }
85 Ok(None)
86 }
87
88 fn needs_pump(&self) -> bool {
89 !self.is_finished()
90 && (self.read_closed || (self.incoming_bytes.is_some() && !self.wants_write()))
91 }
92
93 pub fn wait_and_pump(&mut self, timeout: Option<Duration>) -> io::Result<WaitOutcome> {
97 let interests = self.interests();
98 if interests.immediate {
99 return self
100 .dispatch_ready(SessionReady::default())?
101 .ok_or_else(|| io::Error::other("Session work unavailable"));
102 }
103 let mut descriptors = [
104 interests.pty.map_or(
105 libc::pollfd {
106 fd: -1,
107 events: 0,
108 revents: 0,
109 },
110 |pty| libc::pollfd {
111 fd: pty.fd.as_raw_fd(),
112 events: (if pty.read { libc::POLLIN } else { 0 })
113 | (if pty.write { libc::POLLOUT } else { 0 }),
114 revents: 0,
115 },
116 ),
117 libc::pollfd {
118 fd: interests.child_exit.map_or(-1, |fd| fd.as_raw_fd()),
119 events: libc::POLLIN,
120 revents: 0,
121 },
122 ];
123 let caller_limit = timeout.map(|duration| (Instant::now(), duration));
124 let mut polled = false;
125 loop {
126 let presentation_wait = self
127 .presentation_deadline()
128 .map(|deadline| deadline.saturating_duration_since(Instant::now()));
129 if presentation_wait == Some(Duration::ZERO) {
130 return self.pump_ready();
131 }
132 let caller_wait =
133 caller_limit.map(|(start, duration)| duration.saturating_sub(start.elapsed()));
134 if polled && caller_wait == Some(Duration::ZERO) {
135 return Ok(WaitOutcome::TimedOut);
136 }
137 let wait = match (presentation_wait, caller_wait) {
138 (Some(presentation), Some(caller)) => Some(presentation.min(caller)),
139 (presentation, caller) => presentation.or(caller),
140 };
141 let millis = wait.map_or(-1, |duration| {
142 i32::try_from(duration.as_nanos().div_ceil(1_000_000)).unwrap_or(i32::MAX)
143 });
144 let ready = unsafe {
146 libc::poll(
147 descriptors.as_mut_ptr(),
148 descriptors.len() as libc::nfds_t,
149 millis,
150 )
151 };
152 if ready > 0 {
153 if (descriptors[0].revents | descriptors[1].revents) & libc::POLLNVAL != 0 {
154 return Err(io::Error::from_raw_os_error(libc::EBADF));
155 }
156 let ready = SessionReady {
157 pty: descriptors[0].revents != 0,
158 child_exit: descriptors[1].revents != 0,
159 };
160 if let Some(outcome) = self.dispatch_ready(ready)? {
161 return Ok(outcome);
162 }
163 return Err(io::Error::other("Session readiness did not produce work"));
164 }
165 if ready < 0 {
166 let error = io::Error::last_os_error();
167 if error.kind() != io::ErrorKind::Interrupted {
168 return Err(error);
169 }
170 }
171 polled = true;
172 }
173 }
174
175 fn pump_ready(&mut self) -> io::Result<WaitOutcome> {
176 self.pump()?;
177 Ok(if self.is_finished() && self.child_exit.is_none() {
178 WaitOutcome::Finished
179 } else {
180 WaitOutcome::Pumped
181 })
182 }
183}