Skip to main content

moq_net/transport/
memory.rs

1//! An in-memory [`poll::Session`] pair: two peers in one process, no sockets or crypto.
2//!
3//! Each stream is a channel of [`Bytes`] messages: a write queues one message and a read
4//! hands it back, the same allocation, so a payload crosses without a copy. A read with a
5//! smaller limit splits the message, still without a copy.
6//!
7//! Each stream's channel is bounded by [`Config::stream_buffer`] queued bytes, and a write
8//! pends while it is full, so a slow reader throttles only its own stream. A write is
9//! never split: one accepted while the channel has room may overshoot the bound.
10//!
11//! [`Config::max_concurrent_uni_streams`] and [`Config::max_concurrent_bi_streams`] bound
12//! the streams each side has open toward its peer, as QUIC's stream credit does: an open
13//! pends until the peer is done with one.
14//!
15//! [`finish`](poll::SendStream::finish) closes the channel cleanly once its messages are
16//! read. A [`reset`](poll::SendStream::reset) or [`stop`](poll::RecvStream::stop) closes it
17//! with a code and drops what it queued, except that a
18//! [`reset_at`](poll::SendStream::reset_at) keeps the bytes before its offset for the reader
19//! ahead of the code. Closing the session keeps queued messages
20//! readable, and leaves streams as they were, so the peer reads them, then the close.
21//!
22//! Reads return the channel's room as they go, so streams lease through
23//! [`Buffered`](poll::Buffered) and are not bounded by a receive window.
24//!
25//! Datagrams ignore their send options, and are dropped when oversized or when the
26//! peer's queue is full, as a network would.
27//!
28//! [`Config::latency`] delays each stream message and finish on the ambient clock, so
29//! a mesh of pairs orders its traffic as a network of that latency would. Opens,
30//! resets, stops, datagrams, and the session close skip it.
31
32use std::{
33	collections::VecDeque,
34	pin::Pin,
35	sync::Arc,
36	task::{Poll, ready},
37	time::Duration,
38};
39
40use bytes::{Buf, Bytes};
41
42use super::poll;
43
44/// The largest datagram either side sends: QUIC's minimum MTU, so a payload that fits
45/// here fits any QUIC path.
46const MAX_DATAGRAM_SIZE: usize = 1200;
47
48/// Unread datagrams one side holds before new ones are dropped.
49const DATAGRAM_QUEUE: usize = 1024;
50
51/// The options both sides of a [`pair`] share.
52#[derive(Clone, Debug)]
53#[non_exhaustive]
54pub struct Config {
55	/// Queued bytes one stream holds before its writer pends. An empty stream always takes
56	/// one write, so 0 holds one message at a time.
57	pub stream_buffer: usize,
58	/// The application protocol both sides report, standing in for a negotiated ALPN.
59	pub protocol: Option<String>,
60	/// Uni streams one side may have open toward its peer at once, as QUIC's stream credit.
61	/// A stream is open until its reader reaches the end, stops, or drops it, accepted or
62	/// not. `None` grants credit without limit.
63	pub max_concurrent_uni_streams: Option<usize>,
64	/// Bidi streams one side may have open toward its peer at once, as QUIC's stream credit.
65	/// A stream is open until the peer is done with both halves: its reader reaches the end,
66	/// stops, or drops it, and its writer finishes, resets, or drops it. `None` grants credit
67	/// without limit.
68	pub max_concurrent_bi_streams: Option<usize>,
69	/// How long each stream message and finish takes to reach its reader, on the ambient
70	/// clock. Zero delivers at once.
71	pub latency: Duration,
72}
73
74impl Default for Config {
75	/// A 1 MiB stream buffer: about a QUIC stream's receive window (quinn's is 1.25 MB), so
76	/// a writer pends about where it would against a zero-latency QUIC peer.
77	fn default() -> Self {
78		Self {
79			stream_buffer: 1024 * 1024,
80			protocol: None,
81			max_concurrent_uni_streams: None,
82			max_concurrent_bi_streams: None,
83			latency: Duration::ZERO,
84		}
85	}
86}
87
88/// Create two connected sessions: streams one opens, the other accepts.
89pub fn pair(config: Config) -> (Session, Session) {
90	let conn = Arc::new(Conn {
91		close: Default::default(),
92		incoming: [Incoming::default(), Incoming::default()],
93		config,
94	});
95
96	let side = |local| Session {
97		side: Arc::new(Side {
98			conn: conn.clone(),
99			local,
100		}),
101	};
102
103	(side(0), side(1))
104}
105
106/// A transport failure: a session close, or a stream's reset or stop.
107#[derive(Clone, Debug, thiserror::Error)]
108#[non_exhaustive]
109pub enum Error {
110	/// Either side closed the session, or every handle to one side dropped.
111	#[error("session closed: code={code} reason={reason}")]
112	Session {
113		/// The application close code.
114		code: u32,
115		/// The application close reason.
116		reason: String,
117	},
118
119	/// The peer reset the stream with this code.
120	#[error("stream reset: code={0}")]
121	Reset(u32),
122
123	/// The peer stopped reading the stream with this code.
124	#[error("stream stopped: code={0}")]
125	Stopped(u32),
126
127	/// This side already finished, reset, or stopped the stream.
128	#[error("stream closed")]
129	Closed,
130}
131
132impl super::Error for Error {
133	fn session_error(&self) -> Option<(u32, String)> {
134		match self {
135			Self::Session { code, reason } => Some((*code, reason.clone())),
136			_ => None,
137		}
138	}
139
140	fn stream_error(&self) -> Option<u32> {
141		match self {
142			Self::Reset(code) | Self::Stopped(code) => Some(*code),
143			_ => None,
144		}
145	}
146}
147
148/// The close both sides see: set once, by whichever side closes first.
149type Close = kio::Shared<Option<(u32, String)>>;
150
151/// Poll for the session close, registering `waiter` until it happens.
152fn poll_close(close: &Close, waiter: &kio::Waiter) -> Poll<Error> {
153	let close = ready!(close.poll(waiter, |close| match close.is_some() {
154		true => Poll::Ready(()),
155		false => Poll::Pending,
156	}));
157	let (code, reason) = close.as_ref().expect("closed").clone();
158	Poll::Ready(Error::Session { code, reason })
159}
160
161/// The session close, if it happened.
162fn closed(close: &Close) -> Option<Error> {
163	let (code, reason) = close.read().as_ref()?.clone();
164	Some(Error::Session { code, reason })
165}
166
167/// State shared by both sides of a pair.
168struct Conn {
169	config: Config,
170	close: Close,
171	/// What each side has yet to accept.
172	incoming: [Incoming; 2],
173}
174
175impl Conn {
176	fn close(&self, code: u32, reason: &str) {
177		let mut close = self.close.lock();
178		if close.is_none() {
179			*close = Some((code, reason.to_string()));
180		}
181	}
182
183	/// A one-way stream, whose halves hold `send` and `recv` until each is done.
184	fn stream(&self, send: Option<Credit>, recv: Option<Credit>) -> (SendStream, RecvStream) {
185		let channel = kio::Shared::<Channel>::default();
186		let writer = SendStream {
187			channel: channel.clone(),
188			close: self.close.clone(),
189			buffer: self.config.stream_buffer,
190			latency: self.config.latency,
191			done: false,
192			credit: send,
193		};
194		let reader = poll::Buffered::new(Chunks {
195			channel,
196			close: self.close.clone(),
197			stopped: false,
198			credit: recv,
199			landing: None,
200		});
201		(writer, reader)
202	}
203}
204
205/// One open stream's place in its opener's credit, returned once every half holding it is
206/// done.
207type Credit = Arc<Opened>;
208
209/// The streams one side has open toward its peer in one direction.
210#[derive(Default)]
211struct Open {
212	count: usize,
213}
214
215/// Counted in an open-stream total until dropped.
216struct Opened(kio::Shared<Open>);
217
218impl Drop for Opened {
219	fn drop(&mut self) {
220		let mut open = self.0.lock();
221		open.count -= 1;
222	}
223}
224
225/// Take one stream credit of `max` from `open`, pending until the peer is done with one.
226fn poll_credit(
227	open: &kio::Shared<Open>,
228	max: Option<usize>,
229	close: &Close,
230	waiter: &kio::Waiter,
231) -> Poll<Result<Option<Credit>, Error>> {
232	let Some(max) = max else {
233		return Poll::Ready(Ok(None));
234	};
235	// Check the close first, so a credit granted before it is still taken below.
236	let closed = poll_close(close, waiter);
237	let Poll::Ready(mut taken) = open.poll(waiter, |open| {
238		if open.count < max {
239			return Poll::Ready(());
240		}
241		Poll::Pending
242	}) else {
243		return closed.map(Err);
244	};
245	taken.count += 1;
246	Poll::Ready(Ok(Some(Arc::new(Opened(open.clone())))))
247}
248
249/// Streams and datagrams one side has yet to accept.
250struct Incoming {
251	uni: kio::Queue<RecvStream>,
252	/// The uni streams toward this side still open, against [`Config::max_concurrent_uni_streams`].
253	uni_open: kio::Shared<Open>,
254	bi: kio::Queue<(SendStream, RecvStream)>,
255	/// The bidi streams toward this side still open, against [`Config::max_concurrent_bi_streams`].
256	bi_open: kio::Shared<Open>,
257	datagrams: kio::Queue<Bytes>,
258}
259
260impl Default for Incoming {
261	fn default() -> Self {
262		Self {
263			uni: kio::Queue::new(),
264			uni_open: Default::default(),
265			bi: kio::Queue::new(),
266			bi_open: Default::default(),
267			datagrams: kio::Queue::bounded(DATAGRAM_QUEUE),
268		}
269	}
270}
271
272impl Incoming {
273	/// Drop everything queued and refuse more, once nothing can accept it.
274	fn close(&self) {
275		self.uni.close();
276		self.bi.close();
277		self.datagrams.close();
278		while let Ok(Some(_)) = self.uni.try_pop() {}
279		while let Ok(Some(_)) = self.bi.try_pop() {}
280		while let Ok(Some(_)) = self.datagrams.try_pop() {}
281	}
282}
283
284/// One end of a pair. Dropping every clone closes the session with code 0, as QUIC
285/// closes an abandoned connection.
286struct Side {
287	conn: Arc<Conn>,
288	/// This side's index; the peer is `1 - local`.
289	local: usize,
290}
291
292impl Side {
293	fn incoming(&self) -> &Incoming {
294		&self.conn.incoming[self.local]
295	}
296
297	fn outgoing(&self) -> &Incoming {
298		&self.conn.incoming[1 - self.local]
299	}
300}
301
302impl Drop for Side {
303	fn drop(&mut self) {
304		self.conn.close(0, "");
305		// Queued streams would otherwise wait for an accept that can never come.
306		self.incoming().close();
307	}
308}
309
310/// One side of an in-memory session, created by [`pair`].
311#[derive(Clone)]
312pub struct Session {
313	side: Arc<Side>,
314}
315
316impl Session {
317	/// A handle that closes this session without keeping it open, as a cut link would.
318	pub fn closer(&self) -> Closer {
319		Closer {
320			conn: self.side.conn.clone(),
321		}
322	}
323
324	fn conn(&self) -> &Conn {
325		&self.side.conn
326	}
327
328	/// Pop from an incoming queue, failing with the close once it is empty.
329	fn poll_accept<T>(queue: &kio::Queue<T>, close: &Close, waiter: &kio::Waiter) -> Poll<Result<T, Error>> {
330		// Check the close first, so anything queued before it is still handed out below.
331		let closed = poll_close(close, waiter);
332		if let Poll::Ready(Ok(item)) = queue.poll_pop(waiter) {
333			return Poll::Ready(Ok(item));
334		}
335		closed.map(Err)
336	}
337
338	/// Hand `item` to the peer's `queue`, unless the session closed.
339	fn open<T>(&self, queue: &kio::Queue<T>, item: T) -> Result<(), Error> {
340		if let Some(err) = closed(&self.conn().close) {
341			return Err(err);
342		}
343		// The queue only closes once the peer is gone, which closed the session first.
344		queue
345			.try_push(item)
346			.map_err(|_| closed(&self.conn().close).expect("peer dropped"))
347	}
348}
349
350/// Closes a [`Session`] from outside it, holding neither side open: the session still
351/// closes once both of its handles drop.
352#[derive(Clone)]
353pub struct Closer {
354	conn: Arc<Conn>,
355}
356
357impl Closer {
358	/// Close the session for both sides, unless it already closed.
359	pub fn close(&self, code: u32, reason: &str) {
360		self.conn.close(code, reason);
361	}
362
363	/// Whether the session has closed, by either side or by this handle.
364	pub fn is_closed(&self) -> bool {
365		self.conn.close.read().is_some()
366	}
367}
368
369/// What one side of a pair still holds, read without keeping it alive, for the session fuzz
370/// target's leak check.
371#[cfg(all(feature = "async", any(test, feature = "fuzz")))]
372pub(crate) struct Held {
373	side: std::sync::Weak<Side>,
374	conn: Arc<Conn>,
375	local: usize,
376}
377
378#[cfg(all(feature = "async", any(test, feature = "fuzz")))]
379impl Held {
380	/// Whether any handle to this side's session is alive.
381	pub(crate) fn session(&self) -> bool {
382		self.side.strong_count() > 0
383	}
384
385	/// Streams the peer opened toward this side that this side is not done with, counted only
386	/// under [`Config::max_concurrent_uni_streams`] and [`Config::max_concurrent_bi_streams`].
387	pub(crate) fn streams(&self) -> usize {
388		let incoming = &self.conn.incoming[self.local];
389		incoming.uni_open.read().count + incoming.bi_open.read().count
390	}
391}
392
393#[cfg(all(feature = "async", any(test, feature = "fuzz")))]
394impl Session {
395	/// Watch what this side holds; see [`Held`].
396	pub(crate) fn held(&self) -> Held {
397		Held {
398			side: Arc::downgrade(&self.side),
399			conn: self.side.conn.clone(),
400			local: self.side.local,
401		}
402	}
403}
404
405impl poll::Session for Session {
406	type SendStream = SendStream;
407	type RecvStream = RecvStream;
408	type Error = Error;
409
410	fn poll_accept_uni(&self, waiter: &kio::Waiter) -> Poll<Result<RecvStream, Error>> {
411		Self::poll_accept(&self.side.incoming().uni, &self.side.conn.close, waiter)
412	}
413
414	fn poll_accept_bi(&self, waiter: &kio::Waiter) -> Poll<Result<(SendStream, RecvStream), Error>> {
415		Self::poll_accept(&self.side.incoming().bi, &self.side.conn.close, waiter)
416	}
417
418	fn poll_open_uni(
419		&self,
420		waiter: &kio::Waiter,
421		_: poll::SendOptions<'_, poll::Ungrouped>,
422	) -> Poll<Result<SendStream, Error>> {
423		let outgoing = self.side.outgoing();
424		let max = self.conn().config.max_concurrent_uni_streams;
425		let credit = ready!(poll_credit(&outgoing.uni_open, max, &self.side.conn.close, waiter))?;
426		let (send, recv) = self.conn().stream(None, credit);
427		Poll::Ready(self.open(&outgoing.uni, recv).map(|()| send))
428	}
429
430	fn poll_open_bi(
431		&self,
432		waiter: &kio::Waiter,
433		_: poll::SendOptions<'_, poll::Ungrouped>,
434	) -> Poll<Result<(SendStream, RecvStream), Error>> {
435		let outgoing = self.side.outgoing();
436		let max = self.conn().config.max_concurrent_bi_streams;
437		// The peer's halves both hold the credit, so it returns once the peer is done with both.
438		let credit = ready!(poll_credit(&outgoing.bi_open, max, &self.side.conn.close, waiter))?;
439		let (send, peer_recv) = self.conn().stream(None, credit.clone());
440		let (peer_send, recv) = self.conn().stream(credit, None);
441		let opened = self.open(&outgoing.bi, (peer_send, peer_recv));
442		Poll::Ready(opened.map(|()| (send, recv)))
443	}
444
445	fn send_group(&self, _: i64) -> Option<poll::Ungrouped> {
446		None
447	}
448
449	fn send_datagram(&self, payload: Bytes, _: poll::SendOptions<'_, poll::Ungrouped>) -> Result<(), Error> {
450		if let Some(err) = closed(&self.conn().close) {
451			return Err(err);
452		}
453		// An oversized datagram, or one the peer has no room for, is lost as on a network.
454		if payload.len() <= MAX_DATAGRAM_SIZE {
455			let _ = self.side.outgoing().datagrams.try_push(payload);
456		}
457		Ok(())
458	}
459
460	fn poll_recv_datagram(&self, waiter: &kio::Waiter) -> Poll<Result<Bytes, Error>> {
461		Self::poll_accept(&self.side.incoming().datagrams, &self.side.conn.close, waiter)
462	}
463
464	fn max_datagram_size(&self) -> usize {
465		MAX_DATAGRAM_SIZE
466	}
467
468	fn protocol(&self) -> Option<&str> {
469		self.conn().config.protocol.as_deref()
470	}
471
472	fn address(&self) -> super::Address {
473		// Like raw QUIC, the pair has no request URI, so the target travels in SETUP.
474		super::Address::Setup
475	}
476
477	fn close(&self, code: u32, reason: &str) {
478		self.conn().close(code, reason);
479	}
480
481	fn poll_closed(&self, waiter: &kio::Waiter) -> Poll<Error> {
482		poll_close(&self.side.conn.close, waiter)
483	}
484
485	/// Streams share no connection window, and one holds at most its buffer.
486	fn receive_window(&self) -> Option<super::ReceiveWindow> {
487		Some(super::ReceiveWindow::new(None, self.conn().config.stream_buffer as u64))
488	}
489
490	/// A reset queues behind the prefix it keeps, which the reader still drains.
491	fn reliable_reset(&self) -> bool {
492		true
493	}
494}
495
496/// One direction of a stream: the messages its writer queued for its reader.
497#[derive(Default)]
498struct Channel {
499	messages: VecDeque<Message>,
500	/// The bytes in `messages`.
501	queued: usize,
502	/// The bytes the writer queued, which its offsets count.
503	written: u64,
504	/// The bytes the reader took, which stand in for acknowledged ones.
505	taken: u64,
506	/// How the channel closed, once it has.
507	end: Option<End>,
508	/// When a finish reaches the reader under [`Config::latency`], until the reader
509	/// takes it: the writer counts it acknowledged only then.
510	finished: Option<kio::clock::Instant>,
511}
512
513/// One write, and when it reaches the reader under [`Config::latency`].
514struct Message {
515	bytes: Bytes,
516	lands: Option<kio::clock::Instant>,
517}
518
519/// When something a writer sent `latency` ago reaches the reader: `None` at once.
520fn landing(latency: Duration) -> Option<kio::clock::Instant> {
521	(!latency.is_zero()).then(|| kio::clock::now().saturating_add(latency))
522}
523
524#[derive(Clone, Copy)]
525enum End {
526	/// The writer finished: the reader gets what is queued, then the end of the stream.
527	Fin,
528	/// The writer reset the stream with this code.
529	Reset(u32),
530	/// The reader stopped the stream with this code.
531	Stop(u32),
532}
533
534impl Channel {
535	/// Whether a read would return now: a queued message or the end.
536	fn readable(&self) -> Poll<()> {
537		match !self.messages.is_empty() || self.end.is_some() {
538			true => Poll::Ready(()),
539			false => Poll::Pending,
540		}
541	}
542
543	/// When the next thing the reader takes lands, if it is still in flight.
544	fn in_flight(&self) -> Option<kio::clock::Instant> {
545		let lands = match self.messages.front() {
546			Some(message) => message.lands,
547			None if matches!(self.end, Some(End::Fin)) => self.finished,
548			None => None,
549		}?;
550		(lands > kio::clock::now()).then_some(lands)
551	}
552
553	/// Close with a reset or stop code and drop what is queued. An earlier end stands,
554	/// unless it was a finish the reader has not fully read.
555	fn abort(&mut self, end: End) {
556		self.abort_at(0, end);
557	}
558
559	/// [`Self::abort`], but keep the bytes before `offset` queued for the reader, unless a
560	/// stop already said it reads no more.
561	fn abort_at(&mut self, offset: u64, end: End) {
562		if self.end.is_none() || !self.messages.is_empty() {
563			self.end = Some(end);
564		}
565		let mut keep = match self.end {
566			Some(End::Stop(_)) => 0,
567			_ => offset.saturating_sub(self.taken),
568		};
569		self.messages.retain_mut(|message| {
570			let len = message.bytes.len() as u64;
571			let kept = len.min(keep);
572			message.bytes.truncate(kept as usize);
573			keep -= kept;
574			kept > 0
575		});
576		self.queued = self.messages.iter().map(|message| message.bytes.len()).sum();
577		// Nothing is left in flight for the writer to wait on.
578		self.finished = None;
579	}
580
581	/// Whether the reader took every byte before `offset`, which stands in for an
582	/// acknowledgement, failing once a reset or stop means it never will.
583	fn acked(&self, offset: u64) -> Poll<Result<(), Error>> {
584		if offset <= self.taken {
585			return Poll::Ready(Ok(()));
586		}
587		match self.end {
588			// The bytes a reset still delivers wait for the reader.
589			Some(End::Reset(_)) if offset <= self.taken + self.queued as u64 => Poll::Pending,
590			Some(End::Reset(_)) => Poll::Ready(Err(Error::Closed)),
591			Some(End::Stop(code)) => Poll::Ready(Err(Error::Stopped(code))),
592			_ => Poll::Pending,
593		}
594	}
595
596	/// How the writer sees the channel close: reset, stopped, or finished and drained.
597	fn sent(&self) -> Poll<Result<(), Error>> {
598		match self.end {
599			Some(End::Fin) if self.messages.is_empty() && self.finished.is_none() => Poll::Ready(Ok(())),
600			Some(End::Reset(_)) => Poll::Ready(Ok(())),
601			Some(End::Stop(code)) => Poll::Ready(Err(Error::Stopped(code))),
602			_ => Poll::Pending,
603		}
604	}
605}
606
607/// The writing half of an in-memory stream.
608pub struct SendStream {
609	channel: kio::Shared<Channel>,
610	close: Close,
611	buffer: usize,
612	/// See [`Config::latency`].
613	latency: Duration,
614	/// This side finished or reset the stream.
615	done: bool,
616	/// The credit of a bidi stream the peer opened, held until this side is done.
617	credit: Option<Credit>,
618}
619
620impl poll::SendStream for SendStream {
621	type Error = Error;
622	type Group = crate::transport::poll::Ungrouped;
623	type Offset = u64;
624
625	fn offset(&self) -> u64 {
626		self.channel.lock().written
627	}
628
629	/// Delivered once the reader took every byte before `offset`, which stands in for an
630	/// acknowledgement as it does for [`poll_closed`](poll::SendStream::poll_closed).
631	fn poll_acked(&self, waiter: &kio::Waiter, offset: &u64) -> Poll<Result<(), Error>> {
632		// Check the close first, so bytes taken before it still count below.
633		let closed = poll_close(&self.close, waiter);
634		if let Poll::Ready(channel) = self.channel.poll(waiter, |channel| channel.acked(*offset).map(drop)) {
635			return channel.acked(*offset);
636		}
637		closed.map(Err)
638	}
639
640	fn poll_write(&mut self, waiter: &kio::Waiter, buf: &[u8]) -> Poll<Result<usize, Error>> {
641		let mut buf = buf;
642		self.poll_write_buf(waiter, &mut buf)
643	}
644
645	/// Queue all of `buf` as one message, waiting while the channel is full.
646	fn poll_write_buf<B: Buf>(&mut self, waiter: &kio::Waiter, buf: &mut B) -> Poll<Result<usize, Error>> {
647		if self.done {
648			return Poll::Ready(Err(Error::Closed));
649		}
650		if !buf.has_remaining() {
651			return Poll::Ready(Ok(0));
652		}
653
654		// Peek at the close rather than register on it: only a write that parks waits for it.
655		if let Some(err) = closed(&self.close) {
656			return Poll::Ready(Err(err));
657		}
658
659		let buffer = self.buffer;
660		let Poll::Ready(mut channel) = self.channel.poll(waiter, |channel| {
661			match channel.end.is_some() || channel.messages.is_empty() || channel.queued < buffer {
662				true => Poll::Ready(()),
663				false => Poll::Pending,
664			}
665		}) else {
666			return poll_close(&self.close, waiter).map(Err);
667		};
668		if let Some(End::Stop(code)) = channel.end {
669			return Poll::Ready(Err(Error::Stopped(code)));
670		}
671
672		// Take ownership rather than copy: free for a `Bytes` source.
673		let size = buf.remaining();
674		channel.messages.push_back(Message {
675			bytes: buf.copy_to_bytes(size),
676			lands: landing(self.latency),
677		});
678		channel.queued += size;
679		channel.written += size as u64;
680
681		Poll::Ready(Ok(size))
682	}
683
684	/// Ignored: with no link to share, there is nothing to schedule.
685	fn set_priority(&mut self, _order: i64) {}
686
687	fn set_group(&mut self, group: &Self::Group) {
688		match *group {}
689	}
690
691	fn finish(&mut self) -> Result<(), Error> {
692		if self.done {
693			return Err(Error::Closed);
694		}
695		if let Some(err) = closed(&self.close) {
696			return Err(err);
697		}
698		let mut channel = self.channel.lock();
699		if let Some(End::Stop(code)) = channel.end {
700			return Err(Error::Stopped(code));
701		}
702		channel.end = Some(End::Fin);
703		channel.finished = landing(self.latency);
704		drop(channel);
705		self.done = true;
706		self.credit = None;
707		Ok(())
708	}
709
710	fn reset(&mut self, code: u32) {
711		self.reset_at(&0, code);
712	}
713
714	fn reset_at(&mut self, offset: &u64, code: u32) {
715		if std::mem::replace(&mut self.done, true) {
716			return;
717		}
718		// A closed session leaves its streams as they were, so the peer drains them. The
719		// close is checked under the channel lock so a concurrent close can't land between.
720		let mut channel = self.channel.lock();
721		if closed(&self.close).is_none() {
722			channel.abort_at(*offset, End::Reset(code));
723		}
724		drop(channel);
725		self.credit = None;
726	}
727
728	/// Ready once this side reset the stream, the reader stopped it, or the reader took
729	/// every message of a finished stream and, under latency, the finish. That stands in for a FIN acknowledgement, so a
730	/// writer that waits for it before closing the session knows the peer has the data.
731	fn poll_closed(&self, waiter: &kio::Waiter) -> Poll<Result<(), Error>> {
732		// Check the close first, so a drain that happened before it is still seen below.
733		let closed = poll_close(&self.close, waiter);
734		if let Poll::Ready(channel) = self.channel.poll(waiter, |channel| channel.sent().map(drop)) {
735			return channel.sent();
736		}
737		closed.map(Err)
738	}
739}
740
741impl Drop for SendStream {
742	/// Reset rather than finish, so a writer that went away is never read as complete.
743	fn drop(&mut self) {
744		poll::SendStream::reset(self, 0);
745	}
746}
747
748/// The reading half of an in-memory stream, leased through [`poll::Buffered`].
749pub type RecvStream = poll::Buffered<Chunks>;
750
751/// The plain reads of an in-memory stream.
752pub struct Chunks {
753	channel: kio::Shared<Channel>,
754	close: Close,
755	/// This side stopped the stream.
756	stopped: bool,
757	/// The open-stream count this stream holds a credit in, until it is done.
758	credit: Option<Credit>,
759	/// Armed while the next message or the finish is still in flight.
760	landing: Option<Pin<Box<kio::clock::Sleep>>>,
761}
762
763impl Chunks {
764	/// Let go of this stream's credit, returned to its writer's side once both halves have.
765	fn release(&mut self) {
766		self.credit = None;
767	}
768}
769
770impl poll::Chunks for Chunks {
771	type Error = Error;
772
773	/// Pop the next message, or split off its first `max` bytes.
774	fn poll_read_chunk(&mut self, waiter: &kio::Waiter, max: usize) -> Poll<Result<Option<Bytes>, Error>> {
775		if self.stopped {
776			return Poll::Ready(Err(Error::Closed));
777		}
778		if max == 0 {
779			return Poll::Ready(Ok(Some(Bytes::new())));
780		}
781
782		// Only a read that parks registers on the close, so a ready read costs one lock.
783		let mut channel = match self.channel.poll(waiter, |channel| channel.readable()) {
784			Poll::Ready(channel) => channel,
785			Poll::Pending => {
786				let err = ready!(poll_close(&self.close, waiter));
787				// Queued messages drain first, so look again: one may have landed before the close.
788				match self.channel.poll(waiter, |channel| channel.readable()) {
789					Poll::Ready(channel) => channel,
790					Poll::Pending => return Poll::Ready(Err(err)),
791				}
792			}
793		};
794
795		if let Some(lands) = channel.in_flight() {
796			drop(channel);
797			// Wait on the channel too: a reset or stop drops what is in flight, and the
798			// reader sees it at once rather than at the discarded message's landing.
799			let changed = |channel: &kio::Ref<'_, Channel>| match channel.in_flight() {
800				Some(_) => Poll::Pending,
801				None => Poll::Ready(()),
802			};
803			if self.channel.poll(waiter, changed).is_ready() {
804				return self.poll_read_chunk(waiter, max);
805			}
806			let landing = match &mut self.landing {
807				Some(landing) => {
808					// A reset wakes the task parked on the sleep, so resetting to the
809					// same instant on every poll would spin without time advancing.
810					if landing.deadline() != lands {
811						landing.as_mut().reset(lands);
812					}
813					landing
814				}
815				None => self.landing.insert(Box::pin(kio::clock::sleep_until(lands))),
816			};
817			ready!(waiter.poll_future(landing.as_mut()));
818			return self.poll_read_chunk(waiter, max);
819		}
820
821		let Some(front) = channel.messages.front_mut() else {
822			let end = channel.end.expect("checked above");
823			if matches!(end, End::Fin) && channel.finished.is_some() {
824				// The finish landed: tell the writer, which waits on it as an acknowledgement.
825				channel.finished = None;
826			}
827			drop(channel);
828			self.release();
829			return Poll::Ready(match end {
830				End::Fin => Ok(None),
831				End::Reset(code) => Err(Error::Reset(code)),
832				End::Stop(_) => Err(Error::Closed),
833			});
834		};
835		let chunk = match front.bytes.len() > max {
836			true => front.bytes.split_to(max),
837			false => channel.messages.pop_front().expect("front exists").bytes,
838		};
839		channel.queued -= chunk.len();
840		channel.taken += chunk.len() as u64;
841
842		Poll::Ready(Ok(Some(chunk)))
843	}
844
845	fn stop(&mut self, code: u32) {
846		if std::mem::replace(&mut self.stopped, true) {
847			return;
848		}
849		// A closed session leaves its streams as they were; checked under the channel lock,
850		// as in `reset`.
851		let mut channel = self.channel.lock();
852		if closed(&self.close).is_none() {
853			channel.abort(End::Stop(code));
854		}
855		drop(channel);
856		self.release();
857	}
858
859	fn poll_reset(&mut self, waiter: &kio::Waiter) -> Poll<Error> {
860		if self.stopped {
861			return Poll::Ready(Error::Closed);
862		}
863		if let Poll::Ready(err) = poll_close(&self.close, waiter) {
864			return Poll::Ready(err);
865		}
866		// A reset that still delivers bytes fails only once they were read, as QUIC's does.
867		let channel = ready!(self.channel.poll(waiter, |channel| match channel.end {
868			Some(End::Reset(_)) if channel.messages.is_empty() => Poll::Ready(()),
869			_ => Poll::Pending,
870		}));
871		let Some(End::Reset(code)) = channel.end else {
872			unreachable!("checked above")
873		};
874		Poll::Ready(Error::Reset(code))
875	}
876}
877
878impl Drop for Chunks {
879	/// Stop, so the writer learns nobody reads and the queued messages are freed.
880	fn drop(&mut self) {
881		poll::Chunks::stop(self, 0);
882	}
883}
884
885#[cfg(test)]
886mod tests {
887	use std::{
888		sync::atomic::{AtomicUsize, Ordering},
889		task::{Wake, Waker},
890	};
891
892	use super::*;
893	use poll::{RecvStream as _, SendStream as _, Session as _};
894
895	/// Counts its wakes.
896	#[derive(Default)]
897	struct Count(AtomicUsize);
898
899	impl Wake for Count {
900		fn wake(self: Arc<Self>) {
901			self.0.fetch_add(1, Ordering::Relaxed);
902		}
903	}
904
905	fn noop() -> kio::Waiter {
906		kio::Waiter::noop()
907	}
908
909	fn ready<T>(poll: Poll<T>) -> T {
910		match poll {
911			Poll::Ready(value) => value,
912			Poll::Pending => panic!("pending"),
913		}
914	}
915
916	fn buffer(stream_buffer: usize) -> Config {
917		Config {
918			stream_buffer,
919			..Default::default()
920		}
921	}
922
923	fn uni(a: &Session, b: &Session) -> (SendStream, RecvStream) {
924		let send = ready(a.poll_open_uni(&noop(), Default::default())).unwrap();
925		let recv = ready(b.poll_accept_uni(&noop())).unwrap();
926		(send, recv)
927	}
928
929	fn write(send: &mut SendStream, chunk: &Bytes) -> Poll<Result<usize, Error>> {
930		send.poll_write_buf(&noop(), &mut chunk.clone())
931	}
932
933	/// Below the lease buffering, so each read sees the channel itself.
934	fn read(recv: &mut RecvStream, max: usize) -> Poll<Result<Option<Bytes>, Error>> {
935		poll::Chunks::poll_read_chunk(recv.get_mut(), &noop(), max)
936	}
937
938	fn text(chunk: Poll<Result<Option<Bytes>, Error>>) -> Bytes {
939		ready(chunk).unwrap().unwrap()
940	}
941
942	#[test]
943	fn bounds() {
944		fn boxable<S: poll::Boxable>() {}
945		boxable::<Session>();
946	}
947
948	#[test]
949	fn closer_cuts_without_holding_open() {
950		// A closer closes the session for both sides.
951		let (a, b) = pair(Config::default());
952		let closer = a.closer();
953		closer.close(7, "cut");
954		assert!(closer.is_closed());
955		assert!(matches!(ready(b.poll_closed(&noop())), Error::Session { code: 7, .. }));
956
957		// A side dropped closes the session even while a closer is held.
958		let (a, b) = pair(Config::default());
959		let closer = b.closer();
960		drop(b);
961		assert!(closer.is_closed());
962		assert!(a.poll_closed(&noop()).is_ready());
963	}
964
965	#[test]
966	fn one_write_is_one_read() {
967		let (a, b) = pair(Config::default());
968		let (mut send, mut recv) = uni(&a, &b);
969
970		let first = Bytes::from(vec![1u8; 4096]);
971		let second = Bytes::from_static(b"second");
972		assert_eq!(ready(write(&mut send, &first)).unwrap(), first.len());
973		assert_eq!(ready(write(&mut send, &second)).unwrap(), second.len());
974
975		// Each write is read back as one message, backed by the written allocation.
976		let chunk = text(read(&mut recv, usize::MAX));
977		assert_eq!(chunk.as_ptr(), first.as_ptr());
978		assert_eq!(chunk.len(), first.len());
979
980		// A smaller read splits the message, still without a copy.
981		assert_eq!(text(read(&mut recv, 2)).as_ptr(), second.as_ptr());
982		assert_eq!(text(read(&mut recv, usize::MAX)), "cond");
983
984		send.finish().unwrap();
985		assert_eq!(ready(read(&mut recv, usize::MAX)).unwrap(), None);
986		assert_eq!(ready(read(&mut recv, usize::MAX)).unwrap(), None);
987	}
988
989	#[test]
990	fn full_channel_pends_writer_until_read() {
991		let (a, b) = pair(buffer(8));
992		let (mut send, mut recv) = uni(&a, &b);
993		let (mut other, mut other_recv) = uni(&a, &b);
994
995		// A write is never split, so one larger than the buffer still lands whole.
996		let large = Bytes::from_static(b"0123456789");
997		assert_eq!(ready(write(&mut send, &large)).unwrap(), 10);
998
999		let count = Arc::new(Count::default());
1000		let waiter = kio::Waiter::new(Waker::from(count.clone()));
1001		let mut next = Bytes::from_static(b"x");
1002		assert!(send.poll_write_buf(&waiter, &mut next).is_pending());
1003		assert_eq!(next, "x");
1004
1005		// Only that stream is full.
1006		assert_eq!(ready(write(&mut other, &Bytes::from_static(b"y"))).unwrap(), 1);
1007		assert_eq!(text(read(&mut other_recv, usize::MAX)), "y");
1008
1009		// A partial read leaves the channel full; reading the rest wakes the writer.
1010		assert_eq!(text(read(&mut recv, 2)), "01");
1011		assert!(write(&mut send, &next).is_pending());
1012		assert_eq!(text(read(&mut recv, usize::MAX)), "23456789");
1013		assert!(count.0.load(Ordering::Relaxed) > 0);
1014		assert_eq!(ready(send.poll_write_buf(&noop(), &mut next)).unwrap(), 1);
1015	}
1016
1017	#[test]
1018	fn zero_buffer_holds_one_message() {
1019		let (a, b) = pair(buffer(0));
1020		let (mut send, mut recv) = uni(&a, &b);
1021
1022		assert_eq!(ready(write(&mut send, &Bytes::from_static(b"one"))).unwrap(), 3);
1023		assert!(write(&mut send, &Bytes::from_static(b"two")).is_pending());
1024		assert_eq!(text(read(&mut recv, usize::MAX)), "one");
1025		assert_eq!(ready(write(&mut send, &Bytes::from_static(b"two"))).unwrap(), 3);
1026	}
1027
1028	#[test]
1029	fn uni_credit_pends_opens_until_a_stream_is_done() {
1030		let (a, b) = pair(Config {
1031			max_concurrent_uni_streams: Some(2),
1032			..Default::default()
1033		});
1034		let open = |a: &Session, waiter: &kio::Waiter| a.poll_open_uni(waiter, Default::default());
1035
1036		// Streams the peer has not accepted yet hold credit too.
1037		let mut finished = ready(open(&a, &noop())).unwrap();
1038		let _reset = ready(open(&a, &noop())).unwrap();
1039		let count = Arc::new(Count::default());
1040		let waiter = kio::Waiter::new(Waker::from(count.clone()));
1041		assert!(open(&a, &waiter).is_pending());
1042		assert_eq!(count.0.load(Ordering::Relaxed), 0, "being blocked wakes nobody");
1043
1044		// Credit is per direction.
1045		let _back = ready(open(&b, &noop())).unwrap();
1046
1047		// Reading to the end returns the credit, and wakes the parked open.
1048		ready(write(&mut finished, &Bytes::from_static(b"x"))).unwrap();
1049		finished.finish().unwrap();
1050		let mut recv = ready(b.poll_accept_uni(&noop())).unwrap();
1051		assert_eq!(text(read(&mut recv, usize::MAX)), "x");
1052		assert!(open(&a, &waiter).is_pending(), "an unread FIN keeps the credit");
1053		assert_eq!(ready(read(&mut recv, usize::MAX)).unwrap(), None);
1054		assert!(count.0.load(Ordering::Relaxed) > 0);
1055		let _third = ready(open(&a, &noop())).unwrap();
1056		assert!(open(&a, &noop()).is_pending());
1057
1058		// So does dropping a stream, accepted or not.
1059		drop(recv);
1060		assert!(open(&a, &noop()).is_pending(), "the credit was returned once");
1061		drop(ready(b.poll_accept_uni(&noop())).unwrap());
1062		let _fourth = ready(open(&a, &noop())).unwrap();
1063
1064		// A parked open fails once the session closes.
1065		b.close(1, "bye");
1066		assert!(matches!(ready(open(&a, &noop())), Err(Error::Session { code: 1, .. })));
1067	}
1068
1069	/// A bidi stream holds its opener's credit until the peer is done with both halves.
1070	#[test]
1071	fn bi_credit_returns_once_the_peer_is_done_with_both_halves() {
1072		let (a, b) = pair(Config {
1073			max_concurrent_bi_streams: Some(1),
1074			..Default::default()
1075		});
1076		let open = |a: &Session, waiter: &kio::Waiter| a.poll_open_bi(waiter, Default::default());
1077
1078		let (mut send, _recv) = ready(open(&a, &noop())).unwrap();
1079		let count = Arc::new(Count::default());
1080		let waiter = kio::Waiter::new(Waker::from(count.clone()));
1081		assert!(open(&a, &waiter).is_pending());
1082
1083		// The peer reading our half to the end leaves its own half open.
1084		send.finish().unwrap();
1085		let (mut peer_send, mut peer_recv) = ready(b.poll_accept_bi(&noop())).unwrap();
1086		assert_eq!(ready(read(&mut peer_recv, usize::MAX)).unwrap(), None);
1087		assert!(open(&a, &waiter).is_pending(), "the peer still writes");
1088
1089		peer_send.finish().unwrap();
1090		assert!(count.0.load(Ordering::Relaxed) > 0);
1091		let _second = ready(open(&a, &noop())).unwrap();
1092	}
1093
1094	#[test]
1095	fn reset_drops_queued_messages() {
1096		let (a, b) = pair(buffer(8));
1097		let (mut send, mut recv) = uni(&a, &b);
1098
1099		ready(write(&mut send, &Bytes::from_static(b"01234567"))).unwrap();
1100		send.reset(7);
1101		assert!(ready(send.poll_closed(&noop())).is_ok());
1102		assert!(matches!(ready(read(&mut recv, usize::MAX)), Err(Error::Reset(7))));
1103		assert!(matches!(
1104			ready(write(&mut send, &Bytes::from_static(b"x"))),
1105			Err(Error::Closed)
1106		));
1107	}
1108
1109	/// A reset at an offset still delivers the bytes before it, and fails the reader, or a
1110	/// wait for the reset, only once they were read. A stop drops them.
1111	#[test]
1112	fn reset_at_delivers_the_prefix() {
1113		let (a, b) = pair(buffer(64));
1114		let (mut send, mut recv) = uni(&a, &b);
1115
1116		ready(write(&mut send, &Bytes::from_static(b"head"))).unwrap();
1117		ready(write(&mut send, &Bytes::from_static(b"er-body"))).unwrap();
1118		send.reset_at(&6, 7);
1119		let at = 6;
1120		assert!(send.poll_acked(&noop(), &at).is_pending(), "the prefix is still owed");
1121		assert!(poll::RecvStream::poll_reset(&mut recv, &noop()).is_pending());
1122		assert_eq!(ready(read(&mut recv, 4)).unwrap().unwrap(), "head");
1123		assert_eq!(ready(read(&mut recv, usize::MAX)).unwrap().unwrap(), "er");
1124		assert!(ready(send.poll_acked(&noop(), &at)).is_ok());
1125		assert!(matches!(ready(read(&mut recv, usize::MAX)), Err(Error::Reset(7))));
1126
1127		let (mut send, mut recv) = uni(&a, &b);
1128		ready(write(&mut send, &Bytes::from_static(b"header"))).unwrap();
1129		poll::RecvStream::stop(&mut recv, 3);
1130		send.reset_at(&6, 7);
1131		assert!(matches!(ready(send.poll_acked(&noop(), &6)), Err(Error::Stopped(3))));
1132	}
1133
1134	/// The next chunk `recv` reads, once it lands.
1135	async fn landed(recv: &mut RecvStream) -> Option<Bytes> {
1136		kio::wait(|waiter| poll::Chunks::poll_read_chunk(recv.get_mut(), waiter, usize::MAX))
1137			.await
1138			.unwrap()
1139	}
1140
1141	#[test]
1142	fn latency_delays_each_message_and_the_finish() {
1143		kio::clock::sim::run(async {
1144			const LATENCY: Duration = Duration::from_millis(10);
1145			let (a, b) = pair(Config {
1146				latency: LATENCY,
1147				..Default::default()
1148			});
1149			let (mut send, mut recv) = uni(&a, &b);
1150			let start = kio::clock::now();
1151
1152			ready(write(&mut send, &Bytes::from_static(b"one"))).unwrap();
1153			// Polling again while it is in flight must not wake the reader, or a task
1154			// re-polling its stream would spin without simulated time moving.
1155			let count = Arc::new(Count::default());
1156			let waiter = kio::Waiter::new(Waker::from(count.clone()));
1157			for _ in 0..2 {
1158				let chunk = poll::Chunks::poll_read_chunk(recv.get_mut(), &waiter, usize::MAX);
1159				assert!(chunk.is_pending(), "a message landed at once");
1160			}
1161			assert_eq!(count.0.load(Ordering::Relaxed), 0, "a re-poll woke the reader");
1162			kio::clock::sleep(LATENCY / 2).await;
1163			ready(write(&mut send, &Bytes::from_static(b"two"))).unwrap();
1164			send.finish().unwrap();
1165
1166			// Each lands its latency after it was sent, in order, and the finish last.
1167			assert_eq!(landed(&mut recv).await.unwrap(), "one");
1168			assert_eq!(start.elapsed(), LATENCY);
1169			assert_eq!(landed(&mut recv).await.unwrap(), "two");
1170			assert_eq!(start.elapsed(), LATENCY + LATENCY / 2);
1171			assert_eq!(landed(&mut recv).await, None);
1172			assert_eq!(start.elapsed(), LATENCY + LATENCY / 2);
1173		});
1174	}
1175
1176	#[test]
1177	fn a_finish_is_acknowledged_once_the_reader_takes_it() {
1178		kio::clock::sim::run(async {
1179			const LATENCY: Duration = Duration::from_millis(10);
1180			let (a, b) = pair(Config {
1181				latency: LATENCY,
1182				..Default::default()
1183			});
1184			let (mut send, mut recv) = uni(&a, &b);
1185			ready(write(&mut send, &Bytes::from_static(b"one"))).unwrap();
1186			assert_eq!(landed(&mut recv).await.unwrap(), "one");
1187
1188			// Every message is taken, but the finish is still in flight: a writer that
1189			// closed the session now would beat its finish to the reader.
1190			send.finish().unwrap();
1191			assert!(send.poll_closed(&noop()).is_pending());
1192			let start = kio::clock::now();
1193			assert_eq!(landed(&mut recv).await, None);
1194			assert_eq!(start.elapsed(), LATENCY);
1195			assert!(ready(send.poll_closed(&noop())).is_ok());
1196
1197			// A reader that stops before the finish lands leaves the writer finished.
1198			let (mut send, recv) = uni(&a, &b);
1199			send.finish().unwrap();
1200			assert!(send.poll_closed(&noop()).is_pending());
1201			drop(recv);
1202			assert!(ready(send.poll_closed(&noop())).is_ok());
1203		});
1204	}
1205
1206	#[test]
1207	fn a_reset_skips_the_latency() {
1208		kio::clock::sim::run(async {
1209			let (a, b) = pair(Config {
1210				latency: Duration::from_millis(10),
1211				..Default::default()
1212			});
1213			let (mut send, mut recv) = uni(&a, &b);
1214			let start = kio::clock::now();
1215			ready(write(&mut send, &Bytes::from_static(b"dropped"))).unwrap();
1216
1217			// A reader parked on a message in flight wakes for the reset that drops it.
1218			let count = Arc::new(Count::default());
1219			let waiter = kio::Waiter::new(Waker::from(count.clone()));
1220			assert!(poll::Chunks::poll_read_chunk(recv.get_mut(), &waiter, usize::MAX).is_pending());
1221			send.reset(2);
1222			assert!(count.0.load(Ordering::Relaxed) > 0, "the reset did not wake the reader");
1223			let read = poll::Chunks::poll_read_chunk(recv.get_mut(), &waiter, usize::MAX);
1224			assert!(matches!(ready(read), Err(Error::Reset(2))));
1225			assert_eq!(start.elapsed(), Duration::ZERO);
1226		});
1227	}
1228
1229	#[test]
1230	fn finish_closes_once_drained() {
1231		let (a, b) = pair(Config::default());
1232		let (mut send, mut recv) = uni(&a, &b);
1233
1234		ready(write(&mut send, &Bytes::from_static(b"done"))).unwrap();
1235		send.finish().unwrap();
1236		assert!(matches!(send.finish(), Err(Error::Closed)));
1237
1238		// The writer's close waits for the reader to take every message.
1239		assert!(send.poll_closed(&noop()).is_pending());
1240		assert_eq!(text(read(&mut recv, usize::MAX)), "done");
1241		assert!(ready(send.poll_closed(&noop())).is_ok());
1242		assert_eq!(ready(read(&mut recv, usize::MAX)).unwrap(), None);
1243
1244		// A reset after the finish is ignored, so the reader still gets everything.
1245		let (mut send, mut recv) = uni(&a, &b);
1246		ready(write(&mut send, &Bytes::from_static(b"kept"))).unwrap();
1247		send.finish().unwrap();
1248		send.reset(2);
1249		assert_eq!(text(read(&mut recv, usize::MAX)), "kept");
1250		assert_eq!(ready(read(&mut recv, usize::MAX)).unwrap(), None);
1251
1252		// A reader that stops after taking everything leaves the writer finished.
1253		drop(recv);
1254		assert!(ready(send.poll_closed(&noop())).is_ok());
1255
1256		// A reader that stops with messages unread fails the writer, finished or not.
1257		let (mut send, recv) = uni(&a, &b);
1258		ready(write(&mut send, &Bytes::from_static(b"unread"))).unwrap();
1259		send.finish().unwrap();
1260		drop(recv);
1261		assert!(matches!(ready(send.poll_closed(&noop())), Err(Error::Stopped(0))));
1262	}
1263
1264	/// An offset is acknowledged once the reader took every byte before it, and still is after a
1265	/// reset; the rest fails once a reset or stop means the reader never will take it.
1266	#[test]
1267	fn an_offset_is_acknowledged_once_the_reader_takes_it() {
1268		let acked = |send: &SendStream, offset: u64| send.poll_acked(&noop(), &offset);
1269		let (a, b) = pair(Config::default());
1270		let (mut send, mut recv) = uni(&a, &b);
1271		assert!(matches!(acked(&send, send.offset()), Poll::Ready(Ok(()))));
1272
1273		ready(write(&mut send, &Bytes::from_static(b"one"))).unwrap();
1274		let one = send.offset();
1275		ready(write(&mut send, &Bytes::from_static(b"two"))).unwrap();
1276		let two = send.offset();
1277		assert_eq!((one, two), (3, 6));
1278		assert!(acked(&send, one).is_pending());
1279
1280		// A waiter parked on the offset wakes once the reader takes the bytes.
1281		let count = Arc::new(Count::default());
1282		let waiter = kio::Waiter::new(Waker::from(count.clone()));
1283		assert!(send.poll_acked(&waiter, &one).is_pending());
1284		assert_eq!(text(read(&mut recv, 4)), "one");
1285		assert!(count.0.load(Ordering::Relaxed) > 0, "the read did not wake the writer");
1286		assert!(matches!(acked(&send, one), Poll::Ready(Ok(()))));
1287		assert!(acked(&send, two).is_pending());
1288
1289		send.reset(1);
1290		assert!(matches!(acked(&send, one), Poll::Ready(Ok(()))));
1291		assert!(matches!(acked(&send, two), Poll::Ready(Err(Error::Closed))));
1292
1293		let (mut send, mut recv) = uni(&a, &b);
1294		ready(write(&mut send, &Bytes::from_static(b"one"))).unwrap();
1295		recv.stop(3);
1296		assert!(matches!(
1297			acked(&send, send.offset()),
1298			Poll::Ready(Err(Error::Stopped(3)))
1299		));
1300	}
1301
1302	#[test]
1303	fn stop_fails_the_writer() {
1304		let (a, b) = pair(Config::default());
1305		let (mut send, mut recv) = uni(&a, &b);
1306
1307		ready(write(&mut send, &Bytes::from_static(b"01234567"))).unwrap();
1308		assert!(send.poll_closed(&noop()).is_pending());
1309
1310		recv.stop(3);
1311		assert!(matches!(ready(send.poll_closed(&noop())), Err(Error::Stopped(3))));
1312		assert!(matches!(
1313			ready(write(&mut send, &Bytes::from_static(b"x"))),
1314			Err(Error::Stopped(3))
1315		));
1316		assert!(matches!(send.finish(), Err(Error::Stopped(3))));
1317		assert!(matches!(ready(read(&mut recv, usize::MAX)), Err(Error::Closed)));
1318	}
1319
1320	#[test]
1321	fn drops_reset_and_stop() {
1322		let (a, b) = pair(Config::default());
1323
1324		let (send, mut recv) = uni(&a, &b);
1325		drop(send);
1326		assert!(matches!(ready(read(&mut recv, usize::MAX)), Err(Error::Reset(0))));
1327
1328		let (send, recv) = uni(&a, &b);
1329		drop(recv);
1330		assert!(matches!(ready(send.poll_closed(&noop())), Err(Error::Stopped(0))));
1331	}
1332
1333	#[test]
1334	fn bidi_streams_pair_up() {
1335		let (a, b) = pair(Config::default());
1336		let (mut a_send, mut a_recv) = ready(a.poll_open_bi(&noop(), Default::default())).unwrap();
1337		let (mut b_send, mut b_recv) = ready(b.poll_accept_bi(&noop())).unwrap();
1338
1339		ready(write(&mut a_send, &Bytes::from_static(b"ping"))).unwrap();
1340		assert_eq!(text(read(&mut b_recv, usize::MAX)), "ping");
1341		ready(write(&mut b_send, &Bytes::from_static(b"pong"))).unwrap();
1342		assert_eq!(text(read(&mut a_recv, usize::MAX)), "pong");
1343	}
1344
1345	#[test]
1346	fn close_drains_queued_messages() {
1347		let (a, b) = pair(Config {
1348			protocol: Some("moq".into()),
1349			..Default::default()
1350		});
1351		assert_eq!(b.protocol(), Some("moq"));
1352		let (mut send, mut recv) = uni(&a, &b);
1353		let (mut unfinished, mut unfinished_recv) = uni(&a, &b);
1354		let late = ready(a.poll_open_uni(&noop(), Default::default())).unwrap();
1355
1356		ready(write(&mut send, &Bytes::from_static(b"last"))).unwrap();
1357		send.finish().unwrap();
1358		ready(write(&mut unfinished, &Bytes::from_static(b"part"))).unwrap();
1359		assert!(b.poll_closed(&noop()).is_pending());
1360
1361		a.close(4, "bye");
1362		let closed = |err: Error| matches!(err, Error::Session { code: 4, ref reason } if reason == "bye");
1363		assert!(closed(ready(b.poll_closed(&noop()))));
1364		assert!(closed(
1365			ready(a.poll_open_uni(&noop(), Default::default())).err().unwrap()
1366		));
1367		assert!(closed(
1368			ready(write(&mut unfinished, &Bytes::from_static(b"x"))).unwrap_err()
1369		));
1370		// Dropping a stream after the close leaves it as it was, so it still drains.
1371		drop(send);
1372		drop(unfinished);
1373
1374		assert_eq!(text(read(&mut recv, usize::MAX)), "last");
1375		assert_eq!(ready(read(&mut recv, usize::MAX)).unwrap(), None);
1376		assert_eq!(text(read(&mut unfinished_recv, usize::MAX)), "part");
1377		assert!(closed(ready(read(&mut unfinished_recv, usize::MAX)).unwrap_err()));
1378
1379		// A stream opened before the close is still accepted.
1380		drop(late);
1381		ready(b.poll_accept_uni(&noop())).unwrap();
1382		assert!(closed(ready(b.poll_accept_uni(&noop())).err().unwrap()));
1383	}
1384
1385	/// Only a parked read or write waits on the close: one that returns at once leaves no
1386	/// registration behind, as every frame of a session pays for one.
1387	#[test]
1388	fn only_parked_streams_wait_on_the_close() {
1389		let (a, b) = pair(buffer(0));
1390		let (mut send, mut recv) = uni(&a, &b);
1391		let counted = || {
1392			let count = Arc::new(Count::default());
1393			(kio::Waiter::new(Waker::from(count.clone())), count)
1394		};
1395
1396		let (ready_write, ready_write_count) = counted();
1397		assert_eq!(
1398			ready(send.poll_write_buf(&ready_write, &mut Bytes::from_static(b"one"))).unwrap(),
1399			3
1400		);
1401		let (ready_read, ready_read_count) = counted();
1402		let chunk = ready(poll::Chunks::poll_read_chunk(recv.get_mut(), &ready_read, usize::MAX));
1403		assert_eq!(chunk.unwrap().unwrap(), "one");
1404
1405		// The channel is empty, so the read parks; refill it so the write parks too.
1406		let (parked_read, parked_read_count) = counted();
1407		assert!(poll::Chunks::poll_read_chunk(recv.get_mut(), &parked_read, usize::MAX).is_pending());
1408		let (mut other, _other_recv) = uni(&a, &b);
1409		ready(write(&mut other, &Bytes::from_static(b"two"))).unwrap();
1410		let (parked_write, parked_write_count) = counted();
1411		assert!(
1412			other
1413				.poll_write_buf(&parked_write, &mut Bytes::from_static(b"x"))
1414				.is_pending()
1415		);
1416
1417		a.close(4, "bye");
1418		assert_eq!(ready_write_count.0.load(Ordering::Relaxed), 0);
1419		assert_eq!(ready_read_count.0.load(Ordering::Relaxed), 0);
1420		assert!(parked_read_count.0.load(Ordering::Relaxed) > 0);
1421		assert!(parked_write_count.0.load(Ordering::Relaxed) > 0);
1422
1423		let closed = |err: Error| matches!(err, Error::Session { code: 4, .. });
1424		assert!(closed(ready(read(&mut recv, usize::MAX)).unwrap_err()));
1425		assert!(closed(ready(write(&mut other, &Bytes::from_static(b"x"))).unwrap_err()));
1426	}
1427
1428	#[test]
1429	fn dropping_a_side_closes() {
1430		let (a, b) = pair(Config::default());
1431		let clone = a.clone();
1432		drop(a);
1433		assert!(b.poll_closed(&noop()).is_pending());
1434		drop(clone);
1435		assert!(matches!(ready(b.poll_closed(&noop())), Error::Session { code: 0, .. }));
1436	}
1437
1438	#[test]
1439	fn datagrams() {
1440		let (a, b) = pair(Config::default());
1441		a.send_datagram(vec![0; MAX_DATAGRAM_SIZE + 1].into(), Default::default())
1442			.unwrap();
1443		for _ in 0..DATAGRAM_QUEUE {
1444			a.send_datagram("one".into(), Default::default()).unwrap();
1445		}
1446		// The peer's queue is full, so this one is lost, like the oversized one.
1447		a.send_datagram("two".into(), Default::default()).unwrap();
1448		for _ in 0..DATAGRAM_QUEUE {
1449			assert_eq!(ready(b.poll_recv_datagram(&noop())).unwrap(), "one");
1450		}
1451		assert!(b.poll_recv_datagram(&noop()).is_pending());
1452	}
1453}