Skip to main content

satx_core/
link.rs

1//! The seam between the protocol logic and whoever owns the I/O.
2//!
3//! The logic above `kermit-proto` and `xmodem-proto` (the Kermit session,
4//! the calculator operations, the XModem session) is `async` code that only
5//! talks to a [`Link`]: a mailbox of bytes fed in, packets queued out,
6//! progress events and the caller's clock. It never reads a clock, sleeps or
7//! touches a port. A read waits until bytes are fed or a deadline of the
8//! fed clock passes; a pause waits for the clock alone.
9//!
10//! No executor and no waker are involved: the owner of the I/O polls the
11//! future again after every feed (bytes, time or a link error), with a no-op
12//! waker. Two owners exist:
13//!
14//! - [`drive`]: the blocking loop over a [`Transport`] and
15//!   `Instant::now()` behind [`Session`](crate::Session),
16//!   [`Calculator`](crate::Calculator) and
17//!   [`XmodemSession`](crate::XmodemSession).
18//! - [`Machine`](crate::machine::Machine): the sans-I/O face for a host
19//!   whose bytes arrive by callback (a browser with Web Serial).
20
21use std::collections::VecDeque;
22use std::future::Future;
23use std::io;
24use std::pin::Pin;
25use std::sync::{Arc, Mutex, MutexGuard, PoisonError};
26use std::task::{Context, Poll, Waker};
27
28use crate::time::{Duration, Instant};
29#[cfg(not(target_arch = "wasm32"))]
30use crate::transport::Transport;
31
32/// A progress event of the running operation, in the order the protocol
33/// machines emitted them.
34#[derive(Clone, Debug, PartialEq, Eq)]
35pub enum Progress {
36    /// From the Kermit client (file start, data, progress, server text,
37    /// `Done`, `Error`).
38    Kermit(kermit_proto::Event),
39    /// From the XModem machine.
40    Xmodem(xmodem_proto::Event),
41}
42
43/// Input kept while nothing reads it (between operations of a
44/// [`Machine`](crate::machine::Machine)); the oldest bytes go first. The idle
45/// server NAKs once (6 bytes), a server timeout after its last packet, and
46/// then stays silent (Saturnus and saturnng; real hardware unverified; wiki:
47/// protocols/server-commands), so this is far more than idling leaves.
48const MAX_IDLE_INPUT: usize = 64 * 1024;
49
50#[derive(Debug)]
51struct State {
52    /// The caller's clock, as last fed.
53    now: Instant,
54    /// Bytes fed and not read yet.
55    input: Vec<u8>,
56    /// Packets to write, each with one write.
57    output: VecDeque<Vec<u8>>,
58    /// Progress events not taken yet.
59    events: VecDeque<Progress>,
60    /// Whether events are kept (a caller that never takes them would keep
61    /// every file twice).
62    keep_events: bool,
63    /// When the pending wait ends without input; `None` while nothing waits
64    /// on the clock.
65    wake: Option<Instant>,
66    /// The link failed: every later read or write of the operation fails
67    /// the same way.
68    error: Option<(io::ErrorKind, String)>,
69    /// Whether [`Link::flush`] waits until the queued packets are written
70    /// ([`drive`], whose writes fail or succeed at once); a
71    /// [`Machine`](crate::machine::Machine)'s host writes later and reports
72    /// a failure as a link error.
73    write_through: bool,
74}
75
76/// The mailbox shared by the protocol logic and the I/O owner.
77#[derive(Clone, Debug)]
78pub(crate) struct Link(Arc<Mutex<State>>);
79
80impl Link {
81    pub(crate) fn new(now: Instant) -> Self {
82        Link(Arc::new(Mutex::new(State {
83            now,
84            input: Vec::new(),
85            output: VecDeque::new(),
86            events: VecDeque::new(),
87            keep_events: true,
88            wake: None,
89            error: None,
90            write_through: false,
91        })))
92    }
93
94    fn state(&self) -> MutexGuard<'_, State> {
95        // Nothing panics while holding the lock; a poisoned lock still holds
96        // consistent data.
97        self.0.lock().unwrap_or_else(PoisonError::into_inner)
98    }
99
100    // ---- the protocol side ----
101
102    /// The caller's clock as last fed.
103    pub(crate) fn now(&self) -> Instant {
104        self.state().now
105    }
106
107    /// Queue one packet for a single write. Fails once the link failed.
108    pub(crate) fn write(&self, packet: Vec<u8>) -> io::Result<()> {
109        let mut st = self.state();
110        if let Some((kind, msg)) = &st.error {
111            return Err(io::Error::new(*kind, msg.clone()));
112        }
113        st.output.push_back(packet);
114        Ok(())
115    }
116
117    /// Wait until the queued packets are written (only under [`drive`]),
118    /// then fail if the link has failed: the write of a transaction's last
119    /// packet fails the transaction, as a direct write would.
120    pub(crate) fn flush(&self) -> Flush<'_> {
121        Flush { link: self }
122    }
123
124    /// Hand a progress event to the I/O owner.
125    pub(crate) fn emit(&self, event: Progress) {
126        let mut st = self.state();
127        if st.keep_events {
128            st.events.push_back(event);
129        }
130    }
131
132    /// Wait for input until `deadline` (`None`: no deadline). Resolves to
133    /// every byte fed so far, or to an empty buffer once the deadline has
134    /// passed without input, or to the link's error.
135    pub(crate) fn read(&self, deadline: Option<Instant>) -> Read<'_> {
136        Read {
137            link: self,
138            deadline,
139        }
140    }
141
142    /// Wait until the clock reaches `until`. Input keeps arriving meanwhile
143    /// and is read later.
144    pub(crate) fn sleep_until(&self, until: Instant) -> Sleep<'_> {
145        Sleep { link: self, until }
146    }
147
148    /// Read and discard input for `period` from now: the idle server's NAK
149    /// (it NAKs once, a server timeout after its last packet, and then stays
150    /// silent) sits in the buffers until read. Returns the number of bytes
151    /// discarded.
152    pub(crate) async fn drain(&self, period: Duration) -> io::Result<usize> {
153        let end = self.now() + period;
154        let mut discarded = 0;
155        while self.now() < end {
156            discarded += self.read(Some(end)).await?.len();
157        }
158        Ok(discarded)
159    }
160
161    // ---- the I/O owner's side ----
162
163    pub(crate) fn set_now(&self, now: Instant) {
164        let mut st = self.state();
165        // A clock never runs backwards for the protocol machines.
166        if now > st.now {
167            st.now = now;
168        }
169    }
170
171    /// Feed bytes. Nothing is cut: during an operation every byte counts.
172    pub(crate) fn push_input(&self, bytes: &[u8]) {
173        self.state().input.extend_from_slice(bytes);
174    }
175
176    /// Keep at most the newest [`MAX_IDLE_INPUT`] bytes of unread input,
177    /// while no operation reads it.
178    pub(crate) fn cap_idle_input(&self) {
179        let mut st = self.state();
180        let excess = st.input.len().saturating_sub(MAX_IDLE_INPUT);
181        if excess > 0 {
182            st.input.drain(..excess);
183        }
184    }
185
186    pub(crate) fn fail(&self, error: &io::Error) {
187        let mut st = self.state();
188        if st.error.is_none() {
189            st.error = Some((error.kind(), error.to_string()));
190        }
191    }
192
193    /// Forget the link's error: the next operation tries the link again.
194    pub(crate) fn clear_error(&self) {
195        self.state().error = None;
196    }
197
198    /// Bytes fed and not read yet.
199    #[cfg(test)]
200    pub(crate) fn unread_input(&self) -> usize {
201        self.state().input.len()
202    }
203
204    pub(crate) fn take_output(&self) -> Option<Vec<u8>> {
205        self.state().output.pop_front()
206    }
207
208    pub(crate) fn take_event(&self) -> Option<Progress> {
209        self.state().events.pop_front()
210    }
211
212    pub(crate) fn set_keep_events(&self, keep: bool) {
213        let mut st = self.state();
214        st.keep_events = keep;
215        if !keep {
216            st.events.clear();
217        }
218    }
219
220    /// When the pending wait ends without input (`None`: it waits for input
221    /// only, or nothing waits).
222    pub(crate) fn wake(&self) -> Option<Instant> {
223        self.state().wake
224    }
225
226    /// Forget everything of an aborted operation: queued packets, events
227    /// not taken, unread input (a partial packet would garble the next
228    /// operation's first read) and the wait.
229    pub(crate) fn reset(&self) {
230        let mut st = self.state();
231        st.output.clear();
232        st.events.clear();
233        st.input.clear();
234        st.wake = None;
235    }
236
237    /// Poll `future` once with a no-op waker. The wake-up deadline is
238    /// cleared first; a pending read or sleep sets it again.
239    pub(crate) fn poll<F: Future + ?Sized>(&self, future: Pin<&mut F>) -> Poll<F::Output> {
240        self.state().wake = None;
241        let mut cx = Context::from_waker(Waker::noop());
242        future.poll(&mut cx)
243    }
244}
245
246/// See [`Link::read`].
247pub(crate) struct Read<'a> {
248    link: &'a Link,
249    deadline: Option<Instant>,
250}
251
252impl Future for Read<'_> {
253    type Output = io::Result<Vec<u8>>;
254
255    fn poll(self: Pin<&mut Self>, _cx: &mut Context<'_>) -> Poll<Self::Output> {
256        let mut st = self.link.state();
257        if !st.input.is_empty() {
258            return Poll::Ready(Ok(std::mem::take(&mut st.input)));
259        }
260        if let Some((kind, msg)) = &st.error {
261            return Poll::Ready(Err(io::Error::new(*kind, msg.clone())));
262        }
263        if self.deadline.is_some_and(|d| st.now >= d) {
264            return Poll::Ready(Ok(Vec::new()));
265        }
266        st.wake = self.deadline;
267        Poll::Pending
268    }
269}
270
271/// See [`Link::flush`].
272pub(crate) struct Flush<'a> {
273    link: &'a Link,
274}
275
276impl Future for Flush<'_> {
277    type Output = io::Result<()>;
278
279    fn poll(self: Pin<&mut Self>, _cx: &mut Context<'_>) -> Poll<Self::Output> {
280        let st = self.link.state();
281        if st.write_through && !st.output.is_empty() {
282            return Poll::Pending;
283        }
284        match &st.error {
285            Some((kind, msg)) => Poll::Ready(Err(io::Error::new(*kind, msg.clone()))),
286            None => Poll::Ready(Ok(())),
287        }
288    }
289}
290
291/// See [`Link::sleep_until`].
292pub(crate) struct Sleep<'a> {
293    link: &'a Link,
294    until: Instant,
295}
296
297impl Future for Sleep<'_> {
298    type Output = ();
299
300    fn poll(self: Pin<&mut Self>, _cx: &mut Context<'_>) -> Poll<()> {
301        let mut st = self.link.state();
302        if st.now >= self.until {
303            return Poll::Ready(());
304        }
305        st.wake = Some(self.until);
306        Poll::Pending
307    }
308}
309
310/// Read wait of [`drive`] while the protocol waits for input without a
311/// deadline.
312#[cfg(not(target_arch = "wasm32"))]
313const IDLE_WAIT: Duration = Duration::from_millis(100);
314/// Shortest timeout handed to [`Transport::read`].
315#[cfg(not(target_arch = "wasm32"))]
316const MIN_WAIT: Duration = Duration::from_millis(1);
317
318/// Run `future` to completion over `transport` with the system clock: write
319/// what it queues, read until its wake-up deadline and feed what arrives.
320/// `progress` sees every event. A failing write or read is fed to the link
321/// as its error, which the protocol logic sees on its next read, write or
322/// flush; the next `drive` tries the transport again. After writing, the
323/// future is polled again before anything is read, so a flush returns at
324/// once. While the link has failed and the future still waits (a pause),
325/// the wait is slept instead of read, as the pause was before the seam.
326/// Packets still queued when the future completes are written; a failure
327/// then is ignored (the result is decided).
328#[cfg(not(target_arch = "wasm32"))]
329pub(crate) fn drive<F: Future>(
330    transport: &mut dyn Transport,
331    link: &Link,
332    future: F,
333    progress: &mut dyn FnMut(&Progress),
334) -> F::Output {
335    link.clear_error();
336    link.state().write_through = true;
337    let mut future = std::pin::pin!(future);
338    let mut buf = [0u8; 2048];
339    loop {
340        link.set_now(Instant::now());
341        let polled = link.poll(future.as_mut());
342        let mut wrote = false;
343        while let Some(packet) = link.take_output() {
344            wrote = true;
345            if let Err(e) = transport.write_packet(&packet) {
346                link.fail(&e);
347            }
348        }
349        while let Some(event) = link.take_event() {
350            progress(&event);
351        }
352        if let Poll::Ready(output) = polled {
353            return output;
354        }
355        if wrote {
356            continue;
357        }
358        let wait = link
359            .wake()
360            .map_or(IDLE_WAIT, |w| w.saturating_duration_since(Instant::now()));
361        if link.state().error.is_some() {
362            std::thread::sleep(wait);
363            continue;
364        }
365        match transport.read(&mut buf, wait.max(MIN_WAIT)) {
366            Ok(n) => link.push_input(buf.get(..n).unwrap_or_default()),
367            Err(e) => link.fail(&e),
368        }
369    }
370}
371
372#[cfg(test)]
373#[allow(clippy::unwrap_used, clippy::expect_used)]
374mod tests {
375    use super::*;
376
377    #[test]
378    fn read_waits_for_input_or_the_deadline() {
379        let t0 = Instant::now();
380        let link = Link::new(t0);
381        let mut read = std::pin::pin!(link.read(Some(t0 + Duration::from_millis(10))));
382        assert!(link.poll(read.as_mut()).is_pending());
383        assert_eq!(link.wake(), Some(t0 + Duration::from_millis(10)));
384        link.push_input(b"ab");
385        assert!(matches!(link.poll(read.as_mut()), Poll::Ready(Ok(v)) if v == b"ab"));
386        let mut read = std::pin::pin!(link.read(Some(t0 + Duration::from_millis(10))));
387        link.set_now(t0 + Duration::from_millis(10));
388        assert!(matches!(link.poll(read.as_mut()), Poll::Ready(Ok(v)) if v.is_empty()));
389    }
390
391    #[test]
392    fn a_failed_link_fails_reads_after_the_input_and_writes() {
393        let link = Link::new(Instant::now());
394        link.push_input(b"x");
395        link.fail(&io::Error::from(io::ErrorKind::UnexpectedEof));
396        let mut read = std::pin::pin!(link.read(None));
397        assert!(matches!(link.poll(read.as_mut()), Poll::Ready(Ok(v)) if v == b"x"));
398        let mut read = std::pin::pin!(link.read(None));
399        assert!(matches!(
400            link.poll(read.as_mut()),
401            Poll::Ready(Err(e)) if e.kind() == io::ErrorKind::UnexpectedEof
402        ));
403        assert!(link.write(b"p".to_vec()).is_err());
404    }
405
406    #[test]
407    fn the_clock_never_runs_backwards_and_idle_input_is_capped() {
408        let t0 = Instant::now();
409        let link = Link::new(t0 + Duration::from_secs(1));
410        link.set_now(t0);
411        assert_eq!(link.now(), t0 + Duration::from_secs(1));
412        link.push_input(&vec![0; MAX_IDLE_INPUT]);
413        link.push_input(b"new");
414        link.cap_idle_input();
415        let mut read = std::pin::pin!(link.read(None));
416        let Poll::Ready(Ok(v)) = link.poll(read.as_mut()) else {
417            panic!("no input");
418        };
419        assert_eq!(v.len(), MAX_IDLE_INPUT);
420        assert!(v.ends_with(b"new"));
421    }
422}