//! The driver: one future that owns the transport and moves the session's records over it. use std::future::Future; use std::pin::Pin; use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::{Arc, Mutex}; use std::task::{Context, Poll, Wake, Waker}; use std::time::Duration; use bytes::Bytes; use kio::clock::Instant; use moq_quic::TransportError; use crate::Error; use crate::session::{Inner, State}; use crate::transport::Transport; /// How long a closing session keeps the transport open to deliver its close and finish graceful /// shutdown, like QUIC's draining period. A peer that stopped reading or never finishes its send /// half cannot hold the transport open past it. pub(crate) const CLOSE_TIMEOUT: Duration = Duration::from_secs(3); /// The most bytes read, or queued for writing, before the driver turns to the other direction. /// Writes stop sooner at the transport's unsent bound, when it has one. const BATCH_BYTES: usize = 64 * 1024; /// The shortest time between reads of the socket's byte counts, which cost a syscall each. pub(crate) const WIRE_INTERVAL: Duration = Duration::from_millis(250); /// Rounds of reading and writing in one poll before the driver yields to its executor. const ROUNDS: usize = 16; /// Runs a [`Session`](crate::Session) over the transport it owns. /// /// Returned beside the session by every constructor. Spawn it on any executor, such as /// `tokio::spawn`, or a thread-local task set since it needs no `Send` beyond what the /// transport needs. It reads and writes the transport, runs the session's timers, and resolves /// once the session has closed and the transport shut down. Dropping it first ends the session /// with [`Error::Closed`]. #[must_use = "the session makes no progress unless its driver is polled"] pub struct Driver { park: kio::Park, /// Polls the transport's receive side, so it is polled again only once it asks to be. recv: kio::Waiter, recv_wake: Arc, run: Run, } // The transport is only ever borrowed mutably, never pinned. impl Unpin for Driver {} impl Driver { pub(crate) fn new(inner: Arc, transport: T) -> Self { let recv_wake = Arc::new(RecvWake { // Nothing is known about the receive side until it is polled once. woken: AtomicBool::new(true), task: Mutex::new(None), }); let socket = inner.socket_stats.clone(); let mut run = Run { inner, transport, timer: Timer::default(), inbound: Vec::new(), reading: true, unflushed: false, room: true, phase: Phase::Open, wire_read: None, wire_stale: false, socket, batch: BATCH_BYTES, }; run.limit_unsent(); Self { park: kio::Park::default(), recv: kio::Waiter::new(Waker::from(recv_wake.clone())), recv_wake, run, } } } impl Future for Driver { type Output = (); fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<()> { let this = self.get_mut(); this.recv_wake.track(cx.waker()); let waiter = this.park.hold(cx); let recv = Recv { waiter: &this.recv, wake: &this.recv_wake, }; waiter.batch(|| this.run.poll(waiter, &recv)) } } /// Wakes the driver's task for the transport's receive side, and records that it did. /// /// Polling the receive side is not free on every transport: tungstenite zeroes its whole /// read buffer on each attempt, even one that finds nothing. So the driver polls it only /// after it asked to be woken, rather than on every wakeup a write or a handle caused. struct RecvWake { woken: AtomicBool, /// The task that polls the driver. task: Mutex>, } impl RecvWake { /// Wake `waker` from now on. fn track(&self, waker: &Waker) { let mut task = self.task.lock().unwrap(); if !task.as_ref().is_some_and(|task| task.will_wake(waker)) { *task = Some(waker.clone()); } } } impl Wake for RecvWake { fn wake(self: Arc) { self.wake_by_ref(); } fn wake_by_ref(self: &Arc) { self.woken.store(true, Ordering::Release); if let Some(task) = self.task.lock().unwrap().as_ref() { task.wake_by_ref(); } } } /// The receive side's waiter, and whether it was woken. struct Recv<'a> { waiter: &'a kio::Waiter, wake: &'a RecvWake, } impl Recv<'_> { /// Whether the receive side was woken since it was last found pending, clearing it. fn take(&self) -> bool { self.wake.woken.swap(false, Ordering::AcqRel) } /// Poll the receive side again on the next round, since it stopped short of pending. fn again(&self) { self.wake.woken.store(true, Ordering::Release); } } impl Drop for Driver { fn drop(&mut self) { if !matches!(self.run.phase, Phase::Done) { self.run.read_wire(kio::clock::now()); finish(&self.run.inner, Err(Error::Closed)); } // The socket statistics hold a duplicate of the descriptor, which would keep the // connection open past the transport for as long as any session handle lives. if let Some(socket) = &self.run.socket { socket.shutdown(); } } } impl std::fmt::Debug for Driver { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { f.debug_struct("Driver").finish_non_exhaustive() } } enum Phase { /// Moving records both ways. Open, /// The connection ended, by a close from either side; still moving records both ways to /// deliver what it has left to say, until this deadline. Flushing(Instant), /// The connection said everything; closing the transport until this deadline, the same one /// [`Self::Flushing`] had. Closing(Instant), /// The transport is closed and the session's end published. Done, } impl Phase { /// When a closing session gives up, if it is closing. fn deadline(&self) -> Option { match self { Self::Flushing(deadline) | Self::Closing(deadline) => Some(*deadline), Self::Open | Self::Done => None, } } } /// What one round of reading and writing came to. enum Step { /// Did something; go again. Progress, /// Parked on the transport, a handle, or a timer. Idle, /// The connection has nothing left to say and all of it was flushed. Drained, /// The transport failed, or a closing session ran out of time. Failed(Error), } struct Run { inner: Arc, transport: T, timer: Timer, /// Records read but not yet handed to the connection, kept to reuse its allocation. inbound: Vec>, /// The transport's receive side has not ended. reading: bool, /// The last flush did not finish. unflushed: bool, /// The transport took everything and flushed it, so the connection may hand over more. room: bool, phase: Phase, /// When the socket's byte counts were last copied to the session's wire counters. wire_read: Option, /// Records moved since that read, so the counts it holds are behind. wire_stale: bool, /// The connection underneath, which counts its bytes and bounds what it holds unsent. socket: Option, /// The most bytes queued for writing in one step: [`BATCH_BYTES`], or less to stay /// within the socket's unsent bound, since what the transport has taken can no longer be /// dropped. batch: usize, } impl Run { fn poll(&mut self, waiter: &kio::Waiter, recv: &Recv<'_>) -> Poll<()> { let mut rounds = 0; loop { match self.phase { Phase::Done => return Poll::Ready(()), Phase::Closing(deadline) => { // A close that fails or runs out of time still ends the session; the close // frame, if any, is already out. if self.transport.poll_close(waiter).is_pending() && !self.timer.poll(waiter, Some(deadline)) { return Poll::Pending; } self.finish(Ok(())); } Phase::Open | Phase::Flushing(_) => match self.step(waiter, recv) { Step::Progress => { rounds += 1; if rounds == ROUNDS { waiter.waker().wake_by_ref(); return Poll::Pending; } } Step::Idle => return Poll::Pending, Step::Drained => { // Drained means closed, so `step` already started the close bound. let deadline = self .phase .deadline() .unwrap_or_else(|| kio::clock::now().saturating_add(CLOSE_TIMEOUT)); self.phase = Phase::Closing(deadline); } Step::Failed(err) => self.finish(Err(err)), }, } } } /// Read a batch into the connection, write a batch out of it, and flush. fn step(&mut self, waiter: &kio::Waiter, recv: &Recv<'_>) -> Step { // Whether this step polled the receive side, and whether it stopped short of pending. let polled = self.reading && recv.take(); let mut more_to_read = false; if polled { let mut read = 0; loop { if read >= BATCH_BYTES { recv.again(); more_to_read = true; break; } match self.transport.poll_recv(recv.waiter) { Poll::Ready(Ok(record)) => { read += record.len().max(1); self.inbound.push(Ok(record)); } Poll::Ready(Err(err)) => { self.reading = false; self.inbound.push(Err(err)); break; } Poll::Pending => break, } } } let now = kio::clock::now(); let mut state = self.inner.lock(); let mut received = false; for record in self.inbound.drain(..) { received |= record.is_ok(); deliver(&mut state, record, now); // Publish what this record did before the next one: a close followed by the // transport ending must report the close. state.check_lost(); } if state.conn.poll_timeout().is_some_and(|at| now >= at) { state.conn.handle_timeout(now); } // Hand records to the transport outside the lock: it copies each one, and tungstenite // may write to the socket, while the handles on other threads wait. drop(state); // Take a record from the connection only once the transport is ready for it, so a // stalled transport leaves unreliable datagrams in the connection to be shed, and report // each one the transport took, which delivers its stream data. With nothing to send, // `poll_transmit` parks us until a handle queues something. let mut written = 0; let mut blocked = false; while self.room && written < self.batch { match self.transport.poll_ready(waiter) { Poll::Ready(Ok(())) => {} Poll::Ready(Err(err)) => return Step::Failed(err), Poll::Pending => { blocked = true; break; } } let Poll::Ready(record) = self.inner.lock().conn.poll_transmit(waiter, now) else { break; }; written += record.len(); if let Err(err) = self.transport.send(record) { return Step::Failed(err); } self.inner.lock().conn.transmitted(); } let mut state = self.inner.lock(); // A close, local or not, starts the close bound, even while the transport holds what // the connection has to send. `poll_transmit` would take records the transport has no // room for, so wait for the close with `poll_closed`; the transport wakes us for room. let _ = state.conn.poll_closed(waiter); state.check_lost(); if state.conn.is_closed() && matches!(self.phase, Phase::Open) { self.phase = Phase::Flushing(now.saturating_add(CLOSE_TIMEOUT)); } let drained = state.conn.is_drained(); let deadline = state.conn.poll_timeout(); let credit = state.conn.send_credit_stats(); let held = state.conn.credit_stats().held; drop(state); self.inner.wire.set_credit_stalls(credit.stalls, credit.stalled); self.inner.wire.set_credit_held(held.readers, held.evicted); // Flush what this step queued, what an earlier flush left, and what the transport may // have queued on its own while receiving, such as a WebSocket Pong. Skipping it // otherwise matters: a flush through TLS and tungstenite is not free. let flushed = match written > 0 || blocked || self.unflushed || polled { true => match self.transport.poll_flush(waiter) { Poll::Ready(Ok(())) => true, Poll::Ready(Err(err)) => return Step::Failed(err), Poll::Pending => false, }, false => true, }; self.unflushed = !flushed; // Count only what reached the socket: the transport may hold records until its flush // finishes, which then steps the driver again to publish them. let moved = written > 0 || received; let wire_due = match flushed { true => self.publish_wire(now, moved), false => { self.wire_stale |= moved; None } }; if blocked || !flushed { // The window may have moved since the socket's bound was last set. Setting it // before parking lets a raised bound wake the flush that just went pending sooner. self.limit_unsent(); } let had_room = std::mem::replace(&mut self.room, flushed && !blocked); self.set_stalled(!self.room); if drained && self.room { return Step::Drained; } let closing = self.phase.deadline(); if closing.is_some_and(|at| now >= at) { // The close never got through a stalled transport. return Step::Failed(Error::Closed); } // Each step already wrote what the records it read made the connection say, so go again // only when a batch cut a direction short, or the transport has room again for what the // connection held back meanwhile. if more_to_read || (self.room && (written >= self.batch || !had_room)) { return Step::Progress; } let deadline = [deadline, closing, wire_due].into_iter().flatten().min(); match self.timer.poll(waiter, deadline) { true => Step::Progress, false => Step::Idle, } } /// Bound the socket's unsent bytes to its congestion window, and each batch to match. fn limit_unsent(&mut self) { if let Some(bound) = self.socket.as_ref().and_then(|socket| socket.limit_unsent()) { self.batch = bound.clamp(1, BATCH_BYTES); } } /// Copy the socket's byte counts to the session's wire counters, at most once per /// [`WIRE_INTERVAL`] since reading them is a syscall. Returns when the next read is due if /// records moved since the last one: the driver wakes then even if nothing else would, so /// the last bytes of a burst are counted and an idle connection runs no timer. fn publish_wire(&mut self, now: Instant, moved: bool) -> Option { self.socket.as_ref()?; self.wire_stale |= moved; if !self.wire_stale { return None; } let due = self.wire_read.map(|at| at.saturating_add(WIRE_INTERVAL)); if let Some(due) = due.filter(|due| now < *due) { return Some(due); } self.read_wire(now); None } /// Track whether writes are stalled on the transport. The peer is evidently there but slow, /// which defers the idle timeout. fn set_stalled(&mut self, stalled: bool) { if self.timer.stalled != stalled { self.timer.stalled = stalled; self.inner.lock().conn.set_backpressured(stalled); } } fn finish(&mut self, result: Result<(), Error>) { self.phase = Phase::Done; // The last count, which the stats keep after the session closes. self.read_wire(kio::clock::now()); finish(&self.inner, result); } } impl Run { /// Copy the socket's byte counts to the session's wire counters now. fn read_wire(&mut self, now: Instant) { self.wire_read = Some(now); self.wire_stale = false; if let Some(bytes) = self.socket.as_ref().and_then(|socket| socket.bytes()) { self.inner.wire.set_sent_bytes(bytes.sent); self.inner.wire.set_received_bytes(bytes.received); } } } /// Feed one received record, or the transport's error, into the connection. fn deliver(state: &mut State, record: Result, now: Instant) { let err = match record { Ok(record) => return state.conn.handle_record(record, now), Err(err) => err, }; match err.close_code() { // The peer broke the transport's framing: tell it with a CONNECTION_CLOSE. Some(code) => state.conn.handle_violation(TransportError::new(code, err.to_string())), None => { // The transport's own error says more than the connection's reset, unless this side // is closing, when the peer hanging up is the expected answer and the driver // publishes the close it asked for. if !state.closing() { state.fail(err); } state.conn.transport_closed(); } } } /// The transport is done: publish a local close, or the failure that ended it. fn finish(inner: &Inner, result: Result<(), Error>) { let mut state = inner.lock(); // A close from either side comes first: the driver is done delivering it. state.publish(); if let Err(err) = result { state.fail(err); } // Otherwise the transport died under a live connection, which this ends. state.conn.transport_closed(); state.publish(); } /// The driver's timer. #[derive(Default)] struct Timer { sleep: Option, /// Writes are stalled on the transport. stalled: bool, } impl Timer { /// Wait for `deadline`, returning whether it already passed. fn poll(&mut self, waiter: &kio::Waiter, deadline: Option) -> bool { let Some(deadline) = deadline else { return false; }; if kio::clock::now() >= deadline { return true; } let sleep = match &mut self.sleep { Some(sleep) => { if sleep.deadline() != deadline { sleep.reset(deadline); } sleep } None => self.sleep.insert(kio::clock::sleep_until(deadline)), }; waiter.poll_future(Pin::new(sleep)).is_ready() } }