Skip to main content

moq_net/
transport.rs

1//! The poll transport interface owned by `moq-net`.
2//!
3//! Implement these traits for a transport, or wrap a backend at the application
4//! boundary. `moq-tokio` and `moq-uring` provide their own adapters, and
5//! [`memory`] links two peers in one process.
6//! The async helpers only drive the required poll methods. Sessions take a
7//! [`poll::Boxable`] transport, which adds thread bounds; wrap a thread-local
8//! transport in a type that checks the thread on use (`moq-uring` has one).
9
10use std::time::Duration;
11
12#[cfg(feature = "async")]
13pub(crate) mod boxed;
14pub mod memory;
15#[cfg(feature = "async")]
16pub(crate) mod open;
17
18/// Where a session's request target travels.
19#[derive(Clone, Copy, Debug, Eq, PartialEq)]
20pub enum Address {
21	/// The transport's own request URI carries it (WebTransport, qmux over WebSocket).
22	Uri,
23	/// The MoQ SETUP carries it, because the transport has no request URI.
24	Setup,
25}
26
27/// One connection's cumulative wire counters, which its transport updates as it sends and receives:
28/// its bytes, its sender's losses and waits on the congestion controller and on the peer's
29/// connection-level credit, and its receiver's holds on a spent receive window.
30///
31/// Clones share the counters, so stats read them without polling the session or keeping the
32/// connection alive, and the final totals stay readable after it closes. Each counter is
33/// independent: a transport records the ones it tracks, and the rest stay zero.
34///
35/// A transport whose counts live outside it, such as a TCP socket's in the kernel, builds its
36/// counters with [`Wire::from_source`] instead of pushing them as it carries traffic.
37#[derive(Clone, Debug, Default)]
38pub struct Wire(std::sync::Arc<WireCounters>);
39
40/// Reads a connection's counters on demand, for a transport that cannot cheaply push them as
41/// it sends and receives, such as a TCP socket whose kernel counts its bytes.
42///
43/// Stats call it on every report and once more when the connection's stats end, so the
44/// counters are current whenever stats read them, and an idle connection needs no timer.
45/// Anyone else reading a sourced [`Wire`] sees the counts as of the last stats read.
46pub trait WireSource: Send + Sync + 'static {
47	/// Copy the counts this source tracks into `wire`, leaving the rest as they are.
48	///
49	/// Never keep a clone of `wire`: it owns this source, so the pair would never drop.
50	fn refresh(&self, wire: &Wire);
51}
52
53#[derive(Default)]
54struct WireCounters {
55	/// Dropped with the last clone of the counters, so a source must not hold its connection
56	/// open past the connection's own end.
57	source: Option<Box<dyn WireSource>>,
58	sent_bytes: std::sync::atomic::AtomicU64,
59	received_bytes: std::sync::atomic::AtomicU64,
60	credit_stalls: std::sync::atomic::AtomicU64,
61	credit_stalled_us: std::sync::atomic::AtomicU64,
62	credit_held_readers_us: std::sync::atomic::AtomicU64,
63	credit_held_evicted_us: std::sync::atomic::AtomicU64,
64	lost_bytes: std::sync::atomic::AtomicU64,
65	cwnd_blocked_us: std::sync::atomic::AtomicU64,
66	pacing_blocked_us: std::sync::atomic::AtomicU64,
67}
68
69/// A duration in whole microseconds, saturating.
70pub(crate) fn micros(time: Duration) -> u64 {
71	u64::try_from(time.as_micros()).unwrap_or(u64::MAX)
72}
73
74impl std::fmt::Debug for WireCounters {
75	fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
76		f.debug_struct("WireCounters")
77			.field("sourced", &self.source.is_some())
78			.field("sent_bytes", &self.sent_bytes)
79			.field("received_bytes", &self.received_bytes)
80			.finish_non_exhaustive()
81	}
82}
83
84impl Wire {
85	/// Create counters that start at zero.
86	pub fn new() -> Self {
87		Self::default()
88	}
89
90	/// Create counters that start at zero and that `source` refreshes whenever stats read them.
91	pub fn from_source(source: impl WireSource) -> Self {
92		Self(std::sync::Arc::new(WireCounters {
93			source: Some(Box::new(source)),
94			..Default::default()
95		}))
96	}
97
98	/// Copy the source's counts in, if these counters have one.
99	pub(crate) fn refresh(&self) {
100		if let Some(source) = &self.0.source {
101			source.refresh(self);
102		}
103	}
104
105	/// The bytes sent so far, including transport framing and retransmissions.
106	pub fn sent_bytes(&self) -> u64 {
107		self.0.sent_bytes.load(std::sync::atomic::Ordering::Relaxed)
108	}
109
110	/// The bytes received so far, including transport framing.
111	pub fn received_bytes(&self) -> u64 {
112		self.0.received_bytes.load(std::sync::atomic::Ordering::Relaxed)
113	}
114
115	/// Record the cumulative bytes sent so far.
116	pub fn set_sent_bytes(&self, total: u64) {
117		self.0.sent_bytes.store(total, std::sync::atomic::Ordering::Relaxed);
118	}
119
120	/// Record the cumulative bytes received so far.
121	pub fn set_received_bytes(&self, total: u64) {
122		self.0.received_bytes.store(total, std::sync::atomic::Ordering::Relaxed);
123	}
124
125	/// The sent bytes declared lost so far, part of [`Self::sent_bytes`].
126	pub fn lost_bytes(&self) -> u64 {
127		self.0.lost_bytes.load(std::sync::atomic::Ordering::Relaxed)
128	}
129
130	/// Record the cumulative sent bytes declared lost so far.
131	pub fn set_lost_bytes(&self, total: u64) {
132		self.0.lost_bytes.store(total, std::sync::atomic::Ordering::Relaxed);
133	}
134
135	/// How long data ready to send waited on a full congestion window.
136	pub fn cwnd_blocked(&self) -> Duration {
137		Duration::from_micros(self.0.cwnd_blocked_us.load(std::sync::atomic::Ordering::Relaxed))
138	}
139
140	/// How long data ready to send waited on the pacer.
141	pub fn pacing_blocked(&self) -> Duration {
142		Duration::from_micros(self.0.pacing_blocked_us.load(std::sync::atomic::Ordering::Relaxed))
143	}
144
145	/// Record the cumulative time data ready to send waited on the congestion controller: on a
146	/// full `cwnd`, or on the `pacing` that spreads sends at its rate.
147	pub fn set_congestion_blocked(&self, cwnd: Duration, pacing: Duration) {
148		self.0
149			.cwnd_blocked_us
150			.store(micros(cwnd), std::sync::atomic::Ordering::Relaxed);
151		self.0
152			.pacing_blocked_us
153			.store(micros(pacing), std::sync::atomic::Ordering::Relaxed);
154	}
155
156	/// How many times the sender blocked with all the peer's connection credit (`MAX_DATA`) spent.
157	pub fn credit_stalls(&self) -> u64 {
158		self.0.credit_stalls.load(std::sync::atomic::Ordering::Relaxed)
159	}
160
161	/// How long the sender spent blocked on the peer's connection credit.
162	pub fn credit_stalled(&self) -> Duration {
163		Duration::from_micros(self.0.credit_stalled_us.load(std::sync::atomic::Ordering::Relaxed))
164	}
165
166	/// Record the cumulative episodes and time the sender spent blocked on the peer's connection
167	/// credit. An episode starts when a write blocks with every credited byte sent, and ends when
168	/// the peer grants more; a write held by the local send window is not one.
169	pub fn set_credit_stalls(&self, stalls: u64, stalled: Duration) {
170		self.0.credit_stalls.store(stalls, std::sync::atomic::Ordering::Relaxed);
171		self.0
172			.credit_stalled_us
173			.store(micros(stalled), std::sync::atomic::Ordering::Relaxed);
174	}
175
176	/// How long the peer had this side's whole receive window spent while a reader had data it
177	/// had not looked at yet: a reader behind holding the window.
178	pub fn credit_held_readers(&self) -> Duration {
179		Duration::from_micros(self.0.credit_held_readers_us.load(std::sync::atomic::Ordering::Relaxed))
180	}
181
182	/// How long the peer had this side's whole receive window spent while an evicted reader had
183	/// not stopped its stream.
184	pub fn credit_held_evicted(&self) -> Duration {
185		Duration::from_micros(self.0.credit_held_evicted_us.load(std::sync::atomic::Ordering::Relaxed))
186	}
187
188	/// Record the cumulative time the peer had the whole receive window spent while eviction
189	/// waited on `readers` behind or on `evicted` readers yet to stop their streams.
190	pub fn set_credit_held(&self, readers: Duration, evicted: Duration) {
191		self.0
192			.credit_held_readers_us
193			.store(micros(readers), std::sync::atomic::Ordering::Relaxed);
194		self.0
195			.credit_held_evicted_us
196			.store(micros(evicted), std::sync::atomic::Ordering::Relaxed);
197	}
198}
199
200/// The rate a transport's sender probes up to, which the session sets and the transport reads.
201///
202/// A sender raises the congestion estimate while the connection is app-limited below
203/// this target, so a rate the session wants to send can be funded once the path has room.
204/// The session writes its [`Allocator`](crate::bandwidth::Allocator)'s target here, the
205/// reservations' ceilings summed unless overridden; the transport reads it whenever it
206/// decides how to fill its pacing.
207/// Probing to it is local, so it never reaches the wire.
208///
209/// Clones share one value, which starts at zero: nothing to probe for.
210#[derive(Clone, Debug, Default)]
211pub struct Probe(std::sync::Arc<std::sync::atomic::AtomicU64>);
212
213impl Probe {
214	/// Create a target of zero.
215	pub fn new() -> Self {
216		Self::default()
217	}
218
219	/// The rate to probe up to; zero means don't probe.
220	pub fn target(&self) -> crate::bandwidth::Rate {
221		crate::bandwidth::Rate::from_bps(self.0.load(std::sync::atomic::Ordering::Relaxed))
222	}
223
224	/// Set the rate to probe up to.
225	pub fn set_target(&self, rate: crate::bandwidth::Rate) {
226		self.0.store(rate.as_bps(), std::sync::atomic::Ordering::Relaxed);
227	}
228}
229
230/// Connection-level metrics a transport reports, beyond the byte counts its [`Wire`] holds.
231///
232/// Methods return `Option`: `None` means the implementation doesn't track
233/// this metric, while `Some(0)` means actually zero.
234pub trait Metrics {
235	/// Total bytes lost (detected via retransmission or acknowledgement).
236	fn bytes_lost(&self) -> Option<u64> {
237		None
238	}
239
240	/// Total number of datagrams sent.
241	fn packets_sent(&self) -> Option<u64> {
242		None
243	}
244
245	/// Total number of datagrams received.
246	fn packets_received(&self) -> Option<u64> {
247		None
248	}
249
250	/// Total number of datagrams detected as lost.
251	fn packets_lost(&self) -> Option<u64> {
252		None
253	}
254
255	/// Smoothed round-trip time estimate.
256	fn rtt(&self) -> Option<Duration> {
257		None
258	}
259
260	/// Estimated available send bandwidth, in bits per second.
261	fn estimated_send_rate(&self) -> Option<u64> {
262		None
263	}
264
265	/// Total receive streams evicted because incomplete messages exhausted the receive window.
266	fn streams_evicted(&self) -> Option<u64> {
267		None
268	}
269}
270
271/// The metrics of a transport that tracks none.
272struct Untracked;
273impl Metrics for Untracked {}
274
275/// The receive credit a transport grants its peer, which bounds what a stream the session
276/// stops reading still holds.
277///
278/// A session's ingest stops reading a group's stream while the group's fastest reader is far
279/// behind, so flow control pushes back to the publisher. Such a paused stream holds the
280/// connection credit it was granted, counted against the shared `connection` window, so the
281/// session pauses only as many streams as fit in half of it; the rest keep reading. A
282/// transport that shapes a stream's credit ([`poll::RecvStream::set_window`]) holds a paused
283/// one to a small allowance, which shrinks with each stream the session shapes yet sums to
284/// under that half however many there are, so every one pauses; any other holds its `stream`
285/// window. See [`poll::Session::receive_window`].
286#[derive(Clone, Copy, Debug, PartialEq, Eq)]
287#[non_exhaustive]
288pub struct ReceiveWindow {
289	/// The connection-wide receive window, in bytes, or `None` when streams share none.
290	pub connection: Option<std::num::NonZeroU64>,
291	/// The most receive credit one stream may hold, in bytes.
292	pub stream: u64,
293}
294
295impl ReceiveWindow {
296	/// A connection-wide window of `connection` bytes, if any, of which one stream holds at
297	/// most `stream`.
298	pub fn new(connection: Option<std::num::NonZeroU64>, stream: u64) -> Self {
299		Self { connection, stream }
300	}
301}
302
303/// Limits to change on a live session with [`poll::Session::set_limits`]. Each `None` leaves
304/// its limit as it is.
305#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
306#[non_exhaustive]
307pub struct Limits {
308	/// The connection-wide receive window, in bytes.
309	pub receive_window: Option<std::num::NonZeroU64>,
310}
311
312/// Why a transport did not apply [`Limits`].
313#[derive(Clone, Debug, PartialEq, Eq, thiserror::Error)]
314#[non_exhaustive]
315pub enum LimitsError {
316	/// The transport cannot change these limits on a live session.
317	#[error("the transport cannot change these limits")]
318	Unsupported,
319	/// The transport refused the values, with its reason.
320	#[error("limits refused: {0}")]
321	Refused(String),
322}
323
324/// How long a session may go without hearing from its peer: [`Stale`](Liveness::Stale) after
325/// `soft`, closed as [`Error::IdleTimeout`](crate::Error::IdleTimeout) after `hard`.
326///
327/// The transport probes a peer that stays quiet for half of `soft`, and any packet the peer
328/// sends counts as hearing it, so a busy session pays nothing. Set it with
329/// `Client::with_keep_alive` or `Server::with_keep_alive`, and watch `Session::liveness`.
330/// Native QUIC and qmux (draft-01 and newer) can probe; any other transport refuses it when the
331/// session opens, as does a `hard` longer than the transport's idle timeout, which stays in
332/// force as a backstop.
333#[derive(Clone, Copy, Debug, PartialEq, Eq)]
334#[non_exhaustive]
335pub struct KeepAlive {
336	/// How long the peer may go unheard before it counts as stale.
337	pub soft: std::time::Duration,
338	/// How long the peer may go unheard before the session closes.
339	pub hard: std::time::Duration,
340}
341
342impl KeepAlive {
343	/// Stale after `soft` unheard, closed after `hard`.
344	pub fn new(soft: std::time::Duration, hard: std::time::Duration) -> Self {
345		Self { soft, hard }
346	}
347}
348
349/// Whether a session heard from its peer within its [`KeepAlive`]'s `soft` limit.
350///
351/// Evidence about the whole session, never one track: a quiet track on a live session stays
352/// live.
353#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
354#[non_exhaustive]
355pub enum Liveness {
356	/// The peer was heard within `soft`.
357	#[default]
358	Live,
359	/// `soft` passed without hearing from the peer; the session closes if `hard` does too.
360	Stale,
361}
362
363/// Why a transport refused a [`KeepAlive`].
364#[derive(Clone, Debug, PartialEq, Eq, thiserror::Error)]
365#[non_exhaustive]
366pub enum KeepAliveError {
367	/// The transport cannot probe its peer, such as browser WebTransport or qmux draft-00.
368	#[error("the transport cannot probe its peer")]
369	Unsupported,
370	/// The transport refused the values, with its reason, such as a hard limit past its idle
371	/// timeout.
372	#[error("keep-alive refused: {0}")]
373	Refused(String),
374}
375
376/// The smallest connection receive window a transport that leases may offer: one 1 MiB
377/// storage segment.
378///
379/// A session keeps each unit it is still assembling leased, and a unit larger than the
380/// window can never complete, so the window has to fit the largest one with its framing.
381/// A frame returns its credit a segment at a time, so its size never matters here, and a
382/// legacy announcement set is capped to fit the same segment.
383pub const MIN_RECEIVE_WINDOW: u64 = {
384	// A type and a size prefix, each a varint of at most 8 bytes.
385	const PREFIXES: u64 = 16;
386	let message = <crate::lite::AnnounceInit as crate::lite::Message>::MAX_SIZE as u64 + PREFIXES;
387	let segment = crate::frame::SEGMENT as u64;
388	if message > segment { message } else { segment }
389};
390
391/// The connection receive window a server offers before it admits the session.
392///
393/// It fits the SETUP and one in-band AUTH, each with its framing, which is all a client
394/// sends before the reply. Credit cannot be withdrawn, so a session that started with
395/// its full window could bank it and spend it after a lower window or a bitrate cap
396/// arrives; the server opens the full window only once it admits the session.
397pub const SETUP_RECEIVE_WINDOW: u64 = {
398	// A type and a size prefix, each a varint of at most 8 bytes.
399	const PREFIXES: u64 = 16;
400	let setup = crate::setup::MAX_SETUP_SIZE as u64 + PREFIXES;
401	let auth = <crate::lite::Auth as crate::lite::Message>::MAX_SIZE as u64 + PREFIXES;
402	setup + auth
403};
404
405/// The typed transport condition when no application code was received.
406#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
407#[non_exhaustive]
408pub enum CloseKind {
409	/// The transport failed without a more specific classification.
410	#[default]
411	Transport,
412	/// The connection reached its idle deadline.
413	IdleTimeout,
414	/// This endpoint closed the connection locally.
415	Closed,
416	/// The transport evicted this stream: incomplete messages had spent the receive window,
417	/// and this stream ranked lowest.
418	Evicted,
419}
420
421/// A transport failure with optional session and stream application codes.
422///
423/// Session codes and stream codes belong to separate registries.
424pub trait Error: std::error::Error + Send + Sync + 'static {
425	/// The typed transport condition, independent of application close codes.
426	fn close_kind(&self) -> CloseKind {
427		CloseKind::Transport
428	}
429	/// Returns the error code and reason if this was an application error.
430	///
431	/// Close reasons are exposed as UTF-8 strings at the transport boundary.
432	fn session_error(&self) -> Option<(u32, String)>;
433
434	/// Returns the error code if this was a stream error.
435	fn stream_error(&self) -> Option<u32> {
436		None
437	}
438}
439
440/// Poll operations and their async helpers.
441pub mod poll {
442	/// The outgoing and incoming halves of a bidirectional stream.
443	pub type BiStreams<S> = (<S as Session>::SendStream, <S as Session>::RecvStream);
444	use std::task::{Context, Poll, ready};
445
446	use std::collections::VecDeque;
447
448	use super::{Error, Metrics, Untracked};
449	use bytes::{Buf, Bytes, BytesMut};
450
451	/// A transport session, shared by reference between the tasks that use it.
452	///
453	/// Every session operation takes `&self` and keeps no per-caller progress between polls: the
454	/// caller owns the [`kio::Waiter`] it parks, so an abandoned wait leaves nothing behind.
455	/// Share a session with [`Arc`](std::sync::Arc) rather than cloning it. Poll operations
456	/// never borrow caller buffers between calls, and shared resources must not be held
457	/// across a wait. Implementations register the supplied waiter before Pending.
458	pub trait Session: 'static {
459		/// The outgoing stream type.
460		type SendStream: SendStream;
461
462		/// The incoming stream type.
463		type RecvStream: RecvStream;
464
465		/// The error type for every operation on this session.
466		type Error: Error;
467
468		/// Poll for a unidirectional stream created by the peer.
469		fn poll_accept_uni(&self, waiter: &kio::Waiter) -> Poll<Result<Self::RecvStream, Self::Error>>;
470
471		/// Poll for a bidirectional stream created by the peer.
472		fn poll_accept_bi(&self, waiter: &kio::Waiter) -> Poll<Result<BiStreams<Self>, Self::Error>>;
473
474		/// Poll to open a unidirectional stream scheduled by `options`, which blocks while
475		/// there are too many concurrent streams.
476		fn poll_open_uni(
477			&self,
478			waiter: &kio::Waiter,
479			options: SendOptions<'_, <Self::SendStream as SendStream>::Group>,
480		) -> Poll<Result<Self::SendStream, Self::Error>>;
481
482		/// Poll to open a bidirectional stream, its sending half scheduled by `options`, which
483		/// blocks while there are too many concurrent streams.
484		fn poll_open_bi(
485			&self,
486			waiter: &kio::Waiter,
487			options: SendOptions<'_, <Self::SendStream as SendStream>::Group>,
488		) -> Poll<Result<BiStreams<Self>, Self::Error>>;
489
490		/// Open a send group at `priority`, or `None` when the transport orders streams by
491		/// their own priority alone.
492		///
493		/// Streams that join a group, through [`SendOptions`] or [`SendStream::set_group`], and
494		/// datagrams sent in it share bytes with the session's
495		/// other groups: a higher priority group preempts every lower one, and groups of equal
496		/// priority get an equal share of bytes however many streams each has queued. Streams
497		/// outside every group go before all of them. The group is released once its last
498		/// handle is dropped and its streams finish.
499		fn send_group(&self, priority: i64) -> Option<<Self::SendStream as SendStream>::Group>;
500
501		/// Send a datagram scheduled by `options`, best-effort.
502		///
503		/// The datagram is ranked among its group's streams by its priority, like a stream's
504		/// own [priority](SendStream::set_priority), and goes ahead of a stream of equal
505		/// priority. Without a group it is ranked among the ungrouped streams. A transport that
506		/// cannot rank datagrams against streams ignores `options`.
507		///
508		/// Never blocks: a transport with no room drops a queued datagram, the lowest priority
509		/// first where it can tell, exactly as the network is allowed to.
510		///
511		/// Accepting a datagram is not delivery. QUIC datagrams may still be dropped:
512		/// - Network congestion.
513		/// - Random packet loss.
514		/// - Payload is larger than `max_datagram_size()`
515		/// - Peer is not receiving datagrams.
516		fn send_datagram(
517			&self,
518			payload: Bytes,
519			options: SendOptions<'_, <Self::SendStream as SendStream>::Group>,
520		) -> Result<(), Self::Error>;
521
522		/// Poll for a datagram from the network.
523		fn poll_recv_datagram(&self, waiter: &kio::Waiter) -> Poll<Result<Bytes, Self::Error>>;
524
525		/// The maximum size of a datagram that can be sent.
526		fn max_datagram_size(&self) -> usize;
527
528		/// Return the application protocol negotiated for this session, if any.
529		///
530		/// For WebTransport over HTTP/3 this is the selected WebTransport subprotocol;
531		/// for raw QUIC it is the negotiated ALPN. Return `None` if the transport does
532		/// not negotiate either or the ALPN is not valid UTF-8. This is required rather
533		/// than defaulted: a transport that negotiates an application protocol and
534		/// forgets to report it is a silent bug, and the default hid that.
535		fn protocol(&self) -> Option<&str>;
536
537		/// Return where this transport carries the request target.
538		fn address(&self) -> super::Address;
539
540		/// Close the connection immediately with a code and reason.
541		///
542		/// Idempotent, and deliberately infallible: closing an already-closed connection
543		/// achieved what the caller asked for, and there is nothing they could do with an
544		/// error.
545		fn close(&self, code: u32, reason: &str);
546
547		/// Poll until the connection is closed by either side.
548		fn poll_closed(&self, waiter: &kio::Waiter) -> Poll<Self::Error>;
549
550		/// Return connection-level metrics; by default, none are tracked.
551		fn metrics(&self) -> impl Metrics {
552			Untracked
553		}
554
555		/// Return the wire counters this transport updates, or `None` when it tracks none.
556		fn wire(&self) -> Option<super::Wire> {
557			None
558		}
559
560		/// Return the target this transport's sender probes up to, or `None` when it has no sender.
561		///
562		/// The session sets the target; see [`super::Probe`]. Without a sender nothing probes,
563		/// so the congestion estimate stops rising while the connection is app-limited.
564		fn probe(&self) -> Option<super::Probe> {
565			None
566		}
567
568		/// Return the receive windows now in force, or `None` when the transport cannot say.
569		///
570		/// Read whenever the session considers pausing a stream, so a window changed on a live
571		/// connection is followed. Without one, the session cannot bound the credit a paused
572		/// stream holds, so it never pauses one: ingest reads every stream as it arrives and
573		/// sheds what its readers fall behind on.
574		fn receive_window(&self) -> Option<super::ReceiveWindow> {
575			None
576		}
577
578		/// Whether [`SendStream::reset_at`] still delivers its prefix to the peer's reader, such as
579		/// over raw QUIC with RESET_STREAM_AT negotiated, but never over WebTransport, whose browser
580		/// API may discard it anyway. A plain RESET_STREAM lets the peer discard bytes it has not
581		/// read, even acknowledged ones, so the default is `false`.
582		fn reliable_reset(&self) -> bool {
583			false
584		}
585
586		/// Apply `limits` to the live session, such as to open the receive window a server held
587		/// back until it admitted the peer.
588		///
589		/// Errors with [`LimitsError::Unsupported`](super::LimitsError::Unsupported) when the
590		/// transport cannot change them, which is the default: such a transport holds nothing
591		/// back to open.
592		fn set_limits(&self, limits: super::Limits) -> Result<(), super::LimitsError> {
593			let _ = limits;
594			Err(super::LimitsError::Unsupported)
595		}
596
597		/// Start `keep_alive`: probe the peer once half of its `soft` passes unheard, report it
598		/// [`Stale`](super::Liveness::Stale) through [`poll_liveness`](Self::poll_liveness)
599		/// once all of `soft` does, and close as an idle timeout once `hard` does. Any packet the
600		/// peer sends counts as hearing it, so a busy session sends no probe. A peer already
601		/// unheard for `soft` when this is called is reported stale at once.
602		///
603		/// Errors with [`KeepAliveError::Unsupported`](super::KeepAliveError::Unsupported) when
604		/// the transport cannot probe its peer, which is the default, so the option never passes
605		/// silently.
606		fn set_keep_alive(&self, keep_alive: super::KeepAlive) -> Result<(), super::KeepAliveError> {
607			let _ = keep_alive;
608			Err(super::KeepAliveError::Unsupported)
609		}
610
611		/// Poll until the peer's liveness differs from `last`, returning it. Pending forever
612		/// without a keep-alive.
613		fn poll_liveness(&self, waiter: &kio::Waiter, last: super::Liveness) -> Poll<super::Liveness> {
614			let _ = (waiter, last);
615			Poll::Pending
616		}
617
618		/// Accept the next unidirectional stream opened by the peer.
619		fn accept_uni(&self) -> AcceptUni<'_, Self> {
620			AcceptUni::new(self)
621		}
622
623		/// Accept the next bidirectional stream opened by the peer.
624		fn accept_bi(&self) -> AcceptBi<'_, Self> {
625			AcceptBi::new(self)
626		}
627
628		/// Open a unidirectional stream scheduled by `options`, waiting for stream credit if
629		/// necessary.
630		fn open_uni<'a>(
631			&'a self,
632			options: SendOptions<'a, <Self::SendStream as SendStream>::Group>,
633		) -> OpenUni<'a, Self> {
634			OpenUni {
635				session: self,
636				options,
637				park: kio::Park::default(),
638			}
639		}
640
641		/// Open a bidirectional stream, its sending half scheduled by `options`, waiting for
642		/// stream credit if necessary.
643		fn open_bi<'a>(
644			&'a self,
645			options: SendOptions<'a, <Self::SendStream as SendStream>::Group>,
646		) -> OpenBi<'a, Self> {
647			OpenBi {
648				session: self,
649				options,
650				park: kio::Park::default(),
651			}
652		}
653
654		/// Receive the next datagram from the peer.
655		fn recv_datagram(&self) -> RecvDatagram<'_, Self> {
656			RecvDatagram::new(self)
657		}
658
659		/// Wait until the session is closed by either side, returning the reason.
660		fn closed(&self) -> SessionClosed<'_, Self> {
661			SessionClosed::new(self)
662		}
663	}
664
665	/// One in-flight `poll_*` operation as a [`Future`]: the helpers below are
666	/// named types (not `impl Future`) so their `Send`-ness stays inferred from
667	/// the transport; an opaque return type in a trait would hide it. Each holds
668	/// the [`kio::Park`] that keeps its waiter registered between polls.
669	macro_rules! poll_future {
670		($(#[$doc:meta])* $name:ident, $bound:path, $poll:ident, $out:ty) => {
671			$(#[$doc])*
672			pub struct $name<'a, S: ?Sized> {
673				inner: &'a S,
674				park: kio::Park,
675			}
676
677			impl<'a, S: ?Sized> $name<'a, S> {
678				fn new(inner: &'a S) -> Self {
679					Self {
680						inner,
681						park: kio::Park::default(),
682					}
683				}
684			}
685
686			impl<S: $bound + ?Sized> Future for $name<'_, S> {
687				type Output = $out;
688
689				fn poll(mut self: std::pin::Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
690					let this = &mut *self;
691					this.inner.$poll(this.park.hold(cx))
692				}
693			}
694		};
695	}
696
697	poll_future!(
698		/// A pending [`Session::accept_uni`].
699		AcceptUni, Session, poll_accept_uni, Result<S::RecvStream, S::Error>);
700	poll_future!(
701		/// A pending [`Session::accept_bi`].
702		AcceptBi, Session, poll_accept_bi, Result<BiStreams<S>, S::Error>);
703	/// One in-flight open, which polls with the same options until it resolves.
704	macro_rules! open_future {
705		($(#[$doc:meta])* $name:ident, $poll:ident, $out:ty) => {
706			$(#[$doc])*
707			pub struct $name<'a, S: Session + ?Sized> {
708				session: &'a S,
709				options: SendOptions<'a, <S::SendStream as SendStream>::Group>,
710				park: kio::Park,
711			}
712
713			impl<S: Session + ?Sized> Future for $name<'_, S> {
714				type Output = $out;
715
716				fn poll(self: std::pin::Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
717					let this = self.get_mut();
718					this.session.$poll(this.park.hold(cx), this.options)
719				}
720			}
721		};
722	}
723
724	open_future!(
725		/// A pending [`Session::open_uni`].
726		OpenUni, poll_open_uni, Result<S::SendStream, S::Error>);
727	open_future!(
728		/// A pending [`Session::open_bi`].
729		OpenBi, poll_open_bi, Result<BiStreams<S>, S::Error>);
730	poll_future!(
731		/// A pending [`Session::recv_datagram`].
732		RecvDatagram, Session, poll_recv_datagram, Result<Bytes, S::Error>);
733	poll_future!(
734		/// A pending [`Session::closed`].
735		SessionClosed, Session, poll_closed, S::Error);
736	poll_future!(
737		/// A pending [`SendStream::closed`].
738		SendClosed, SendStream, poll_closed, Result<(), S::Error>);
739
740	/// A session shared with the client or server that runs it, so the caller can still close
741	/// or watch it.
742	impl<S: Session + ?Sized> Session for std::sync::Arc<S> {
743		type SendStream = S::SendStream;
744		type RecvStream = S::RecvStream;
745		type Error = S::Error;
746
747		fn poll_accept_uni(&self, waiter: &kio::Waiter) -> Poll<Result<Self::RecvStream, Self::Error>> {
748			(**self).poll_accept_uni(waiter)
749		}
750
751		fn poll_accept_bi(&self, waiter: &kio::Waiter) -> Poll<Result<BiStreams<Self>, Self::Error>> {
752			(**self).poll_accept_bi(waiter)
753		}
754
755		fn poll_open_uni(
756			&self,
757			waiter: &kio::Waiter,
758			options: SendOptions<'_, <Self::SendStream as SendStream>::Group>,
759		) -> Poll<Result<Self::SendStream, Self::Error>> {
760			(**self).poll_open_uni(waiter, options)
761		}
762
763		fn poll_open_bi(
764			&self,
765			waiter: &kio::Waiter,
766			options: SendOptions<'_, <Self::SendStream as SendStream>::Group>,
767		) -> Poll<Result<BiStreams<Self>, Self::Error>> {
768			(**self).poll_open_bi(waiter, options)
769		}
770
771		fn send_group(&self, priority: i64) -> Option<<Self::SendStream as SendStream>::Group> {
772			(**self).send_group(priority)
773		}
774
775		fn send_datagram(
776			&self,
777			payload: Bytes,
778			options: SendOptions<'_, <Self::SendStream as SendStream>::Group>,
779		) -> Result<(), Self::Error> {
780			(**self).send_datagram(payload, options)
781		}
782
783		fn poll_recv_datagram(&self, waiter: &kio::Waiter) -> Poll<Result<Bytes, Self::Error>> {
784			(**self).poll_recv_datagram(waiter)
785		}
786
787		fn max_datagram_size(&self) -> usize {
788			(**self).max_datagram_size()
789		}
790
791		fn protocol(&self) -> Option<&str> {
792			(**self).protocol()
793		}
794
795		fn address(&self) -> super::Address {
796			(**self).address()
797		}
798
799		fn close(&self, code: u32, reason: &str) {
800			(**self).close(code, reason)
801		}
802
803		fn poll_closed(&self, waiter: &kio::Waiter) -> Poll<Self::Error> {
804			(**self).poll_closed(waiter)
805		}
806
807		fn metrics(&self) -> impl Metrics {
808			(**self).metrics()
809		}
810
811		fn wire(&self) -> Option<super::Wire> {
812			(**self).wire()
813		}
814
815		fn probe(&self) -> Option<super::Probe> {
816			(**self).probe()
817		}
818
819		fn receive_window(&self) -> Option<super::ReceiveWindow> {
820			(**self).receive_window()
821		}
822
823		fn reliable_reset(&self) -> bool {
824			(**self).reliable_reset()
825		}
826
827		fn set_limits(&self, limits: super::Limits) -> Result<(), super::LimitsError> {
828			(**self).set_limits(limits)
829		}
830
831		fn set_keep_alive(&self, keep_alive: super::KeepAlive) -> Result<(), super::KeepAliveError> {
832			(**self).set_keep_alive(keep_alive)
833		}
834
835		fn poll_liveness(&self, waiter: &kio::Waiter, last: super::Liveness) -> Poll<super::Liveness> {
836			(**self).poll_liveness(waiter, last)
837		}
838	}
839
840	/// A transport that the async client and server can box:
841	/// the session, its streams, send groups, and errors are thread-safe.
842	/// Implemented automatically.
843	///
844	/// Boxing is what compiles the session code once per binary rather than once per
845	/// transport.
846	pub trait Boxable:
847		Session<SendStream: Send + Sync + SendStream<Group: Send + Sync, Offset: Send + Sync>, RecvStream: Send + Sync>
848		+ Send
849		+ Sync
850	{
851	}
852
853	impl<S> Boxable for S where
854		S: Session<
855				SendStream: Send + Sync + SendStream<Group: Send + Sync, Offset: Send + Sync>,
856				RecvStream: Send + Sync,
857			> + Send
858			+ Sync
859	{
860	}
861
862	/// The send group of a session's streams.
863	#[cfg(feature = "async")]
864	pub(crate) type GroupOf<S> = <<S as Session>::SendStream as SendStream>::Group;
865
866	/// How an outgoing stream or datagram is scheduled, like W3C WebTransport's send options.
867	///
868	/// The default is ungrouped at priority 0.
869	#[derive(Debug)]
870	pub struct SendOptions<'a, G> {
871		/// The send group to join, from [`Session::send_group`], or `None` for the ungrouped
872		/// streams that go before every group.
873		pub group: Option<&'a G>,
874		/// The priority within the group, like [`SendStream::set_priority`]: higher goes first.
875		pub priority: i64,
876	}
877
878	impl<G> Default for SendOptions<'_, G> {
879		fn default() -> Self {
880			Self {
881				group: None,
882				priority: 0,
883			}
884		}
885	}
886
887	impl<G> Clone for SendOptions<'_, G> {
888		fn clone(&self) -> Self {
889			*self
890		}
891	}
892
893	impl<G> Copy for SendOptions<'_, G> {}
894
895	/// A transport's send group, from [`Session::send_group`].
896	///
897	/// Clones share the group.
898	pub trait SendGroup: Clone + 'static {
899		/// Change the group's priority: higher preempts lower.
900		fn set_priority(&mut self, priority: i64);
901	}
902
903	/// The send group of a transport that has none, which cannot be constructed.
904	#[derive(Clone, Debug)]
905	pub enum Ungrouped {}
906
907	impl SendGroup for Ungrouped {
908		fn set_priority(&mut self, _: i64) {
909			match *self {}
910		}
911	}
912
913	/// An outgoing stream with partial writes, priorities, and reset codes.
914	pub trait SendStream: 'static {
915		/// The error type for every operation on this stream.
916		type Error: Error;
917
918		/// The transport's send group, [`Ungrouped`] for a transport without them.
919		type Group: SendGroup;
920
921		/// A position in the stream, minted only by [`offset`](Self::offset), for
922		/// [`poll_acked`](Self::poll_acked). `()` for a transport that cannot see acknowledgments.
923		type Offset: 'static;
924
925		/// The position just past every byte written so far.
926		fn offset(&self) -> Self::Offset;
927
928		/// Poll until every byte below `offset` reaches the peer unless the session fails.
929		///
930		/// That is once the peer acknowledged them, or, over a reliable link such as qmux's TCP,
931		/// once the link took them, so a reset can no longer discard them. Errors once those
932		/// bytes can never get there: the stream was reset by either side or the session closed.
933		/// Bytes already acknowledged stay so after a reset or stop. The default, for a transport
934		/// that cannot see acknowledgments, is ready at once: the bytes it took are all it knows.
935		/// An offset minted by another stream may panic.
936		fn poll_acked(&self, waiter: &kio::Waiter, offset: &Self::Offset) -> Poll<Result<(), Self::Error>> {
937			let _ = (waiter, offset);
938			Poll::Ready(Ok(()))
939		}
940
941		/// Poll to write some of the buffer to the stream, returning how many bytes were
942		/// written. See [`poll_write_buf`](Self::poll_write_buf) for the partial-write
943		/// contract, which this shares.
944		fn poll_write(&mut self, waiter: &kio::Waiter, buf: &[u8]) -> Poll<Result<usize, Self::Error>>;
945
946		/// Poll to write some of the given buffer to the stream, advancing it by the
947		/// number of bytes written. This may be less than the whole buffer, so callers
948		/// loop.
949		///
950		/// # Partial writes
951		///
952		/// Implementations must not advance `buf` past the bytes they accepted for
953		/// sending. (Whether those bytes reach the peer is a separate matter: a reset
954		/// or a dead connection can still discard accepted bytes.) A returned
955		/// [`Poll::Pending`] must leave `buf` exactly where the accepted bytes end.
956		/// Callers race writes against other work, so a byte taken from `buf` but never
957		/// accepted becomes a silent hole in the stream, which the peer decodes as a
958		/// truncated or garbage frame. Wait for send capacity *before* consuming from
959		/// `buf`, never after.
960		///
961		/// Override this to avoid a copy when the underlying transport can take
962		/// ownership of `buf`'s bytes: see [`Buf::copy_to_bytes`], which is free for a
963		/// [`Bytes`] source.
964		fn poll_write_buf<B: Buf>(&mut self, waiter: &kio::Waiter, buf: &mut B) -> Poll<Result<usize, Self::Error>> {
965			let size = ready!(self.poll_write(waiter, buf.chunk()))?;
966			buf.advance(size);
967			Poll::Ready(Ok(size))
968		}
969
970		/// Set the priority within the stream's send group, or session-wide when ungrouped.
971		///
972		/// Streams with higher values will be sent first, but are not guaranteed to
973		/// arrive first. This matches the W3C WebTransport `sendOrder` convention.
974		///
975		/// Backends with a narrower priority saturate or approximate it, so treat the
976		/// ordering as best-effort.
977		fn set_priority(&mut self, priority: i64);
978
979		/// Move the stream into `group`, which belongs to this stream's session.
980		fn set_group(&mut self, group: &Self::Group);
981
982		/// Mark the stream as finished, erroring on any future writes.
983		///
984		/// [`reset`](Self::reset) can still be called to abandon any queued data.
985		/// [`poll_closed`](Self::poll_closed) should resolve when the FIN is acknowledged
986		/// by the peer.
987		///
988		/// Dropping an unfinished stream must [`reset`](Self::reset) it, so the peer cannot
989		/// mistake truncated data for a complete stream.
990		fn finish(&mut self) -> Result<(), Self::Error>;
991
992		/// Immediately closes the stream and discards any remaining data.
993		///
994		/// This translates into a RESET_STREAM QUIC code.
995		/// The peer may not receive the reset code if the stream is already closed.
996		///
997		/// Takes `&mut self` rather than `self` even though it is terminal, so a caller
998		/// can still [`poll_closed`](Self::poll_closed) afterwards to await the peer,
999		/// and so it matches [`finish`](Self::finish), which must not consume the stream
1000		/// for exactly that reason.
1001		fn reset(&mut self, code: u32);
1002
1003		/// Like [`reset`](Self::reset), but still deliver every byte before `offset`.
1004		///
1005		/// The peer reads those bytes before the reset's error only where the session's
1006		/// [`reliable_reset`](Session::reliable_reset) says so; otherwise the transport may send a
1007		/// plain reset once it delivered them, which lets the peer discard any it has not read. A
1008		/// peer that stopped the stream gets the reset without them. Takes `&mut self` for the
1009		/// same reasons as [`reset`](Self::reset).
1010		fn reset_at(&mut self, offset: &Self::Offset, code: u32);
1011
1012		/// Poll until the stream is closed by either side.
1013		///
1014		/// This includes:
1015		/// - We sent a RESET_STREAM via [`reset`](Self::reset)
1016		/// - We received a STOP_SENDING via [`RecvStream::stop`]
1017		/// - A FIN is acknowledged by the peer via [`finish`](Self::finish)
1018		///
1019		/// Some implementations do not support FIN acknowledgement, in which case this
1020		/// resolves once the FIN is sent.
1021		fn poll_closed(&self, waiter: &kio::Waiter) -> Poll<Result<(), Self::Error>>;
1022
1023		/// Write some of the buffer, returning how many bytes were accepted.
1024		fn write<'a>(&'a mut self, buf: &'a [u8]) -> Write<'a, Self> {
1025			Write {
1026				stream: self,
1027				buf,
1028				park: kio::Park::default(),
1029			}
1030		}
1031
1032		/// Write some of the buffer, advancing it by the bytes accepted.
1033		fn write_buf<'a, B: Buf>(&'a mut self, buf: &'a mut B) -> WriteBuf<'a, Self, B> {
1034			WriteBuf {
1035				stream: self,
1036				buf,
1037				park: kio::Park::default(),
1038			}
1039		}
1040
1041		/// Write the entire chunk to the stream.
1042		fn write_chunk(&mut self, chunk: Bytes) -> WriteChunk<'_, Self> {
1043			WriteChunk {
1044				stream: self,
1045				chunk,
1046				park: kio::Park::default(),
1047			}
1048		}
1049
1050		/// Wait until the stream is closed by either side.
1051		fn closed(&self) -> SendClosed<'_, Self> {
1052			SendClosed::new(self)
1053		}
1054	}
1055
1056	/// A pending [`SendStream::write`].
1057	pub struct Write<'a, S: ?Sized> {
1058		stream: &'a mut S,
1059		buf: &'a [u8],
1060		park: kio::Park,
1061	}
1062
1063	impl<S: SendStream> Future for Write<'_, S> {
1064		type Output = Result<usize, S::Error>;
1065
1066		fn poll(mut self: std::pin::Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
1067			let this = &mut *self;
1068			this.stream.poll_write(this.park.hold(cx), this.buf)
1069		}
1070	}
1071
1072	/// A pending [`SendStream::write_buf`].
1073	pub struct WriteBuf<'a, S: ?Sized, B> {
1074		stream: &'a mut S,
1075		buf: &'a mut B,
1076		park: kio::Park,
1077	}
1078
1079	impl<S: SendStream, B: Buf> Future for WriteBuf<'_, S, B> {
1080		type Output = Result<usize, S::Error>;
1081
1082		fn poll(mut self: std::pin::Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
1083			let this = &mut *self;
1084			this.stream.poll_write_buf(this.park.hold(cx), this.buf)
1085		}
1086	}
1087
1088	/// A pending [`SendStream::write_chunk`].
1089	pub struct WriteChunk<'a, S: ?Sized> {
1090		stream: &'a mut S,
1091		chunk: Bytes,
1092		park: kio::Park,
1093	}
1094
1095	impl<S: SendStream> Future for WriteChunk<'_, S> {
1096		type Output = Result<(), S::Error>;
1097
1098		fn poll(mut self: std::pin::Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
1099			let this = &mut *self;
1100			let waiter = this.park.hold(cx);
1101			while !this.chunk.is_empty() {
1102				ready!(this.stream.poll_write_buf(waiter, &mut this.chunk))?;
1103			}
1104			Poll::Ready(Ok(()))
1105		}
1106	}
1107
1108	/// An incoming stream, read through leases of the bytes its transport buffers.
1109	///
1110	/// Leased bytes stay in the transport, counted against its flow control, until
1111	/// [`Lease::release`] returns the credit of those read, so an incomplete message holds
1112	/// receive credit rather than memory of its own. When incomplete messages leave no credit for
1113	/// any of them to finish, a transport that bounds them evicts the lowest
1114	/// [priority](Self::set_priority) holder, whose next lease fails. A transport that returns
1115	/// credit as it reads, adapted with [`Buffered`], is not bounded this way.
1116	pub trait RecvStream: 'static {
1117		/// The error type for every operation on this stream.
1118		type Error: Error;
1119
1120		/// The unreleased bytes borrowed from this stream.
1121		type Lease<'a>: Lease
1122		where
1123			Self: 'a;
1124
1125		/// Poll until at least `want` bytes are leased, or the peer finished the stream with
1126		/// fewer.
1127		///
1128		/// Reading the lease as a [`Buf`] moves past bytes for good, but they keep their
1129		/// flow-control credit until [`Lease::release`]. Bytes not read stay for the next lease.
1130		/// A `want` the stream's receive window can never hold is an error rather than a wait, and
1131		/// a `want` of 0 never waits.
1132		///
1133		/// A lease may borrow the transport's connection state, so release it before
1134		/// touching any other stream of the session.
1135		fn poll_lease(&mut self, waiter: &kio::Waiter, want: usize) -> Poll<Result<Self::Lease<'_>, Self::Error>>;
1136
1137		/// Rank this stream for eviction when incomplete messages exhaust the receive window.
1138		///
1139		/// Higher keeps it longer, the convention of [`SendStream::set_priority`]. A stream
1140		/// starts at 0, and ties evict the newest stream first. A transport without eviction
1141		/// ignores it.
1142		fn set_priority(&mut self, priority: i64);
1143
1144		/// Send a `STOP_SENDING` QUIC code, informing the peer that no more data will be
1145		/// read, and discard what is buffered.
1146		///
1147		/// An implementation MUST do this on Drop otherwise flow control will be leaked.
1148		/// Call this method manually if you want to specify a code yourself.
1149		fn stop(&mut self, code: u32);
1150
1151		/// Poll until the stream fails without reading it: the peer resets it, the receiver
1152		/// evicts it to free a stuck window, or the connection closes. Pending for good once the
1153		/// peer finished it.
1154		///
1155		/// A session that stops reading a stream, to pace it (see [`Session::receive_window`])
1156		/// or until a control message says how to read it, watches this instead, so a reset
1157		/// still ends the group it carries and an eviction stops the stream. It takes no bytes and grants no credit. The default never completes,
1158		/// which suits a transport reporting no receive window, since none of its streams pause.
1159		fn poll_reset(&mut self, waiter: &kio::Waiter) -> Poll<Self::Error> {
1160			let _ = waiter;
1161			Poll::Pending
1162		}
1163
1164		/// Let the peer send at most `window` bytes past what the reader took, rather than the
1165		/// stream's full receive credit, returning the connection credit the stream may hold from
1166		/// now on: the bytes that arrived and were not released, and those the peer may still send.
1167		///
1168		/// A session pacing a stream (see [`Session::receive_window`]) shrinks its window as the
1169		/// group runs out of room, so the stream holds little once paused, and many fit in the
1170		/// connection window. Credit already granted stays granted. `None` when the transport
1171		/// cannot, the default, whose paused streams hold their full stream credit.
1172		///
1173		/// A transport that can also implements [`Lease::set_window`].
1174		fn set_window(&mut self, window: u64) -> Option<u64> {
1175			let _ = window;
1176			None
1177		}
1178
1179		/// Poll for the next chunk, up to `max` bytes, or `None` once the peer finished the
1180		/// stream. Its credit returns as it is read.
1181		///
1182		/// An empty `max` reads nothing and returns an empty chunk: asking for no bytes is
1183		/// not end of stream.
1184		fn poll_read_chunk(&mut self, waiter: &kio::Waiter, max: usize) -> Poll<Result<Option<Bytes>, Self::Error>> {
1185			if max == 0 {
1186				return Poll::Ready(Ok(Some(Bytes::new())));
1187			}
1188			let mut lease = ready!(self.poll_lease(waiter, 1))?;
1189			if !lease.has_remaining() {
1190				return Poll::Ready(Ok(None));
1191			}
1192			let chunk = lease.copy_to_bytes(lease.chunk().len().min(max));
1193			lease.release();
1194			Poll::Ready(Ok(Some(chunk)))
1195		}
1196
1197		/// Read the next chunk, up to `max` bytes, or `None` once finished.
1198		fn read_chunk(&mut self, max: usize) -> ReadChunk<'_, Self> {
1199			ReadChunk {
1200				stream: self,
1201				max,
1202				park: kio::Park::default(),
1203			}
1204		}
1205	}
1206
1207	/// Unreleased bytes borrowed from a [`RecvStream`] by [`poll_lease`](RecvStream::poll_lease),
1208	/// read as a [`Buf`].
1209	///
1210	/// Bytes read keep their credit until [`release`](Self::release), which is how a frame
1211	/// reaches its consumer before the whole of it has arrived. Implementations override
1212	/// [`Buf::copy_to_bytes`] to hand out bytes within one chunk without copying.
1213	pub trait Lease: Buf {
1214		/// The bytes not yet read, in order, one contiguous chunk at a time, without reading them.
1215		fn chunks(&self) -> impl Iterator<Item = &[u8]>;
1216
1217		/// Whether the peer finished the stream right after the leased bytes.
1218		fn is_fin(&self) -> bool;
1219
1220		/// Return the credit of every byte read so far, by this lease or an earlier one.
1221		fn release(self);
1222
1223		/// Set the stream's window, as [`RecvStream::set_window`] does, in the same step as the
1224		/// lease is handed back, by [`release`](Self::release) or a drop.
1225		///
1226		/// The reader shrinks the window for the bytes it just read, and the credit they return
1227		/// may be granted from the window as the transport builds the grant. A shrink made
1228		/// after the hand back can lose that race, and credit granted cannot be taken back.
1229		/// Ignored by default, for a transport whose streams cannot set a window.
1230		fn set_window(&mut self, window: u64) {
1231			let _ = window;
1232		}
1233	}
1234
1235	/// A pending [`RecvStream::read_chunk`].
1236	pub struct ReadChunk<'a, S: ?Sized> {
1237		stream: &'a mut S,
1238		max: usize,
1239		park: kio::Park,
1240	}
1241
1242	impl<S: RecvStream> Future for ReadChunk<'_, S> {
1243		type Output = Result<Option<Bytes>, S::Error>;
1244
1245		fn poll(mut self: std::pin::Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
1246			let this = &mut *self;
1247			this.stream.poll_read_chunk(this.park.hold(cx), this.max)
1248		}
1249	}
1250
1251	/// A receive stream read as plain chunks, whose flow-control credit returns as it reads.
1252	///
1253	/// [`Buffered`] turns one into a [`RecvStream`].
1254	pub trait Chunks: 'static {
1255		/// The error type for every operation on this stream.
1256		type Error: Error;
1257
1258		/// Poll for the next chunk, up to `max` bytes, or `None` once the peer finished the
1259		/// stream.
1260		fn poll_read_chunk(&mut self, waiter: &kio::Waiter, max: usize) -> Poll<Result<Option<Bytes>, Self::Error>>;
1261
1262		/// Send a `STOP_SENDING` code. See [`RecvStream::stop`].
1263		///
1264		/// An implementation MUST also do this on Drop: [`Buffered`] forwards an explicit stop
1265		/// but leaves the drop to the wrapped stream.
1266		fn stop(&mut self, code: u32);
1267
1268		/// Poll until the stream fails without reading it. See [`RecvStream::poll_reset`].
1269		fn poll_reset(&mut self, waiter: &kio::Waiter) -> Poll<Self::Error> {
1270			let _ = waiter;
1271			Poll::Pending
1272		}
1273	}
1274
1275	/// Leases over a transport that cannot keep bytes unconsumed, buffering what it reads.
1276	///
1277	/// The transport returns credit as it reads, so incomplete messages are bounded by the
1278	/// largest message each, not by its receive window, and nothing is evicted.
1279	pub struct Buffered<S> {
1280		inner: S,
1281		chunks: VecDeque<Bytes>,
1282		len: usize,
1283		fin: bool,
1284	}
1285
1286	impl<S> Buffered<S> {
1287		/// Lease over `inner`.
1288		pub fn new(inner: S) -> Self {
1289			Self {
1290				inner,
1291				chunks: VecDeque::new(),
1292				len: 0,
1293				fin: false,
1294			}
1295		}
1296
1297		/// The wrapped stream.
1298		pub fn get_ref(&self) -> &S {
1299			&self.inner
1300		}
1301
1302		/// The wrapped stream.
1303		pub fn get_mut(&mut self) -> &mut S {
1304			&mut self.inner
1305		}
1306	}
1307
1308	impl<S: Chunks> RecvStream for Buffered<S> {
1309		type Error = S::Error;
1310		type Lease<'a>
1311			= BufferedLease<'a>
1312		where
1313			S: 'a;
1314
1315		fn poll_lease(&mut self, waiter: &kio::Waiter, want: usize) -> Poll<Result<BufferedLease<'_>, S::Error>> {
1316			while self.len < want && !self.fin {
1317				// Whatever the transport has in one piece: a transport handing over whole
1318				// messages, like the memory one, keeps a large frame in a single chunk, so it
1319				// reaches the consumer without a copy. Each read still ends at what has arrived.
1320				match ready!(self.inner.poll_read_chunk(waiter, usize::MAX))? {
1321					Some(chunk) if chunk.is_empty() => {}
1322					Some(chunk) => {
1323						self.len += chunk.len();
1324						self.chunks.push_back(chunk);
1325					}
1326					None => self.fin = true,
1327				}
1328			}
1329			Poll::Ready(Ok(BufferedLease {
1330				chunks: &mut self.chunks,
1331				len: &mut self.len,
1332				fin: self.fin,
1333			}))
1334		}
1335
1336		fn set_priority(&mut self, _priority: i64) {}
1337
1338		fn stop(&mut self, code: u32) {
1339			self.chunks.clear();
1340			self.len = 0;
1341			self.inner.stop(code);
1342		}
1343
1344		fn poll_reset(&mut self, waiter: &kio::Waiter) -> Poll<S::Error> {
1345			// Every byte arrived, so nothing is left to reset.
1346			match self.fin {
1347				true => Poll::Pending,
1348				false => self.inner.poll_reset(waiter),
1349			}
1350		}
1351	}
1352
1353	/// A [`Lease`] of a [`Buffered`] stream.
1354	pub struct BufferedLease<'a> {
1355		chunks: &'a mut VecDeque<Bytes>,
1356		len: &'a mut usize,
1357		fin: bool,
1358	}
1359
1360	impl Buf for BufferedLease<'_> {
1361		fn remaining(&self) -> usize {
1362			*self.len
1363		}
1364
1365		fn chunk(&self) -> &[u8] {
1366			self.chunks.front().map_or(&[], |chunk| &chunk[..])
1367		}
1368
1369		fn advance(&mut self, mut n: usize) {
1370			assert!(n <= *self.len, "advanced {n} past {} leased bytes", *self.len);
1371			*self.len -= n;
1372			while n > 0 {
1373				let front = self.chunks.front_mut().expect("counted above");
1374				if front.len() > n {
1375					front.advance(n);
1376					return;
1377				}
1378				n -= front.len();
1379				self.chunks.pop_front();
1380			}
1381		}
1382
1383		fn copy_to_bytes(&mut self, n: usize) -> Bytes {
1384			assert!(n <= *self.len, "copied {n} of {} leased bytes", *self.len);
1385			let Some(front) = self.chunks.front_mut().filter(|front| front.len() >= n) else {
1386				// Spans chunks, so it needs a contiguous copy.
1387				let mut bytes = BytesMut::with_capacity(n);
1388				while bytes.len() < n {
1389					let take = self.chunk().len().min(n - bytes.len());
1390					bytes.extend_from_slice(&self.chunk()[..take]);
1391					self.advance(take);
1392				}
1393				return bytes.freeze();
1394			};
1395			*self.len -= n;
1396			match front.len() > n {
1397				true => front.split_to(n),
1398				false => self.chunks.pop_front().expect("front exists"),
1399			}
1400		}
1401	}
1402
1403	impl Lease for BufferedLease<'_> {
1404		fn chunks(&self) -> impl Iterator<Item = &[u8]> {
1405			self.chunks.iter().map(|chunk| &chunk[..])
1406		}
1407
1408		fn is_fin(&self) -> bool {
1409			self.fin
1410		}
1411
1412		// The transport returned the credit as it read.
1413		fn release(self) {}
1414	}
1415}
1416
1417#[cfg(test)]
1418mod tests {
1419	use super::poll::{Buffered, Chunks, Lease as _, RecvStream as _};
1420	use bytes::{Buf, Bytes};
1421	use std::collections::VecDeque;
1422	use std::task::{Context, Poll};
1423
1424	/// Hands back one queued chunk per poll, then blocks, or finishes once told to.
1425	#[derive(Default)]
1426	struct Queue {
1427		chunks: VecDeque<&'static [u8]>,
1428		fin: bool,
1429		stopped: Option<u32>,
1430	}
1431
1432	impl Chunks for Queue {
1433		type Error = crate::Error;
1434		fn poll_read_chunk(&mut self, _: &kio::Waiter, max: usize) -> Poll<Result<Option<Bytes>, Self::Error>> {
1435			match self.chunks.pop_front() {
1436				Some(chunk) => {
1437					let n = chunk.len().min(max);
1438					if n < chunk.len() {
1439						self.chunks.push_front(&chunk[n..]);
1440					}
1441					Poll::Ready(Ok(Some(Bytes::from_static(&chunk[..n]))))
1442				}
1443				None if self.fin => Poll::Ready(Ok(None)),
1444				None => Poll::Pending,
1445			}
1446		}
1447		fn stop(&mut self, code: u32) {
1448			self.stopped = Some(code);
1449		}
1450	}
1451
1452	fn buffered(chunks: &[&'static [u8]], fin: bool) -> Buffered<Queue> {
1453		Buffered::new(Queue {
1454			chunks: chunks.iter().copied().collect(),
1455			fin,
1456			stopped: None,
1457		})
1458	}
1459
1460	/// A lease waits for `want` across chunks, and dropping it keeps every unread byte for the next.
1461	#[test]
1462	fn lease_waits_for_want_and_drop_keeps_unread() {
1463		let waiter = kio::Waiter::noop();
1464		let mut stream = buffered(&[b"ab", b"cd"], false);
1465
1466		{
1467			let Poll::Ready(Ok(lease)) = stream.poll_lease(&waiter, 3) else {
1468				panic!("both chunks were ready")
1469			};
1470			assert_eq!(lease.remaining(), 4);
1471			assert_eq!(lease.chunk(), b"ab");
1472			assert_eq!(lease.chunks().collect::<Vec<_>>(), [b"ab", b"cd"]);
1473		}
1474
1475		assert!(stream.poll_lease(&waiter, 5).is_pending(), "nothing more arrived");
1476		let Poll::Ready(Ok(lease)) = stream.poll_lease(&waiter, 1) else {
1477			panic!("the dropped lease's bytes are still there")
1478		};
1479		let mut lease = lease;
1480		assert_eq!(lease.remaining(), 4);
1481		lease.advance(3);
1482		lease.release();
1483
1484		let Poll::Ready(Ok(lease)) = stream.poll_lease(&waiter, 0) else {
1485			panic!("want 0 never waits")
1486		};
1487		assert_eq!(lease.chunk(), b"d");
1488		assert!(!lease.is_fin());
1489	}
1490
1491	/// Bytes within a chunk are handed out without a copy, bytes across chunks are joined, and a
1492	/// finished stream leases what is left with its FIN.
1493	#[test]
1494	fn copy_to_bytes_and_fin_ends_short() {
1495		let waiter = kio::Waiter::noop();
1496		let mut stream = buffered(&[b"abc", b"de"], true);
1497
1498		let Poll::Ready(Ok(mut lease)) = stream.poll_lease(&waiter, 10) else {
1499			panic!("a finished stream leases short")
1500		};
1501		assert!(lease.is_fin());
1502		assert_eq!(lease.copy_to_bytes(2), Bytes::from_static(b"ab"));
1503		assert_eq!(
1504			lease.copy_to_bytes(2),
1505			Bytes::from_static(b"cd"),
1506			"joined across chunks"
1507		);
1508		assert_eq!(lease.remaining(), 1);
1509		lease.release();
1510
1511		assert_eq!(
1512			stream.read_chunk(10).now_or_never_ready(),
1513			Some(Bytes::from_static(b"e"))
1514		);
1515		assert_eq!(stream.read_chunk(10).now_or_never_ready(), None);
1516		assert_eq!(stream.read_chunk(0).now_or_never_ready(), Some(Bytes::new()));
1517	}
1518
1519	/// A large chunk the transport hands over whole reaches the reader as that same
1520	/// allocation, so a frame from the memory transport is never copied.
1521	#[test]
1522	fn a_large_chunk_is_leased_whole() {
1523		static FRAME: [u8; 1 << 20] = [7; 1 << 20];
1524		let waiter = kio::Waiter::noop();
1525		let mut stream = buffered(&[&FRAME], true);
1526
1527		let Poll::Ready(Ok(mut lease)) = stream.poll_lease(&waiter, 1) else {
1528			panic!("the chunk was ready")
1529		};
1530		let chunk = lease.copy_to_bytes(FRAME.len());
1531		assert_eq!(chunk.len(), FRAME.len());
1532		assert_eq!(chunk.as_ptr(), FRAME.as_ptr(), "the chunk was not copied");
1533	}
1534
1535	/// Stopping discards what was buffered and stops the transport.
1536	#[test]
1537	fn stop_discards_the_buffer() {
1538		let waiter = kio::Waiter::noop();
1539		let mut stream = buffered(&[b"abc"], false);
1540		assert!(stream.poll_lease(&waiter, 1).is_ready());
1541		stream.stop(7);
1542		assert_eq!(stream.get_ref().stopped, Some(7));
1543		assert!(stream.poll_lease(&waiter, 1).is_pending());
1544	}
1545
1546	trait NowOrNever {
1547		fn now_or_never_ready(self) -> Option<Bytes>;
1548	}
1549
1550	impl<F: Future<Output = Result<Option<Bytes>, crate::Error>>> NowOrNever for F {
1551		fn now_or_never_ready(self) -> Option<Bytes> {
1552			let mut cx = Context::from_waker(std::task::Waker::noop());
1553			match std::pin::pin!(self).poll(&mut cx) {
1554				Poll::Ready(res) => res.unwrap(),
1555				Poll::Pending => panic!("pending"),
1556			}
1557		}
1558	}
1559}