use std::collections::{HashMap, VecDeque};
use std::hash::Hash;
use std::sync::{Arc, Condvar, Mutex, Weak};
use std::time::{Duration, Instant};
use crate::peer::PeerHandle;
pub const DEFAULT_WINDOW_BYTES: u64 = 64 * 1024 * 1024;
pub const DEFAULT_BACKPRESSURE_TIMEOUT: Duration = Duration::from_secs(30);
pub const DEFAULT_IDLE_TIMEOUT: Duration = Duration::from_secs(60);
pub const DEFAULT_REPLAY_RING_BYTES: u64 = 64 * 1024 * 1024;
pub const DEFAULT_RECONNECT_TIMEOUT: Duration = Duration::from_secs(30);
pub struct TransferControl {
inner: Mutex<TransferControlInner>,
cv: Condvar,
}
struct TransferControlInner {
window_bytes: u64,
sent_offset: u64,
acked_offset: u64,
current_file_index: u32,
cancelled: Option<String>,
last_chunk_at: Instant,
last_ack_at: Instant,
replay: ReplayRing,
peer: Option<PeerHandle>,
pending_resume: Option<PendingResume>,
}
#[derive(Debug, Clone)]
pub struct PendingResume {
pub resume_at_offset: u64,
}
struct ReplayRing {
chunks: VecDeque<RingChunk>,
bytes_held: u64,
capacity_bytes: u64,
}
#[derive(Clone)]
pub struct RingChunk {
pub offset: u64,
pub last: bool,
pub body_bytes: Arc<Vec<u8>>,
}
impl ReplayRing {
fn new(capacity_bytes: u64) -> Self {
Self {
chunks: VecDeque::new(),
bytes_held: 0,
capacity_bytes,
}
}
fn push(&mut self, offset: u64, last: bool, body_bytes: Vec<u8>) {
debug_assert!(
self.chunks.back().is_none_or(|c| offset > c.offset),
"ReplayRing::push: non-monotonic offset {offset} (last was {:?})",
self.chunks.back().map(|c| c.offset),
);
let len = body_bytes.len() as u64;
self.chunks.push_back(RingChunk {
offset,
last,
body_bytes: Arc::new(body_bytes),
});
self.bytes_held = self.bytes_held.saturating_add(len);
while self.bytes_held > self.capacity_bytes && self.chunks.len() > 1 {
if let Some(front) = self.chunks.pop_front() {
self.bytes_held = self
.bytes_held
.saturating_sub(front.body_bytes.len() as u64);
}
}
}
fn clear(&mut self) {
self.chunks.clear();
self.bytes_held = 0;
}
fn highest_end_offset(&self) -> Option<u64> {
self.chunks
.back()
.map(|c| c.offset + c.body_bytes.len() as u64)
}
fn covers(&self, offset: u64) -> bool {
if self.chunks.is_empty() {
return offset == 0;
}
for chunk in &self.chunks {
if chunk.offset == offset {
return true;
}
}
self.highest_end_offset() == Some(offset)
}
fn replay_from(&self, offset: u64) -> Vec<RingChunk> {
self.chunks
.iter()
.filter(|c| c.offset >= offset)
.cloned()
.collect()
}
}
#[derive(Debug)]
pub enum CreditError {
Cancelled(String),
Timeout,
}
impl std::fmt::Display for CreditError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
CreditError::Cancelled(reason) => write!(f, "transfer cancelled: {reason}"),
CreditError::Timeout => write!(f, "credit timeout"),
}
}
}
impl std::error::Error for CreditError {}
#[derive(Debug)]
pub enum ReconnectOutcome {
ResumeReady,
Cancelled(String),
Timeout,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ResumeRejection {
WrongFileIndex { requested: u32, current: u32 },
OutOfWindow,
Cancelled,
}
impl ResumeRejection {
pub fn reason(&self) -> &'static str {
match self {
ResumeRejection::WrongFileIndex { .. } => "wrong_file_index",
ResumeRejection::OutOfWindow => "out_of_window",
ResumeRejection::Cancelled => "transfer_cancelled",
}
}
}
impl TransferControl {
pub fn new(window_bytes: u64) -> Arc<Self> {
Self::with_replay_capacity(window_bytes, DEFAULT_REPLAY_RING_BYTES)
}
pub fn with_replay_capacity(window_bytes: u64, replay_capacity_bytes: u64) -> Arc<Self> {
let now = Instant::now();
Arc::new(Self {
inner: Mutex::new(TransferControlInner {
window_bytes,
sent_offset: 0,
acked_offset: 0,
current_file_index: 0,
cancelled: None,
last_chunk_at: now,
last_ack_at: now,
replay: ReplayRing::new(replay_capacity_bytes),
peer: None,
pending_resume: None,
}),
cv: Condvar::new(),
})
}
pub fn set_peer(&self, peer: PeerHandle) {
let mut g = self.inner.lock().expect("TransferControl mutex poisoned");
g.peer = Some(peer);
}
pub fn peer(&self) -> Option<PeerHandle> {
self.inner
.lock()
.expect("TransferControl mutex poisoned")
.peer
.clone()
}
pub fn push_replay(&self, offset: u64, last: bool, body_bytes: Vec<u8>) {
let mut g = self.inner.lock().expect("TransferControl mutex poisoned");
g.replay.push(offset, last, body_bytes);
}
pub fn replay_chunks_from(&self, offset: u64) -> Vec<RingChunk> {
let g = self.inner.lock().expect("TransferControl mutex poisoned");
g.replay.replay_from(offset)
}
pub fn request_resume(
&self,
new_peer: PeerHandle,
file_index: u32,
last_received_offset: u64,
) -> Result<u64, ResumeRejection> {
let mut g = self.inner.lock().expect("TransferControl mutex poisoned");
if g.cancelled.is_some() {
return Err(ResumeRejection::Cancelled);
}
if file_index != g.current_file_index {
return Err(ResumeRejection::WrongFileIndex {
requested: file_index,
current: g.current_file_index,
});
}
if !g.replay.covers(last_received_offset) {
return Err(ResumeRejection::OutOfWindow);
}
g.peer = Some(new_peer);
g.pending_resume = Some(PendingResume {
resume_at_offset: last_received_offset,
});
let now = Instant::now();
g.last_chunk_at = now;
g.last_ack_at = now;
if last_received_offset > g.acked_offset && last_received_offset <= g.sent_offset {
g.acked_offset = last_received_offset;
}
self.cv.notify_all();
Ok(last_received_offset)
}
pub fn wait_for_reconnect(&self, timeout: Duration) -> ReconnectOutcome {
let deadline = Instant::now() + timeout;
let mut g = self.inner.lock().expect("TransferControl mutex poisoned");
loop {
if let Some(reason) = g.cancelled.clone() {
return ReconnectOutcome::Cancelled(reason);
}
if g.pending_resume.is_some() {
return ReconnectOutcome::ResumeReady;
}
let now = Instant::now();
if now >= deadline {
return ReconnectOutcome::Timeout;
}
let (gg, _) = self
.cv
.wait_timeout(g, deadline - now)
.expect("TransferControl mutex poisoned");
g = gg;
}
}
pub fn take_pending_resume(&self) -> Option<PendingResume> {
self.inner
.lock()
.expect("TransferControl mutex poisoned")
.pending_resume
.take()
}
pub fn wait_for_credit(&self, chunk_len: u64, deadline: Instant) -> Result<(), CreditError> {
let mut guard = self.inner.lock().expect("TransferControl mutex poisoned");
loop {
if let Some(reason) = guard.cancelled.clone() {
return Err(CreditError::Cancelled(reason));
}
let in_flight = guard.sent_offset.saturating_sub(guard.acked_offset);
if in_flight == 0 || in_flight + chunk_len <= guard.window_bytes {
return Ok(());
}
let now = Instant::now();
if now >= deadline {
return Err(CreditError::Timeout);
}
let timeout = deadline - now;
let (g, _) = self
.cv
.wait_timeout(guard, timeout)
.expect("TransferControl mutex poisoned");
guard = g;
}
}
pub fn record_sent(&self, new_offset: u64) {
let mut guard = self.inner.lock().expect("TransferControl mutex poisoned");
if new_offset > guard.sent_offset {
guard.sent_offset = new_offset;
}
guard.last_chunk_at = Instant::now();
}
pub fn record_ack(&self, file_index: u32, received_through_offset: u64) {
let mut guard = self.inner.lock().expect("TransferControl mutex poisoned");
guard.last_ack_at = Instant::now();
if file_index == guard.current_file_index {
let capped = received_through_offset.min(guard.sent_offset);
if capped > guard.acked_offset {
guard.acked_offset = capped;
self.cv.notify_all();
}
}
}
pub fn cancel(&self, reason: impl Into<String>) {
let mut guard = self.inner.lock().expect("TransferControl mutex poisoned");
if guard.cancelled.is_none() {
guard.cancelled = Some(reason.into());
self.cv.notify_all();
}
}
pub fn is_cancelled(&self) -> bool {
self.inner
.lock()
.expect("TransferControl mutex poisoned")
.cancelled
.is_some()
}
pub fn cancel_reason(&self) -> Option<String> {
self.inner
.lock()
.expect("TransferControl mutex poisoned")
.cancelled
.clone()
}
pub fn advance_to_file(&self, next_file_index: u32) {
let mut guard = self.inner.lock().expect("TransferControl mutex poisoned");
guard.current_file_index = next_file_index;
guard.sent_offset = 0;
guard.acked_offset = 0;
guard.replay.clear();
guard.pending_resume = None;
let now = Instant::now();
guard.last_chunk_at = now;
guard.last_ack_at = now;
self.cv.notify_all();
}
pub fn timestamps(&self) -> (Instant, Instant) {
let g = self.inner.lock().expect("TransferControl mutex poisoned");
(g.last_chunk_at, g.last_ack_at)
}
pub fn offsets(&self) -> (u64, u64) {
let g = self.inner.lock().expect("TransferControl mutex poisoned");
(g.sent_offset, g.acked_offset)
}
}
pub struct TransferRegistry<K: Hash + Eq + Copy + Send + Sync + 'static> {
map: Mutex<HashMap<K, Arc<TransferControl>>>,
}
impl<K: Hash + Eq + Copy + Send + Sync + 'static> Default for TransferRegistry<K> {
fn default() -> Self {
Self::new()
}
}
impl<K: Hash + Eq + Copy + Send + Sync + 'static> TransferRegistry<K> {
pub fn new() -> Self {
Self {
map: Mutex::new(HashMap::new()),
}
}
pub fn register(&self, key: K, control: Arc<TransferControl>) {
self.map
.lock()
.expect("TransferRegistry mutex poisoned")
.insert(key, control);
}
pub fn unregister(&self, key: K) -> Option<Arc<TransferControl>> {
self.map
.lock()
.expect("TransferRegistry mutex poisoned")
.remove(&key)
}
pub fn get(&self, key: K) -> Option<Arc<TransferControl>> {
self.map
.lock()
.expect("TransferRegistry mutex poisoned")
.get(&key)
.cloned()
}
pub fn snapshot(&self) -> Vec<(K, Arc<TransferControl>)> {
self.map
.lock()
.expect("TransferRegistry mutex poisoned")
.iter()
.map(|(k, v)| (*k, v.clone()))
.collect()
}
pub fn len(&self) -> usize {
self.map
.lock()
.expect("TransferRegistry mutex poisoned")
.len()
}
pub fn is_empty(&self) -> bool {
self.len() == 0
}
}
pub fn spawn_watchdog<K>(registry: Arc<TransferRegistry<K>>, idle_timeout: Duration)
where
K: Hash + Eq + Copy + Send + Sync + 'static,
{
let weak = Arc::downgrade(®istry);
drop(registry);
std::thread::Builder::new()
.name("repe-stream-watchdog".to_string())
.spawn(move || watchdog_loop(weak, idle_timeout))
.expect("spawn idle-transfer watchdog");
}
fn watchdog_loop<K>(registry: Weak<TransferRegistry<K>>, idle_timeout: Duration)
where
K: Hash + Eq + Copy + Send + Sync + 'static,
{
let tick = (idle_timeout / 4)
.min(Duration::from_secs(5))
.max(Duration::from_secs(1));
loop {
std::thread::sleep(tick);
let Some(registry) = registry.upgrade() else {
return;
};
let snapshot = registry.snapshot();
drop(registry);
let now = Instant::now();
for (_key, control) in snapshot {
if control.is_cancelled() {
continue;
}
let (last_chunk_at, last_ack_at) = control.timestamps();
let last_progress = last_chunk_at.max(last_ack_at);
if now.saturating_duration_since(last_progress) >= idle_timeout {
control.cancel("transfer idle");
}
}
}
}
#[cfg(test)]
mod tests {
use super::*;
fn dummy_peer(id: u64) -> PeerHandle {
use crate::peer::{NotifyBody, PeerId, PeerSendError, PeerSink};
struct Dummy;
impl PeerSink for Dummy {
fn send_notify(
&self,
_method: &str,
_body: NotifyBody,
) -> std::result::Result<(), PeerSendError> {
Ok(())
}
fn is_connected(&self) -> bool {
true
}
}
PeerHandle::new(PeerId(id), Arc::new(Dummy))
}
#[test]
fn wait_returns_immediately_when_window_has_room() {
let ctl = TransferControl::new(1024);
let deadline = Instant::now() + Duration::from_millis(50);
ctl.wait_for_credit(512, deadline).unwrap();
}
#[test]
fn wait_blocks_when_window_full_and_unblocks_on_ack() {
let ctl = TransferControl::new(1024);
ctl.record_sent(1024);
let writer = Arc::clone(&ctl);
let handle = std::thread::spawn(move || {
let deadline = Instant::now() + Duration::from_secs(2);
writer.wait_for_credit(512, deadline)
});
std::thread::sleep(Duration::from_millis(50));
ctl.record_ack(0, 512);
let res = handle.join().expect("writer thread");
res.expect("ack should release credit");
}
#[test]
fn wait_returns_timeout_when_no_ack_arrives() {
let ctl = TransferControl::new(1024);
ctl.record_sent(1024);
let deadline = Instant::now() + Duration::from_millis(80);
let err = ctl.wait_for_credit(512, deadline).unwrap_err();
assert!(matches!(err, CreditError::Timeout), "got {err:?}");
}
#[test]
fn cancel_unblocks_waiters() {
let ctl = TransferControl::new(1024);
ctl.record_sent(1024);
let writer = Arc::clone(&ctl);
let handle = std::thread::spawn(move || {
let deadline = Instant::now() + Duration::from_secs(5);
writer.wait_for_credit(512, deadline)
});
std::thread::sleep(Duration::from_millis(50));
ctl.cancel("client cancelled");
let err = handle.join().unwrap().unwrap_err();
match err {
CreditError::Cancelled(reason) => assert_eq!(reason, "client cancelled"),
other => panic!("expected Cancelled, got {other:?}"),
}
}
#[test]
fn ack_for_wrong_file_index_is_ignored() {
let ctl = TransferControl::new(1024);
ctl.record_sent(800);
ctl.record_ack(7, 600);
let (sent, acked) = ctl.offsets();
assert_eq!(sent, 800);
assert_eq!(acked, 0);
}
#[test]
fn ack_offset_is_capped_to_sent_offset() {
let ctl = TransferControl::new(1024);
ctl.record_sent(400);
ctl.record_ack(0, 999_999);
let (_, acked) = ctl.offsets();
assert_eq!(acked, 400, "ack must not advance past actually-sent bytes");
}
#[test]
fn advance_to_file_resets_offsets() {
let ctl = TransferControl::new(1024);
ctl.record_sent(900);
ctl.record_ack(0, 800);
ctl.advance_to_file(1);
let (sent, acked) = ctl.offsets();
assert_eq!(sent, 0);
assert_eq!(acked, 0);
}
#[test]
fn registry_round_trip() {
#[derive(Hash, Eq, PartialEq, Copy, Clone)]
struct Id(u64);
let reg: TransferRegistry<Id> = TransferRegistry::new();
let ctl = TransferControl::new(1024);
let id = Id(424_242);
reg.register(id, Arc::clone(&ctl));
assert!(reg.get(id).is_some());
let removed = reg.unregister(id).unwrap();
assert!(Arc::ptr_eq(&removed, &ctl));
assert!(reg.get(id).is_none());
}
#[test]
fn oversized_chunk_does_not_deadlock_when_window_is_idle() {
let ctl = TransferControl::new(1024);
let deadline = Instant::now() + Duration::from_millis(50);
ctl.wait_for_credit(8192, deadline).unwrap();
}
#[test]
fn replay_ring_evicts_oldest_when_full() {
let mut ring = ReplayRing::new(100);
ring.push(0, false, vec![0u8; 40]);
ring.push(40, false, vec![0u8; 40]);
assert_eq!(ring.bytes_held, 80);
assert_eq!(ring.chunks.len(), 2);
ring.push(80, false, vec![0u8; 40]);
assert_eq!(ring.bytes_held, 80);
assert_eq!(ring.chunks.len(), 2);
assert_eq!(ring.chunks.front().unwrap().offset, 40);
assert_eq!(ring.chunks.back().unwrap().offset, 80);
}
#[test]
fn replay_ring_keeps_single_oversized_chunk() {
let mut ring = ReplayRing::new(50);
ring.push(0, false, vec![0u8; 200]);
assert_eq!(ring.chunks.len(), 1);
assert_eq!(ring.bytes_held, 200);
}
#[test]
fn replay_ring_covers_offsets() {
let mut ring = ReplayRing::new(1024);
assert!(ring.covers(0));
assert!(!ring.covers(8));
ring.push(0, false, vec![0u8; 16]);
ring.push(16, false, vec![0u8; 16]);
assert!(ring.covers(0));
assert!(ring.covers(16));
assert!(!ring.covers(8));
assert!(ring.covers(32));
assert!(!ring.covers(64));
}
#[test]
fn replay_chunks_from_returns_tail() {
let mut ring = ReplayRing::new(1024);
ring.push(0, false, vec![0xAA; 16]);
ring.push(16, false, vec![0xBB; 16]);
ring.push(32, true, vec![0xCC; 16]);
let from_16 = ring.replay_from(16);
assert_eq!(from_16.len(), 2);
assert_eq!(from_16[0].offset, 16);
assert_eq!(from_16[1].offset, 32);
assert!(from_16[1].last);
}
#[test]
fn request_resume_validates_file_index() {
let ctl = TransferControl::with_replay_capacity(1024, 1024);
ctl.set_peer(dummy_peer(1));
ctl.advance_to_file(2);
ctl.push_replay(0, false, vec![0u8; 16]);
let new_peer = dummy_peer(2);
let err = ctl.request_resume(new_peer, 5, 0).unwrap_err();
match err {
ResumeRejection::WrongFileIndex { requested, current } => {
assert_eq!(requested, 5);
assert_eq!(current, 2);
}
other => panic!("expected WrongFileIndex, got {other:?}"),
}
}
#[test]
fn request_resume_validates_offset_in_ring() {
let ctl = TransferControl::with_replay_capacity(1024, 64);
ctl.set_peer(dummy_peer(1));
ctl.push_replay(0, false, vec![0u8; 32]);
ctl.push_replay(32, false, vec![0u8; 32]);
ctl.push_replay(64, false, vec![0u8; 32]);
let new_peer = dummy_peer(2);
let err = ctl.request_resume(new_peer, 0, 0).unwrap_err();
assert_eq!(err, ResumeRejection::OutOfWindow);
}
#[test]
fn request_resume_signals_writer_via_condvar() {
let ctl = TransferControl::new(1024);
ctl.set_peer(dummy_peer(1));
ctl.push_replay(0, false, vec![0u8; 16]);
let writer_ctl = Arc::clone(&ctl);
let waiter =
std::thread::spawn(move || writer_ctl.wait_for_reconnect(Duration::from_secs(2)));
std::thread::sleep(Duration::from_millis(40));
let new_peer = dummy_peer(2);
ctl.request_resume(new_peer, 0, 0).unwrap();
match waiter.join().unwrap() {
ReconnectOutcome::ResumeReady => {}
other => panic!("expected ResumeReady, got {other:?}"),
}
let pending = ctl.take_pending_resume().expect("resume staged");
assert_eq!(pending.resume_at_offset, 0);
assert!(ctl.take_pending_resume().is_none());
}
#[test]
fn wait_for_reconnect_times_out() {
let ctl = TransferControl::new(1024);
match ctl.wait_for_reconnect(Duration::from_millis(40)) {
ReconnectOutcome::Timeout => {}
other => panic!("expected Timeout, got {other:?}"),
}
}
#[test]
fn wait_for_reconnect_returns_cancelled_when_cancelled() {
let ctl = TransferControl::new(1024);
ctl.cancel("client requested abort");
match ctl.wait_for_reconnect(Duration::from_secs(1)) {
ReconnectOutcome::Cancelled(reason) => {
assert_eq!(reason, "client requested abort")
}
other => panic!("expected Cancelled, got {other:?}"),
}
}
#[test]
fn advance_to_file_clears_replay_ring() {
let ctl = TransferControl::with_replay_capacity(1024, 1024);
ctl.set_peer(dummy_peer(1));
ctl.push_replay(0, false, vec![0u8; 32]);
let before = ctl.replay_chunks_from(0);
assert_eq!(before.len(), 1);
ctl.advance_to_file(1);
let after = ctl.replay_chunks_from(0);
assert!(after.is_empty(), "ring should be empty after file boundary");
}
#[test]
fn watchdog_does_not_keep_registry_alive() {
#[derive(Hash, Eq, PartialEq, Copy, Clone)]
struct Id(u64);
let registry: Arc<TransferRegistry<Id>> = Arc::new(TransferRegistry::new());
let weak = Arc::downgrade(®istry);
spawn_watchdog(Arc::clone(®istry), Duration::from_millis(100));
drop(registry);
std::thread::sleep(Duration::from_millis(1_500));
assert_eq!(
weak.strong_count(),
0,
"watchdog must not extend the registry's lifetime"
);
}
#[test]
fn watchdog_check_logic_matches_spawn_loop() {
let ctl = TransferControl::new(1024);
let idle_timeout = Duration::from_millis(40);
std::thread::sleep(idle_timeout + Duration::from_millis(20));
let (last_chunk_at, last_ack_at) = ctl.timestamps();
let last_progress = last_chunk_at.max(last_ack_at);
let elapsed = Instant::now().saturating_duration_since(last_progress);
assert!(elapsed >= idle_timeout);
ctl.cancel("transfer idle");
match ctl.cancel_reason() {
Some(reason) => assert_eq!(reason, "transfer idle"),
None => panic!("watchdog should have cancelled"),
}
}
}