use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Mutex, PoisonError};
use std::time::{Duration, Instant};
use weida_core::Error;
use weida_protocol::header::limits::MAX_PATH_RECORD_BYTES;
use weida_protocol::{FrameKind, PathRecord, ReportHead, encode_frame};
use crate::conn::{ConnHandle, violation};
use crate::stats::{RemoteStats, TransportStats, UdpCounts};
use crate::transport::RecvHalf;
const REPORT_INTERVAL: Duration = Duration::from_secs(2);
#[derive(Default)]
pub(crate) struct RemoteSlot {
claimed: AtomicBool,
latest: Mutex<Option<(PathRecord, Instant)>>,
}
impl RemoteSlot {
pub(crate) fn latest(&self, now: Instant) -> Option<RemoteStats> {
let latest = *self.latest.lock().unwrap_or_else(PoisonError::into_inner);
latest.map(|(record, arrived)| RemoteStats {
rtt: Duration::from_micros(record.rtt_us),
min_rtt: Duration::from_micros(record.min_rtt_us),
cwnd: record.cwnd,
congestion_events: record.congestion_events,
lost_packets: record.lost_packets,
lost_bytes: record.lost_bytes,
sent_packets: record.sent_packets,
current_mtu: u16::try_from(record.current_mtu).unwrap_or(u16::MAX),
tx: UdpCounts {
datagrams: record.tx_datagrams,
bytes: record.tx_bytes,
},
rx: UdpCounts {
datagrams: record.rx_datagrams,
bytes: record.rx_bytes,
},
age: now.saturating_duration_since(arrived),
})
}
fn store(&self, record: PathRecord, now: Instant) {
*self.latest.lock().unwrap_or_else(PoisonError::into_inner) = Some((record, now));
}
}
fn record_of(stats: &TransportStats) -> PathRecord {
let path = &stats.path;
PathRecord {
rtt_us: u64::try_from(path.rtt.as_micros()).unwrap_or(u64::MAX),
min_rtt_us: u64::try_from(path.min_rtt.as_micros()).unwrap_or(u64::MAX),
cwnd: path.cwnd,
congestion_events: path.congestion_events,
lost_packets: path.lost_packets,
lost_bytes: path.lost_bytes,
sent_packets: path.sent_packets,
current_mtu: u64::from(path.current_mtu),
tx_datagrams: stats.tx.datagrams,
tx_bytes: stats.tx.bytes,
rx_datagrams: stats.rx.datagrams,
rx_bytes: stats.rx.bytes,
}
}
pub(crate) async fn send_reports(ctx: ConnHandle) {
let mut stream = match ctx.conn.open_uni().await {
Ok(stream) => stream,
Err(e) => {
tracing::debug!(error = %e, "could not open the REPORT stream");
return;
}
};
let mut out = encode_frame(FrameKind::Report, &ReportHead.encode());
loop {
if let Some(stats) = ctx.conn.transport_stats() {
record_of(&stats).encode_into(&mut out);
}
if stream.write_all(&out).await.is_err() {
return;
}
out.clear();
tokio::select! {
() = ctx.exec.sleep(REPORT_INTERVAL) => {}
_ = ctx.conn.closed() => return,
}
}
}
pub(crate) async fn receive_reports(ctx: &ConnHandle, mut stream: RecvHalf) -> Result<(), Error> {
if !ctx.agreed_now().is_some_and(|agreed| agreed.path_report) {
return violation(ctx, "REPORT without agreed capability 2");
}
if ctx.remote.claimed.swap(true, Ordering::AcqRel) {
return violation(ctx, "a second REPORT stream on one connection");
}
let mut buf = [0u8; 512];
let mut pending: Vec<u8> = Vec::with_capacity(buf.len() + MAX_PATH_RECORD_BYTES + 2);
loop {
match stream.read(&mut buf).await {
Ok(Some(0)) => continue,
Ok(Some(n)) => {
pending.extend_from_slice(&buf[..n]);
let mut at = 0;
let mut newest = None;
while let Some((record, used)) = match PathRecord::decode(&pending[at..]) {
Ok(record) => record,
Err(e) => return violation(ctx, &e.to_string()),
} {
at += used;
newest = Some(record);
}
if let Some(record) = newest {
ctx.remote.store(record, ctx.exec.now());
}
pending.drain(..at);
}
Ok(None) => {
if !pending.is_empty() {
return violation(ctx, "a REPORT record truncated at FIN");
}
return Ok(());
}
Err(e) => {
tracing::debug!(error = %e, "REPORT stream ended");
return Ok(());
}
}
}
}