psicose 0.4.3

no_std heapless reliable link motor: 4-byte frame, ACK/CRC, window N≤8, P2P Node/PeerLink, LinkFace — zero crate dependencies
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
//! Cooperative session pump: one RX step, one TX step, never a loop.
//!
//! ```text
//!                    PSICOSE SESSION
//! ┌──────────────────────────────────────────────┐
//! │  Sender (TxState)     Receiver (RxState)     │
//! │                 └── Pump ──┘                 │
//! └───────────────────┬──────────────────────────┘
//!                     │
//!               TYPE|SEQ|DATA|CRC
//! ```
//!
//! [`Pump::poll`] returns immediately. The caller decides when to call
//! again. [`Pump::send_all`] is only that loop stacked on top.

use crate::error::Error;
use crate::rx::{PollOutcome, Receiver};
use crate::stream::StreamError;
use crate::timeout::{IdleBudget, RetryPolicy};
use crate::transport::{ByteSource, ByteTransport};
use crate::tx::{Sender, TxPoll, TxState};
use crate::window::{WindowedReceiver, WindowedSender};

/// Session counters. `Copy`, stack-only, no logging.
///
/// These fields are the future PSICOSE-8 registers (`BYTES_*`, `RETRIES`,
/// `NACKS`, `CRC_ERRORS`, `DUPLICATES`) without turning the runtime into
/// a VM.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct SessionStats {
    /// Payload bytes the receiver delivered (after the ACK was written).
    pub bytes_delivered: u32,
    /// Frames whose four bytes fully left the sender `OutBuf`.
    pub frames_sent: u32,
    /// Times the sender entered retransmission.
    pub retries: u32,
    /// NACKs generated by the receiver.
    pub nacks: u32,
    /// Duplicate DATA frames the receiver re-ACKed without delivering.
    pub duplicates: u32,
    /// Frames the receiver rejected for CRC (also counted in [`Self::nacks`]).
    pub crc_errors: u32,
    /// How many times [`Pump::poll`] was called.
    pub ticks: u64,
}

impl SessionStats {
    /// All counters at zero. `const` twin of `Default::default()`.
    pub const fn new() -> Self {
        SessionStats {
            bytes_delivered: 0,
            frames_sent: 0,
            retries: 0,
            nacks: 0,
            duplicates: 0,
            crc_errors: 0,
            ticks: 0,
        }
    }
}

/// Outcome of one cooperative [`Pump::poll`].
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum PumpEvent {
    /// Both sides were quiet.
    Idle,
    /// Work happened (write, retry, START, NACK, …) without a payload event.
    Progress,
    /// A DATA byte was ACKed on the sender.
    Sent,
    /// A new payload byte was delivered on the receiver.
    Received(u8),
    /// FINISH was completed on either side.
    Completed,
    /// ABORT cancelled the session.
    Aborted,
}

/// One session: a [`Sender`] and a [`Receiver`] driven by the same poll.
///
/// `Rx::Error` must be the same type as `Tx::Error` so a single
/// [`Error`] covers the pair.
pub struct Pump<Tx, Rx>
where
    Tx: ByteTransport,
    Rx: ByteTransport<Error = Tx::Error>,
{
    tx: Sender<Tx>,
    rx: Receiver<Rx>,
    stats: SessionStats,
    last_acked: bool,
    /// `Sender` stays `Finished` and would report `TransferDone` forever.
    /// The edge is reported once so later RX bytes are not dropped.
    tx_done_seen: bool,
    /// App byte and a fresh TX completion arrived in the same step.
    pending_completed: bool,
}

impl<Tx, Rx> Pump<Tx, Rx>
where
    Tx: ByteTransport,
    Rx: ByteTransport<Error = Tx::Error>,
{
    /// Wraps an existing sender/receiver pair.
    pub fn new(tx: Sender<Tx>, rx: Receiver<Rx>) -> Self {
        Pump {
            tx,
            rx,
            stats: SessionStats::default(),
            last_acked: false,
            tx_done_seen: false,
            pending_completed: false,
        }
    }

    /// A pump on raw transports: `Pump::on(uart_tx, uart_rx)`.
    pub fn on(tx: Tx, rx: Rx) -> Self {
        Self::new(Sender::new(tx), Receiver::new(rx))
    }

    /// [`Self::on`] with an explicit [`RetryPolicy`].
    pub fn on_with(tx: Tx, rx: Rx, policy: RetryPolicy) -> Self {
        Self::new(Sender::with_policy(tx, policy), Receiver::new(rx))
    }

    /// Current counters. Copy them; the pump keeps owning the live set.
    pub fn stats(&self) -> SessionStats {
        self.stats
    }

    /// The sender.
    pub fn sender(&self) -> &Sender<Tx> {
        &self.tx
    }

    /// The sender, mutably (for `offer` / `offer_start` / `offer_finish`).
    pub fn sender_mut(&mut self) -> &mut Sender<Tx> {
        &mut self.tx
    }

    /// The receiver.
    pub fn receiver(&self) -> &Receiver<Rx> {
        &self.rx
    }

    /// The receiver, mutably.
    pub fn receiver_mut(&mut self) -> &mut Receiver<Rx> {
        &mut self.rx
    }

    /// Cancels the session: drops any in-flight TX frame and sends ABORT.
    pub fn abort(&mut self) -> Result<(), Error<Tx::Error>> {
        self.tx.offer_abort()
    }

    /// One non-blocking step: RX first, then TX. Never loops.
    ///
    /// 1. Give RX a chance (ACK/NACK/ABORT/DATA).
    /// 2. If RX accepted ABORT, locally cancel TX (do not send a second ABORT).
    /// 3. Let TX write or wait.
    /// 4. Return immediately.
    ///
    /// `TransferDone` is edge-triggered. The sender stays in `Finished`, but
    /// a later poll still returns RX bytes instead of repeating `Completed`.
    pub fn poll(&mut self) -> Result<PumpEvent, Error<Tx::Error>> {
        self.stats.ticks = self.stats.ticks.saturating_add(1);

        if self.pending_completed {
            self.pending_completed = false;
            return Ok(PumpEvent::Completed);
        }

        let rx = self.rx.poll()?;
        match rx {
            PollOutcome::Delivered(_) => {
                self.stats.bytes_delivered = self.stats.bytes_delivered.saturating_add(1);
            }
            PollOutcome::DuplicateIgnored => {
                self.stats.duplicates = self.stats.duplicates.saturating_add(1);
            }
            PollOutcome::Rejected => {
                self.stats.nacks = self.stats.nacks.saturating_add(1);
            }
            PollOutcome::CrcRejected => {
                self.stats.nacks = self.stats.nacks.saturating_add(1);
                self.stats.crc_errors = self.stats.crc_errors.saturating_add(1);
            }
            PollOutcome::Aborted => {
                // Peer abort cancels DATA. Do not kill our own ABORT/START
                // handshake — RX may still emit Aborted while finishing ACK 0.
                if !self.tx.holds_session_control() {
                    self.tx.force_abort();
                }
            }
            PollOutcome::Pending | PollOutcome::Started | PollOutcome::TransferFinished => {}
        }

        let tx = self.tx.poll()?;
        self.last_acked = matches!(tx, TxPoll::Acked);
        let mark = self.tx.take_mark();
        if mark.frame_on_wire {
            self.stats.frames_sent = self.stats.frames_sent.saturating_add(1);
        }
        if mark.retransmit {
            self.stats.retries = self.stats.retries.saturating_add(1);
        }

        let tx_done_edge = matches!(tx, TxPoll::TransferDone) && !self.tx_done_seen;
        self.tx_done_seen = matches!(tx, TxPoll::TransferDone);

        if matches!(rx, PollOutcome::Aborted) || matches!(tx, TxPoll::Aborted) {
            return Ok(PumpEvent::Aborted);
        }
        if let PollOutcome::Delivered(byte) = rx {
            if tx_done_edge {
                self.pending_completed = true;
            }
            return Ok(PumpEvent::Received(byte));
        }
        if matches!(rx, PollOutcome::TransferFinished) || tx_done_edge {
            return Ok(PumpEvent::Completed);
        }
        if matches!(tx, TxPoll::Acked) {
            return Ok(PumpEvent::Sent);
        }

        let progress = !matches!(rx, PollOutcome::Pending)
            || !matches!(tx, TxPoll::Pending)
            || mark.frame_on_wire
            || mark.retransmit
            || mark.nack;
        if progress {
            Ok(PumpEvent::Progress)
        } else {
            Ok(PumpEvent::Idle)
        }
    }

    /// Drain `src` through the pump, then FINISH. Convenience over [`Self::poll`].
    ///
    /// Uses [`IdleBudget::DEFAULT`] so a silent peer cannot spin forever.
    /// Override with [`Self::send_all_budgeted`].
    ///
    /// Returns how many DATA bytes the peer ACKed. On a single-thread pair
    /// this works because each poll serves RX (so ACKs are written) and TX.
    pub fn send_all<S: ByteSource>(
        &mut self,
        src: &mut S,
    ) -> Result<u64, StreamError<Tx::Error, S::Error>> {
        self.send_all_budgeted(src, IdleBudget::DEFAULT)
    }

    /// [`Self::send_all`] with an [`IdleBudget`] so a silent peer cannot spin
    /// forever. Retransmit/`Progress` polls do **not** reset the budget —
    /// only [`PumpEvent::Sent`] / [`PumpEvent::Received`] do. Per-frame
    /// retries remain governed by [`RetryPolicy`].
    pub fn send_all_budgeted<S: ByteSource>(
        &mut self,
        src: &mut S,
        mut budget: IdleBudget,
    ) -> Result<u64, StreamError<Tx::Error, S::Error>> {
        let mut n = 0u64;
        let mut hold = None;
        let mut exhausted = false;
        let mut finish_offered = false;
        loop {
            if hold.is_none() && !exhausted {
                match src.read_byte().map_err(StreamError::Application)? {
                    Some(b) => hold = Some(b),
                    None => exhausted = true,
                }
            }
            if self.tx.state() == TxState::Idle {
                if let Some(b) = hold.take() {
                    self.tx.offer(b).map_err(StreamError::Protocol)?;
                } else if exhausted && !finish_offered {
                    match self.tx.offer_finish() {
                        Ok(()) => finish_offered = true,
                        Err(Error::NotIdle) => {}
                        Err(e) => return Err(StreamError::Protocol(e)),
                    }
                }
            }
            let ev = self.poll().map_err(StreamError::Protocol)?;
            if self.last_acked {
                n = n.saturating_add(1);
            }
            match ev {
                PumpEvent::Completed => return Ok(n),
                PumpEvent::Aborted => return Err(StreamError::Protocol(Error::Aborted)),
                PumpEvent::Sent | PumpEvent::Received(_) => budget.reset(),
                PumpEvent::Idle | PumpEvent::Progress => {
                    budget.tick().map_err(StreamError::Protocol)?;
                }
            }
        }
    }
}

/// Cooperative pump over a selective-repeat window (`N ≤ 8`).
///
/// Same poll contract as [`Pump`]: one RX step, one TX step, never a loop.
/// Used by [`crate::PeerLink`] so a negotiated `WINDOW` is real on the wire.
pub struct WindowedPump<Tx, Rx, const N: usize>
where
    Tx: ByteTransport,
    Rx: ByteTransport<Error = Tx::Error>,
{
    tx: WindowedSender<Tx, N>,
    rx: WindowedReceiver<Rx, N>,
    stats: SessionStats,
    last_acked: bool,
    /// See [`Pump::poll`]: `TransferDone` stays latched on `Finished`.
    tx_done_seen: bool,
    pending_completed: bool,
}

impl<Tx, Rx, const N: usize> WindowedPump<Tx, Rx, N>
where
    Tx: ByteTransport,
    Rx: ByteTransport<Error = Tx::Error>,
{
    /// Wraps an existing windowed sender/receiver pair.
    pub fn new(tx: WindowedSender<Tx, N>, rx: WindowedReceiver<Rx, N>) -> Self {
        WindowedPump {
            tx,
            rx,
            stats: SessionStats::default(),
            last_acked: false,
            tx_done_seen: false,
            pending_completed: false,
        }
    }

    /// `WindowedPump::on(uart_tx, uart_rx)`.
    pub fn on(tx: Tx, rx: Rx) -> Self {
        Self::new(WindowedSender::new(tx), WindowedReceiver::new(rx))
    }

    /// [`Self::on`] with an explicit [`RetryPolicy`].
    pub fn on_with(tx: Tx, rx: Rx, policy: RetryPolicy) -> Self {
        Self::new(
            WindowedSender::with_policy(tx, policy),
            WindowedReceiver::new(rx),
        )
    }

    /// Current counters.
    pub fn stats(&self) -> SessionStats {
        self.stats
    }

    /// The windowed sender.
    pub fn sender(&self) -> &WindowedSender<Tx, N> {
        &self.tx
    }

    /// The windowed sender, mutably.
    pub fn sender_mut(&mut self) -> &mut WindowedSender<Tx, N> {
        &mut self.tx
    }

    /// The windowed receiver.
    pub fn receiver(&self) -> &WindowedReceiver<Rx, N> {
        &self.rx
    }

    /// The windowed receiver, mutably.
    pub fn receiver_mut(&mut self) -> &mut WindowedReceiver<Rx, N> {
        &mut self.rx
    }

    /// Runtime DATA window on both sides (`1..=N`).
    pub fn set_window_limit(&mut self, limit: usize) {
        self.tx.set_window_limit(limit);
        self.rx.set_window_limit(limit);
    }

    /// Current runtime DATA window.
    pub fn window_limit(&self) -> usize {
        self.tx.window_limit()
    }

    /// Cancels the session: ABORT on the wire.
    pub fn abort(&mut self) -> Result<(), Error<Tx::Error>> {
        self.tx.offer_abort()
    }

    /// One non-blocking step: RX first, then TX. Never loops.
    ///
    /// `TransferDone` is edge-triggered, same as [`Pump::poll`], so a
    /// later session's bytes are not discarded.
    pub fn poll(&mut self) -> Result<PumpEvent, Error<Tx::Error>> {
        self.stats.ticks = self.stats.ticks.saturating_add(1);

        if self.pending_completed {
            self.pending_completed = false;
            return Ok(PumpEvent::Completed);
        }

        let rx = self.rx.poll()?;
        match rx {
            PollOutcome::Delivered(_) => {
                self.stats.bytes_delivered = self.stats.bytes_delivered.saturating_add(1);
            }
            PollOutcome::DuplicateIgnored => {
                self.stats.duplicates = self.stats.duplicates.saturating_add(1);
            }
            PollOutcome::Rejected => {
                self.stats.nacks = self.stats.nacks.saturating_add(1);
            }
            PollOutcome::CrcRejected => {
                self.stats.nacks = self.stats.nacks.saturating_add(1);
                self.stats.crc_errors = self.stats.crc_errors.saturating_add(1);
            }
            PollOutcome::Aborted => {
                if !self.tx.holds_session_control() {
                    self.tx.force_abort();
                }
            }
            PollOutcome::Pending | PollOutcome::Started | PollOutcome::TransferFinished => {}
        }

        let tx = self.tx.poll()?;
        self.last_acked = matches!(tx, TxPoll::Acked);
        let mark = self.tx.take_mark();
        if mark.frame_on_wire {
            self.stats.frames_sent = self.stats.frames_sent.saturating_add(1);
        }
        if mark.retransmit {
            self.stats.retries = self.stats.retries.saturating_add(1);
        }

        let tx_done_edge = matches!(tx, TxPoll::TransferDone) && !self.tx_done_seen;
        self.tx_done_seen = matches!(tx, TxPoll::TransferDone);

        if matches!(rx, PollOutcome::Aborted) || matches!(tx, TxPoll::Aborted) {
            return Ok(PumpEvent::Aborted);
        }
        if let PollOutcome::Delivered(byte) = rx {
            if tx_done_edge {
                self.pending_completed = true;
            }
            return Ok(PumpEvent::Received(byte));
        }
        if matches!(rx, PollOutcome::TransferFinished) || tx_done_edge {
            return Ok(PumpEvent::Completed);
        }
        if matches!(tx, TxPoll::Acked) {
            return Ok(PumpEvent::Sent);
        }

        let progress = !matches!(rx, PollOutcome::Pending)
            || !matches!(tx, TxPoll::Pending)
            || mark.frame_on_wire
            || mark.retransmit
            || mark.nack;
        if progress {
            Ok(PumpEvent::Progress)
        } else {
            Ok(PumpEvent::Idle)
        }
    }
}