Skip to main content

psicose/
pump.rs

1//! Cooperative session pump: one RX step, one TX step, never a loop.
2//!
3//! ```text
4//!                    PSICOSE SESSION
5//! ┌──────────────────────────────────────────────┐
6//! │  Sender (TxState)     Receiver (RxState)     │
7//! │                 └── Pump ──┘                 │
8//! └───────────────────┬──────────────────────────┘
9//!                     │
10//!               TYPE|SEQ|DATA|CRC
11//! ```
12//!
13//! [`Pump::poll`] returns immediately. The caller decides when to call
14//! again. [`Pump::send_all`] is only that loop stacked on top.
15
16use crate::error::Error;
17use crate::rx::{PollOutcome, Receiver};
18use crate::stream::StreamError;
19use crate::timeout::{IdleBudget, RetryPolicy};
20use crate::transport::{ByteSource, ByteTransport};
21use crate::tx::{Sender, TxPoll, TxState};
22use crate::window::{WindowedReceiver, WindowedSender};
23
24/// Session counters. `Copy`, stack-only, no logging.
25///
26/// These fields are the future PSICOSE-8 registers (`BYTES_*`, `RETRIES`,
27/// `NACKS`, `CRC_ERRORS`, `DUPLICATES`) without turning the runtime into
28/// a VM.
29#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
30pub struct SessionStats {
31    /// Payload bytes the receiver delivered (after the ACK was written).
32    pub bytes_delivered: u32,
33    /// Frames whose four bytes fully left the sender `OutBuf`.
34    pub frames_sent: u32,
35    /// Times the sender entered retransmission.
36    pub retries: u32,
37    /// NACKs generated by the receiver.
38    pub nacks: u32,
39    /// Duplicate DATA frames the receiver re-ACKed without delivering.
40    pub duplicates: u32,
41    /// Frames the receiver rejected for CRC (also counted in [`Self::nacks`]).
42    pub crc_errors: u32,
43    /// How many times [`Pump::poll`] was called.
44    pub ticks: u64,
45}
46
47impl SessionStats {
48    /// All counters at zero. `const` twin of `Default::default()`.
49    pub const fn new() -> Self {
50        SessionStats {
51            bytes_delivered: 0,
52            frames_sent: 0,
53            retries: 0,
54            nacks: 0,
55            duplicates: 0,
56            crc_errors: 0,
57            ticks: 0,
58        }
59    }
60}
61
62/// Outcome of one cooperative [`Pump::poll`].
63#[derive(Debug, Clone, Copy, PartialEq, Eq)]
64pub enum PumpEvent {
65    /// Both sides were quiet.
66    Idle,
67    /// Work happened (write, retry, START, NACK, …) without a payload event.
68    Progress,
69    /// A DATA byte was ACKed on the sender.
70    Sent,
71    /// A new payload byte was delivered on the receiver.
72    Received(u8),
73    /// FINISH was completed on either side.
74    Completed,
75    /// ABORT cancelled the session.
76    Aborted,
77}
78
79/// One session: a [`Sender`] and a [`Receiver`] driven by the same poll.
80///
81/// `Rx::Error` must be the same type as `Tx::Error` so a single
82/// [`Error`] covers the pair.
83pub struct Pump<Tx, Rx>
84where
85    Tx: ByteTransport,
86    Rx: ByteTransport<Error = Tx::Error>,
87{
88    tx: Sender<Tx>,
89    rx: Receiver<Rx>,
90    stats: SessionStats,
91    last_acked: bool,
92    /// `Sender` stays `Finished` and would report `TransferDone` forever.
93    /// The edge is reported once so later RX bytes are not dropped.
94    tx_done_seen: bool,
95    /// App byte and a fresh TX completion arrived in the same step.
96    pending_completed: bool,
97}
98
99impl<Tx, Rx> Pump<Tx, Rx>
100where
101    Tx: ByteTransport,
102    Rx: ByteTransport<Error = Tx::Error>,
103{
104    /// Wraps an existing sender/receiver pair.
105    pub fn new(tx: Sender<Tx>, rx: Receiver<Rx>) -> Self {
106        Pump {
107            tx,
108            rx,
109            stats: SessionStats::default(),
110            last_acked: false,
111            tx_done_seen: false,
112            pending_completed: false,
113        }
114    }
115
116    /// A pump on raw transports: `Pump::on(uart_tx, uart_rx)`.
117    pub fn on(tx: Tx, rx: Rx) -> Self {
118        Self::new(Sender::new(tx), Receiver::new(rx))
119    }
120
121    /// [`Self::on`] with an explicit [`RetryPolicy`].
122    pub fn on_with(tx: Tx, rx: Rx, policy: RetryPolicy) -> Self {
123        Self::new(Sender::with_policy(tx, policy), Receiver::new(rx))
124    }
125
126    /// Current counters. Copy them; the pump keeps owning the live set.
127    pub fn stats(&self) -> SessionStats {
128        self.stats
129    }
130
131    /// The sender.
132    pub fn sender(&self) -> &Sender<Tx> {
133        &self.tx
134    }
135
136    /// The sender, mutably (for `offer` / `offer_start` / `offer_finish`).
137    pub fn sender_mut(&mut self) -> &mut Sender<Tx> {
138        &mut self.tx
139    }
140
141    /// The receiver.
142    pub fn receiver(&self) -> &Receiver<Rx> {
143        &self.rx
144    }
145
146    /// The receiver, mutably.
147    pub fn receiver_mut(&mut self) -> &mut Receiver<Rx> {
148        &mut self.rx
149    }
150
151    /// Cancels the session: drops any in-flight TX frame and sends ABORT.
152    pub fn abort(&mut self) -> Result<(), Error<Tx::Error>> {
153        self.tx.offer_abort()
154    }
155
156    /// One non-blocking step: RX first, then TX. Never loops.
157    ///
158    /// 1. Give RX a chance (ACK/NACK/ABORT/DATA).
159    /// 2. If RX accepted ABORT, locally cancel TX (do not send a second ABORT).
160    /// 3. Let TX write or wait.
161    /// 4. Return immediately.
162    ///
163    /// `TransferDone` is edge-triggered. The sender stays in `Finished`, but
164    /// a later poll still returns RX bytes instead of repeating `Completed`.
165    pub fn poll(&mut self) -> Result<PumpEvent, Error<Tx::Error>> {
166        self.stats.ticks = self.stats.ticks.saturating_add(1);
167
168        if self.pending_completed {
169            self.pending_completed = false;
170            return Ok(PumpEvent::Completed);
171        }
172
173        let rx = self.rx.poll()?;
174        match rx {
175            PollOutcome::Delivered(_) => {
176                self.stats.bytes_delivered = self.stats.bytes_delivered.saturating_add(1);
177            }
178            PollOutcome::DuplicateIgnored => {
179                self.stats.duplicates = self.stats.duplicates.saturating_add(1);
180            }
181            PollOutcome::Rejected => {
182                self.stats.nacks = self.stats.nacks.saturating_add(1);
183            }
184            PollOutcome::CrcRejected => {
185                self.stats.nacks = self.stats.nacks.saturating_add(1);
186                self.stats.crc_errors = self.stats.crc_errors.saturating_add(1);
187            }
188            PollOutcome::Aborted => {
189                // Peer abort cancels DATA. Do not kill our own ABORT/START
190                // handshake — RX may still emit Aborted while finishing ACK 0.
191                if !self.tx.holds_session_control() {
192                    self.tx.force_abort();
193                }
194            }
195            PollOutcome::Pending | PollOutcome::Started | PollOutcome::TransferFinished => {}
196        }
197
198        let tx = self.tx.poll()?;
199        self.last_acked = matches!(tx, TxPoll::Acked);
200        let mark = self.tx.take_mark();
201        if mark.frame_on_wire {
202            self.stats.frames_sent = self.stats.frames_sent.saturating_add(1);
203        }
204        if mark.retransmit {
205            self.stats.retries = self.stats.retries.saturating_add(1);
206        }
207
208        let tx_done_edge = matches!(tx, TxPoll::TransferDone) && !self.tx_done_seen;
209        self.tx_done_seen = matches!(tx, TxPoll::TransferDone);
210
211        if matches!(rx, PollOutcome::Aborted) || matches!(tx, TxPoll::Aborted) {
212            return Ok(PumpEvent::Aborted);
213        }
214        if let PollOutcome::Delivered(byte) = rx {
215            if tx_done_edge {
216                self.pending_completed = true;
217            }
218            return Ok(PumpEvent::Received(byte));
219        }
220        if matches!(rx, PollOutcome::TransferFinished) || tx_done_edge {
221            return Ok(PumpEvent::Completed);
222        }
223        if matches!(tx, TxPoll::Acked) {
224            return Ok(PumpEvent::Sent);
225        }
226
227        let progress = !matches!(rx, PollOutcome::Pending)
228            || !matches!(tx, TxPoll::Pending)
229            || mark.frame_on_wire
230            || mark.retransmit
231            || mark.nack;
232        if progress {
233            Ok(PumpEvent::Progress)
234        } else {
235            Ok(PumpEvent::Idle)
236        }
237    }
238
239    /// Drain `src` through the pump, then FINISH. Convenience over [`Self::poll`].
240    ///
241    /// Uses [`IdleBudget::DEFAULT`] so a silent peer cannot spin forever.
242    /// Override with [`Self::send_all_budgeted`].
243    ///
244    /// Returns how many DATA bytes the peer ACKed. On a single-thread pair
245    /// this works because each poll serves RX (so ACKs are written) and TX.
246    pub fn send_all<S: ByteSource>(
247        &mut self,
248        src: &mut S,
249    ) -> Result<u64, StreamError<Tx::Error, S::Error>> {
250        self.send_all_budgeted(src, IdleBudget::DEFAULT)
251    }
252
253    /// [`Self::send_all`] with an [`IdleBudget`] so a silent peer cannot spin
254    /// forever. Retransmit/`Progress` polls do **not** reset the budget —
255    /// only [`PumpEvent::Sent`] / [`PumpEvent::Received`] do. Per-frame
256    /// retries remain governed by [`RetryPolicy`].
257    pub fn send_all_budgeted<S: ByteSource>(
258        &mut self,
259        src: &mut S,
260        mut budget: IdleBudget,
261    ) -> Result<u64, StreamError<Tx::Error, S::Error>> {
262        let mut n = 0u64;
263        let mut hold = None;
264        let mut exhausted = false;
265        let mut finish_offered = false;
266        loop {
267            if hold.is_none() && !exhausted {
268                match src.read_byte().map_err(StreamError::Application)? {
269                    Some(b) => hold = Some(b),
270                    None => exhausted = true,
271                }
272            }
273            if self.tx.state() == TxState::Idle {
274                if let Some(b) = hold.take() {
275                    self.tx.offer(b).map_err(StreamError::Protocol)?;
276                } else if exhausted && !finish_offered {
277                    match self.tx.offer_finish() {
278                        Ok(()) => finish_offered = true,
279                        Err(Error::NotIdle) => {}
280                        Err(e) => return Err(StreamError::Protocol(e)),
281                    }
282                }
283            }
284            let ev = self.poll().map_err(StreamError::Protocol)?;
285            if self.last_acked {
286                n = n.saturating_add(1);
287            }
288            match ev {
289                PumpEvent::Completed => return Ok(n),
290                PumpEvent::Aborted => return Err(StreamError::Protocol(Error::Aborted)),
291                PumpEvent::Sent | PumpEvent::Received(_) => budget.reset(),
292                PumpEvent::Idle | PumpEvent::Progress => {
293                    budget.tick().map_err(StreamError::Protocol)?;
294                }
295            }
296        }
297    }
298}
299
300/// Cooperative pump over a selective-repeat window (`N ≤ 8`).
301///
302/// Same poll contract as [`Pump`]: one RX step, one TX step, never a loop.
303/// Used by [`crate::PeerLink`] so a negotiated `WINDOW` is real on the wire.
304pub struct WindowedPump<Tx, Rx, const N: usize>
305where
306    Tx: ByteTransport,
307    Rx: ByteTransport<Error = Tx::Error>,
308{
309    tx: WindowedSender<Tx, N>,
310    rx: WindowedReceiver<Rx, N>,
311    stats: SessionStats,
312    last_acked: bool,
313    /// See [`Pump::poll`]: `TransferDone` stays latched on `Finished`.
314    tx_done_seen: bool,
315    pending_completed: bool,
316}
317
318impl<Tx, Rx, const N: usize> WindowedPump<Tx, Rx, N>
319where
320    Tx: ByteTransport,
321    Rx: ByteTransport<Error = Tx::Error>,
322{
323    /// Wraps an existing windowed sender/receiver pair.
324    pub fn new(tx: WindowedSender<Tx, N>, rx: WindowedReceiver<Rx, N>) -> Self {
325        WindowedPump {
326            tx,
327            rx,
328            stats: SessionStats::default(),
329            last_acked: false,
330            tx_done_seen: false,
331            pending_completed: false,
332        }
333    }
334
335    /// `WindowedPump::on(uart_tx, uart_rx)`.
336    pub fn on(tx: Tx, rx: Rx) -> Self {
337        Self::new(WindowedSender::new(tx), WindowedReceiver::new(rx))
338    }
339
340    /// [`Self::on`] with an explicit [`RetryPolicy`].
341    pub fn on_with(tx: Tx, rx: Rx, policy: RetryPolicy) -> Self {
342        Self::new(
343            WindowedSender::with_policy(tx, policy),
344            WindowedReceiver::new(rx),
345        )
346    }
347
348    /// Current counters.
349    pub fn stats(&self) -> SessionStats {
350        self.stats
351    }
352
353    /// The windowed sender.
354    pub fn sender(&self) -> &WindowedSender<Tx, N> {
355        &self.tx
356    }
357
358    /// The windowed sender, mutably.
359    pub fn sender_mut(&mut self) -> &mut WindowedSender<Tx, N> {
360        &mut self.tx
361    }
362
363    /// The windowed receiver.
364    pub fn receiver(&self) -> &WindowedReceiver<Rx, N> {
365        &self.rx
366    }
367
368    /// The windowed receiver, mutably.
369    pub fn receiver_mut(&mut self) -> &mut WindowedReceiver<Rx, N> {
370        &mut self.rx
371    }
372
373    /// Runtime DATA window on both sides (`1..=N`).
374    pub fn set_window_limit(&mut self, limit: usize) {
375        self.tx.set_window_limit(limit);
376        self.rx.set_window_limit(limit);
377    }
378
379    /// Current runtime DATA window.
380    pub fn window_limit(&self) -> usize {
381        self.tx.window_limit()
382    }
383
384    /// Cancels the session: ABORT on the wire.
385    pub fn abort(&mut self) -> Result<(), Error<Tx::Error>> {
386        self.tx.offer_abort()
387    }
388
389    /// One non-blocking step: RX first, then TX. Never loops.
390    ///
391    /// `TransferDone` is edge-triggered, same as [`Pump::poll`], so a
392    /// later session's bytes are not discarded.
393    pub fn poll(&mut self) -> Result<PumpEvent, Error<Tx::Error>> {
394        self.stats.ticks = self.stats.ticks.saturating_add(1);
395
396        if self.pending_completed {
397            self.pending_completed = false;
398            return Ok(PumpEvent::Completed);
399        }
400
401        let rx = self.rx.poll()?;
402        match rx {
403            PollOutcome::Delivered(_) => {
404                self.stats.bytes_delivered = self.stats.bytes_delivered.saturating_add(1);
405            }
406            PollOutcome::DuplicateIgnored => {
407                self.stats.duplicates = self.stats.duplicates.saturating_add(1);
408            }
409            PollOutcome::Rejected => {
410                self.stats.nacks = self.stats.nacks.saturating_add(1);
411            }
412            PollOutcome::CrcRejected => {
413                self.stats.nacks = self.stats.nacks.saturating_add(1);
414                self.stats.crc_errors = self.stats.crc_errors.saturating_add(1);
415            }
416            PollOutcome::Aborted => {
417                if !self.tx.holds_session_control() {
418                    self.tx.force_abort();
419                }
420            }
421            PollOutcome::Pending | PollOutcome::Started | PollOutcome::TransferFinished => {}
422        }
423
424        let tx = self.tx.poll()?;
425        self.last_acked = matches!(tx, TxPoll::Acked);
426        let mark = self.tx.take_mark();
427        if mark.frame_on_wire {
428            self.stats.frames_sent = self.stats.frames_sent.saturating_add(1);
429        }
430        if mark.retransmit {
431            self.stats.retries = self.stats.retries.saturating_add(1);
432        }
433
434        let tx_done_edge = matches!(tx, TxPoll::TransferDone) && !self.tx_done_seen;
435        self.tx_done_seen = matches!(tx, TxPoll::TransferDone);
436
437        if matches!(rx, PollOutcome::Aborted) || matches!(tx, TxPoll::Aborted) {
438            return Ok(PumpEvent::Aborted);
439        }
440        if let PollOutcome::Delivered(byte) = rx {
441            if tx_done_edge {
442                self.pending_completed = true;
443            }
444            return Ok(PumpEvent::Received(byte));
445        }
446        if matches!(rx, PollOutcome::TransferFinished) || tx_done_edge {
447            return Ok(PumpEvent::Completed);
448        }
449        if matches!(tx, TxPoll::Acked) {
450            return Ok(PumpEvent::Sent);
451        }
452
453        let progress = !matches!(rx, PollOutcome::Pending)
454            || !matches!(tx, TxPoll::Pending)
455            || mark.frame_on_wire
456            || mark.retransmit
457            || mark.nack;
458        if progress {
459            Ok(PumpEvent::Progress)
460        } else {
461            Ok(PumpEvent::Idle)
462        }
463    }
464}