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};
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct SessionStats {
pub bytes_delivered: u32,
pub frames_sent: u32,
pub retries: u32,
pub nacks: u32,
pub duplicates: u32,
pub crc_errors: u32,
pub ticks: u64,
}
impl SessionStats {
pub const fn new() -> Self {
SessionStats {
bytes_delivered: 0,
frames_sent: 0,
retries: 0,
nacks: 0,
duplicates: 0,
crc_errors: 0,
ticks: 0,
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum PumpEvent {
Idle,
Progress,
Sent,
Received(u8),
Completed,
Aborted,
}
pub struct Pump<Tx, Rx>
where
Tx: ByteTransport,
Rx: ByteTransport<Error = Tx::Error>,
{
tx: Sender<Tx>,
rx: Receiver<Rx>,
stats: SessionStats,
last_acked: bool,
tx_done_seen: bool,
pending_completed: bool,
}
impl<Tx, Rx> Pump<Tx, Rx>
where
Tx: ByteTransport,
Rx: ByteTransport<Error = Tx::Error>,
{
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,
}
}
pub fn on(tx: Tx, rx: Rx) -> Self {
Self::new(Sender::new(tx), Receiver::new(rx))
}
pub fn on_with(tx: Tx, rx: Rx, policy: RetryPolicy) -> Self {
Self::new(Sender::with_policy(tx, policy), Receiver::new(rx))
}
pub fn stats(&self) -> SessionStats {
self.stats
}
pub fn sender(&self) -> &Sender<Tx> {
&self.tx
}
pub fn sender_mut(&mut self) -> &mut Sender<Tx> {
&mut self.tx
}
pub fn receiver(&self) -> &Receiver<Rx> {
&self.rx
}
pub fn receiver_mut(&mut self) -> &mut Receiver<Rx> {
&mut self.rx
}
pub fn abort(&mut self) -> Result<(), Error<Tx::Error>> {
self.tx.offer_abort()
}
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)
}
}
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)
}
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)?;
}
}
}
}
}
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,
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>,
{
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,
}
}
pub fn on(tx: Tx, rx: Rx) -> Self {
Self::new(WindowedSender::new(tx), WindowedReceiver::new(rx))
}
pub fn on_with(tx: Tx, rx: Rx, policy: RetryPolicy) -> Self {
Self::new(
WindowedSender::with_policy(tx, policy),
WindowedReceiver::new(rx),
)
}
pub fn stats(&self) -> SessionStats {
self.stats
}
pub fn sender(&self) -> &WindowedSender<Tx, N> {
&self.tx
}
pub fn sender_mut(&mut self) -> &mut WindowedSender<Tx, N> {
&mut self.tx
}
pub fn receiver(&self) -> &WindowedReceiver<Rx, N> {
&self.rx
}
pub fn receiver_mut(&mut self) -> &mut WindowedReceiver<Rx, N> {
&mut self.rx
}
pub fn set_window_limit(&mut self, limit: usize) {
self.tx.set_window_limit(limit);
self.rx.set_window_limit(limit);
}
pub fn window_limit(&self) -> usize {
self.tx.window_limit()
}
pub fn abort(&mut self) -> Result<(), Error<Tx::Error>> {
self.tx.offer_abort()
}
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)
}
}
}