1use 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#[derive(Clone, Debug, PartialEq, Eq)]
35pub enum Progress {
36 Kermit(kermit_proto::Event),
39 Xmodem(xmodem_proto::Event),
41}
42
43const MAX_IDLE_INPUT: usize = 64 * 1024;
49
50#[derive(Debug)]
51struct State {
52 now: Instant,
54 input: Vec<u8>,
56 output: VecDeque<Vec<u8>>,
58 events: VecDeque<Progress>,
60 keep_events: bool,
63 wake: Option<Instant>,
66 error: Option<(io::ErrorKind, String)>,
69 write_through: bool,
74}
75
76#[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 self.0.lock().unwrap_or_else(PoisonError::into_inner)
98 }
99
100 pub(crate) fn now(&self) -> Instant {
104 self.state().now
105 }
106
107 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 pub(crate) fn flush(&self) -> Flush<'_> {
121 Flush { link: self }
122 }
123
124 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 pub(crate) fn read(&self, deadline: Option<Instant>) -> Read<'_> {
136 Read {
137 link: self,
138 deadline,
139 }
140 }
141
142 pub(crate) fn sleep_until(&self, until: Instant) -> Sleep<'_> {
145 Sleep { link: self, until }
146 }
147
148 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 pub(crate) fn set_now(&self, now: Instant) {
164 let mut st = self.state();
165 if now > st.now {
167 st.now = now;
168 }
169 }
170
171 pub(crate) fn push_input(&self, bytes: &[u8]) {
173 self.state().input.extend_from_slice(bytes);
174 }
175
176 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 pub(crate) fn clear_error(&self) {
195 self.state().error = None;
196 }
197
198 #[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 pub(crate) fn wake(&self) -> Option<Instant> {
223 self.state().wake
224 }
225
226 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 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
246pub(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
271pub(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
291pub(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#[cfg(not(target_arch = "wasm32"))]
313const IDLE_WAIT: Duration = Duration::from_millis(100);
314#[cfg(not(target_arch = "wasm32"))]
316const MIN_WAIT: Duration = Duration::from_millis(1);
317
318#[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}