Skip to main content

moq_net/
session.rs

1//! A MoQ session handle and a snapshot of its connection statistics.
2
3use std::{
4	sync::{
5		Arc,
6		atomic::{AtomicU64, Ordering},
7	},
8	task::{Poll, ready},
9	time::Duration,
10};
11
12use crate::transport::poll::Session as _;
13use crate::transport::{Error as _, Liveness, Metrics as _};
14
15use crate::{Error, SessionError, Version, auth, bandwidth, coding::StreamCodes, goaway};
16
17/// How long [`Session::close`] waits for queued data before closing anyway.
18const CLOSE_TIMEOUT: Duration = Duration::from_secs(1);
19
20/// The least time a transport this side closed gets to confirm it, before the session
21/// ends without its confirmation.
22const CLOSE_GRACE: Duration = Duration::from_millis(100);
23
24/// A close requested by a session handle, executed by the driver.
25#[derive(Clone)]
26enum Close {
27	/// Close now with this error's code.
28	Abort(Error),
29	/// Close once the protocol owes the peer nothing, or at [`CLOSE_TIMEOUT`].
30	Drain,
31}
32
33/// How the session ended, published by the driver.
34#[derive(Clone)]
35struct Ended {
36	/// The transport's terminal error, or this side's reason when it closed first.
37	err: Error,
38	/// The drain's outcome, when a drain is what closed the transport.
39	drain: Option<Result<(), Error>>,
40}
41
42/// Resolve with `read` of how the session ended, or [`kio::Closed`] once the driver dropped
43/// without publishing it.
44fn poll_ended<R>(
45	closed: &kio::Consumer<Option<Ended>>,
46	waiter: &kio::Waiter,
47	read: impl FnOnce(&Ended) -> R,
48) -> Poll<Result<R, kio::Closed>> {
49	let ended = closed.poll(waiter, |state| match &**state {
50		Some(ended) => Poll::Ready(read(ended)),
51		None => Poll::Pending,
52	});
53	ended.map(|ended| ended.map_err(|_| kio::Closed))
54}
55
56/// How this side closed the transport, shared by every clone of it.
57///
58/// Every close goes through the boxed transport, so the first one is recorded whichever
59/// task sent it, including one ending the session from inside a single request.
60#[derive(Default)]
61pub(crate) struct Closing {
62	/// The handles closed it by dropping or draining: a clean close, whatever the protocol reports.
63	local: std::sync::atomic::AtomicBool,
64	/// The first close this side sent: its code, and the error behind it when the closer had one.
65	sent: std::sync::Mutex<Option<(u32, Option<Error>)>>,
66}
67
68impl Closing {
69	/// Remember that this side closed the transport with `code`, over `cause` when known,
70	/// unless it already closed it.
71	pub(crate) fn sent(&self, code: u32, cause: Option<&Error>) {
72		let mut sent = self.sent.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
73		sent.get_or_insert_with(|| (code, cause.cloned()));
74	}
75
76	/// Whether this side closed the transport.
77	pub(crate) fn is_sent(&self) -> bool {
78		self.sent
79			.lock()
80			.unwrap_or_else(std::sync::PoisonError::into_inner)
81			.is_some()
82	}
83
84	/// Whether the handles closed the transport by dropping or draining.
85	pub(crate) fn is_local(&self) -> bool {
86		self.local.load(std::sync::atomic::Ordering::Relaxed)
87	}
88
89	/// Why this side closed the transport, reading a bare code with `version`'s registry.
90	fn cause(&self, version: Version) -> Option<Error> {
91		let sent = self.sent.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
92		let (code, cause) = sent.as_ref()?;
93		Some(
94			cause
95				.clone()
96				.unwrap_or_else(|| version.decode_session_code(*code).into()),
97		)
98	}
99}
100
101/// The stats cell shared between the driver's sampler and the handles.
102struct StatsState {
103	/// The latest sample the driver took (or the construction-time snapshot).
104	sample: Stats,
105	/// A handle read the stats since the last sample: keep sampling.
106	demanded: bool,
107}
108
109/// A snapshot of connection statistics for a [`Session`].
110///
111/// Every field is optional: availability depends on the transport backend (native QUIC
112/// reports all of them, the browser WebTransport reports few or none) and on the
113/// connection state (e.g. `estimated_send_rate` is `None` until the congestion controller
114/// has a window). `None` means "not reported", not "zero".
115#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
116#[non_exhaustive]
117pub struct Stats {
118	/// Smoothed round-trip time estimate.
119	pub rtt: Option<Duration>,
120
121	/// Estimated send bandwidth from the congestion controller.
122	pub estimated_send_rate: Option<bandwidth::Rate>,
123
124	/// Total bytes sent over the connection, including retransmissions and overhead.
125	pub bytes_sent: Option<u64>,
126
127	/// Total bytes received over the connection, including duplicates and overhead.
128	pub bytes_received: Option<u64>,
129
130	/// Total bytes lost (detected via retransmission or acknowledgement).
131	pub bytes_lost: Option<u64>,
132
133	/// Total datagrams sent.
134	pub packets_sent: Option<u64>,
135
136	/// Total datagrams received.
137	pub packets_received: Option<u64>,
138
139	/// Total datagrams detected as lost.
140	pub packets_lost: Option<u64>,
141
142	/// Total receive streams evicted because incomplete messages exhausted the receive window.
143	/// A count above zero means the receive window is too small for what the peer sends.
144	pub streams_evicted: Option<u64>,
145
146	/// Total times the sender blocked with all the peer's connection-level credit (`MAX_DATA`)
147	/// spent: an episode starts when a write blocks with every credited byte sent, and ends when
148	/// the peer grants more. A count rising while [`Self::credit_stalled`] grows means the peer
149	/// is not granting credit, rather than loss or congestion slowing the session.
150	pub credit_stalls: Option<u64>,
151
152	/// Total time the sender spent blocked on the peer's connection-level credit, across
153	/// [`Self::credit_stalls`]. A wait in progress counts up to the transport's latest step.
154	pub credit_stalled: Option<Duration>,
155
156	/// Total datagrams received for a subscription with no datagram track: one this session
157	/// doesn't know, has ended, or whose answer it hasn't received. `None` on a version without
158	/// datagrams: moq-transport and moq-lite before 05.
159	pub datagrams_unrouted: Option<u64>,
160}
161
162/// The congestion controller's view of the connection, as PROBE reports it.
163#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
164pub(crate) struct Estimate {
165	/// The congestion controller's send rate.
166	pub send_rate: Option<bandwidth::Rate>,
167	/// The smoothed round-trip time.
168	pub rtt: Option<Duration>,
169}
170
171impl Estimate {
172	/// Read the transport's current estimate.
173	pub(crate) fn read<S: crate::transport::poll::Session>(session: &S) -> Self {
174		Self::from(&snapshot(session))
175	}
176}
177
178impl From<&Stats> for Estimate {
179	fn from(stats: &Stats) -> Self {
180		Self {
181			send_rate: stats.estimated_send_rate,
182			rtt: stats.rtt,
183		}
184	}
185}
186
187/// A MoQ transport session, wrapping a WebTransport connection.
188///
189/// Returned with a [`Driver`](crate::Driver) by [`crate::Client::connect`] and
190/// [`crate::Server::accept`]. The caller must poll or spawn that driver to run
191/// the session.
192///
193/// Like every handle in this library, the lifecycle is reference counted: clones
194/// share the connection, the transport closes when the last clone drops, and
195/// [`abort`](Self::abort) closes it explicitly with an error. The handle and the
196/// driver are severed in both directions: the driver holds no `Session` clone,
197/// so running it never keeps the session alive, and the `Session`
198/// holds no transport, so the handle is `Send + Sync` whatever transport the
199/// driver uses. Everything transport-shaped (the close, the close reason,
200/// the stats sample) is relayed through the driver.
201#[derive(Clone)]
202pub struct Session {
203	/// Handle side to driver: `Some` once [`abort`](Self::abort) or
204	/// [`close`](Self::close) ran; the channel closing (the last handle
205	/// dropping) is the implicit Cancel, unless a drain was already requested.
206	close: kio::Producer<Option<Close>>,
207	/// Driver to handle side: how the transport ended.
208	closed: kio::Consumer<Option<Ended>>,
209	stats: kio::Shared<StatsState>,
210	version: Version,
211	/// What the peer's SETUP advertised, once it arrives.
212	peer_implementation: kio::Consumer<Option<Option<String>>>,
213	// Weak, so the sampler runs only while a caller holds a consumer.
214	send_bandwidth: Option<bandwidth::Weak>,
215	recv_bandwidth: Option<bandwidth::Weak>,
216	/// The registry whose reservations this session probes for. Its estimate is
217	/// unused: [`bandwidth`](Self::bandwidth) mints one per call, so holding the
218	/// session doesn't keep the sampler running.
219	bandwidth: bandwidth::Allocator,
220	/// The registry whose viewers this session sends its peer as the PROBE target.
221	viewers: bandwidth::Viewers,
222	goaway: Arc<goaway::Handle>,
223	auth: auth::Handle,
224	/// This session's side of `auth`, kept so a close the driver records before the
225	/// reconnect loop reads it still answers the connection credential.
226	link: auth::Link,
227	credential: Option<auth::Credential>,
228	/// The subscriptions and fetches the protocol tasks carry.
229	work: Work,
230	/// What [`Stats::datagrams_unrouted`] reads.
231	datagrams_unrouted: Option<Arc<AtomicU64>>,
232	/// The peer's liveness, under a keep-alive.
233	liveness: Option<kio::Consumer<Liveness>>,
234}
235
236/// Two handles are equal when they are clones of the same session.
237impl PartialEq for Session {
238	fn eq(&self, other: &Self) -> bool {
239		self.close.is_clone(&other.close)
240	}
241}
242
243impl Eq for Session {}
244
245impl std::fmt::Debug for Session {
246	fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
247		f.debug_struct("Session")
248			.field("version", &self.version())
249			.finish_non_exhaustive()
250	}
251}
252
253impl Session {
254	/// Returns the negotiated protocol version.
255	pub fn version(&self) -> Version {
256		self.version
257	}
258
259	/// The implementation the peer advertised in its SETUP, such as `moq-net-rs/0.3.10`.
260	///
261	/// Waits for the peer's SETUP, which a dialing client may not have read yet.
262	/// `None` when the peer advertised none, its version carries no SETUP (moq-lite
263	/// 01-04), or the session ended first. Peer-controlled: use it for logs and
264	/// rollout counts, never to authorize.
265	pub async fn peer_implementation(&self) -> Option<String> {
266		kio::wait(|waiter| self.poll_peer_implementation(waiter)).await
267	}
268
269	/// See [`Self::peer_implementation`].
270	fn poll_peer_implementation(&self, waiter: &kio::Waiter) -> Poll<Option<String>> {
271		// The slot closes only when the driver drops, which a caller holding a finished
272		// one never does, so the transport's end is watched too.
273		let slot = self.peer_implementation.poll(waiter, |slot| match &**slot {
274			Some(value) => Poll::Ready(value.clone()),
275			None => Poll::Pending,
276		});
277		match slot {
278			Poll::Ready(Ok(value)) => return Poll::Ready(value),
279			Poll::Ready(Err(_)) => return Poll::Ready(None),
280			Poll::Pending => {}
281		}
282		poll_ended(&self.closed, waiter, |_| ()).map(|_| None)
283	}
284
285	/// Returns a consumer for the estimated send bitrate (from the congestion controller).
286	///
287	/// Returns `None` if the QUIC backend doesn't support bandwidth estimation.
288	/// Otherwise it holds an estimate from the start, the session's first sample.
289	pub fn send_bandwidth(&self) -> Option<bandwidth::Consumer> {
290		self.send_bandwidth.as_ref().map(bandwidth::Weak::consume)
291	}
292
293	/// Divides [`send_bandwidth`](Self::send_bandwidth) among this session's senders.
294	///
295	/// The session probes up to what the reservations add up to, through its
296	/// transport's [`Probe`](crate::transport::Probe) when it has one, so reserve
297	/// here rather than on an allocator of your own. Clones share one registry: a
298	/// [`Client::with_allocator`](crate::Client::with_allocator) allocator's when the
299	/// session was dialed with one, so reservations outlive a reconnect. Reservations
300	/// report `None` when the transport has no estimate.
301	pub fn allocator(&self) -> bandwidth::Allocator {
302		self.bandwidth.with_estimate(self.send_bandwidth())
303	}
304
305	/// Returns a consumer for the estimated receive bitrate (from PROBE).
306	///
307	/// Holding the consumer requests PROBE; dropping the last one stops it.
308	/// Returns `None` if the MoQ version doesn't support PROBE (requires moq-lite-03+).
309	pub fn recv_bandwidth(&self) -> Option<bandwidth::Consumer> {
310		self.recv_bandwidth.as_ref().map(bandwidth::Weak::consume)
311	}
312
313	/// Divides [`recv_bandwidth`](Self::recv_bandwidth) among the broadcasts watched over this session.
314	///
315	/// The session sends what the viewers add up to as its PROBE target, so a peer that
316	/// advertised `Increase` probes the connection up to it. Holding a viewer requests
317	/// PROBE. Clones share one registry: a
318	/// [`Client::with_viewers`](crate::Client::with_viewers) registry's when the session
319	/// was dialed with one, so their claims outlive a reconnect, like
320	/// [`allocator`](Self::allocator)'s. Viewers taken here read this session's
321	/// estimate, and report `None` once it ends or when the version has no PROBE; take
322	/// them from the reconnecting handle (`moq_tokio::Connection::viewers`) to read
323	/// each new session's.
324	pub fn viewers(&self) -> bandwidth::Viewers {
325		self.viewers.with_estimate(self.recv_bandwidth.clone())
326	}
327
328	/// Returns a snapshot of the current connection statistics.
329	///
330	/// Cheap and non-blocking: this reads the latest sample the session's
331	/// driver took, and schedules a refresh, so periodic polling observes
332	/// fresh counters (100ms cadence), and reads the session's own counters
333	/// live. See [`Stats`] for which metrics each backend reports.
334	pub fn stats(&self) -> Stats {
335		let mut state = self.stats.lock();
336		// A read is demand: wake the sampler, but only mutate (and so wake)
337		// when the flag actually flips.
338		if !state.demanded {
339			state.demanded = true;
340		}
341		Stats {
342			datagrams_unrouted: self
343				.datagrams_unrouted
344				.as_ref()
345				.map(|count| count.load(Ordering::Relaxed)),
346			..state.sample
347		}
348	}
349
350	/// Close the transport with an explicit error, instead of waiting for the last
351	/// clone to drop. Idempotent: the first abort wins, and it cuts short a
352	/// [`close`](Self::close) still draining.
353	///
354	/// The close is executed by the session's driver, so it reaches the wire
355	/// once the runtime polls it (immediately on a live runtime).
356	pub fn abort(&self, err: Error) {
357		if let Ok(mut close) = self.close.write()
358			&& !matches!(*close, Some(Close::Abort(_)))
359		{
360			*close = Some(Close::Abort(err));
361		}
362	}
363
364	/// Close the session after draining its queued data.
365	///
366	/// Waits until every stream still serving the peer (a subscription whose track
367	/// finished, a fetch, a track info reply) has written its data and FIN and the
368	/// transport acknowledged them, then closes the transport. Lite-05 and newer, including
369	/// the default lite-06, also wait for the subscriber to receive a subscription's tail.
370	/// Older Lite versions and IETF wait only for transport ACKs. Returns
371	/// [`Error::Timeout`] if that takes longer than one second, closing anyway, or
372	/// the session's terminal error if it ended some other way first. A track that
373	/// is still live never finishes, so finish or abort tracks before closing.
374	///
375	/// Both protocols withdraw this session's announcements and wait for their
376	/// delivery.
377	pub async fn close(self) -> Result<(), Error> {
378		self.start_close();
379		// The drain outlives this handle, so dropping it cannot cut the drain short.
380		let closed = self.closed.clone();
381		drop(self);
382
383		kio::wait(|waiter| {
384			Poll::Ready(match ready!(poll_ended(&closed, waiter, Ended::clone)) {
385				Ok(ended) => ended.drain.unwrap_or(Err(ended.err)),
386				Err(kio::Closed) => Err(Error::Cancel),
387			})
388		})
389		.await
390	}
391
392	/// Block until the transport session is closed, returning the reason.
393	///
394	/// A close this side sent counts as closed once the transport confirms it, or after
395	/// three round trips (at least 100ms) without that, since a peer that is gone may never
396	/// let it; the transport keeps delivering the close in the background.
397	///
398	/// The driver keeps draining group streams already delivered to the transport
399	/// after this resolves, so keep driving it until it completes.
400	///
401	/// A clean close is [`Error::Cancel`], whichever side closed. A close code the peer
402	/// sent is otherwise decoded through the session registry (so an auth rejection arrives
403	/// as `Error::Session(SessionError::Unauthorized)`) and preserved as [`Error::Session`].
404	/// When the transport reports that this side closed it, this is this side's reason:
405	/// the [`abort`](Self::abort) error, or the protocol failure that ended the session.
406	/// A close carrying no application code is otherwise [`Error::IdleTimeout`] for an
407	/// idle timeout and [`Error::Transport`] for anything else. See
408	/// [`Error::from_transport`]. If the runtime drops the driver instead of running it to
409	/// completion, this resolves with [`Error::Cancel`]. A panic while polling the driver is
410	/// a transport failure instead.
411	pub async fn closed(&self) -> Error {
412		kio::wait(|waiter| self.poll_closed(waiter)).await
413	}
414
415	/// Poll form of [`closed`](Self::closed).
416	pub(crate) fn poll_closed(&self, waiter: &kio::Waiter) -> Poll<Error> {
417		Poll::Ready(
418			match ready!(poll_ended(&self.closed, waiter, |ended| ended.err.clone())) {
419				Ok(err) => err,
420				// The driver was dropped before it could observe the close.
421				Err(kio::Closed) => Error::Cancel,
422			},
423		)
424	}
425
426	/// Start the drain [`close`](Self::close) runs, without waiting for it or giving up this handle.
427	pub(crate) fn start_close(&self) {
428		if let Ok(mut close) = self.close.write()
429			&& close.is_none()
430		{
431			*close = Some(Close::Drain);
432		}
433	}
434
435	/// Drain the peer gracefully: send this session's single GOAWAY.
436	///
437	/// The graceful counterpart to [`abort`](Self::abort). Await
438	/// [`closed`](Self::closed) afterwards to observe the peer leaving.
439	///
440	/// Only a [`Goaway`](goaway::Goaway) carrying a [`timeout`](goaway::Goaway::timeout)
441	/// schedules a close of our own, so without one this waits for a peer that may
442	/// never leave. Set a deadline when the drain has to finish. It starts at the driver
443	/// poll this send wakes, so the session must stay driven for the message to reach
444	/// the wire and for the deadline to close it.
445	///
446	/// Available on every version. A version with no GOAWAY message (moq-lite-03
447	/// and earlier) simply carries no explanation to the peer; the deadline is the
448	/// sender's own timer either way, so the session still closes on schedule and
449	/// the caller does not branch on the negotiated version.
450	///
451	/// # Errors
452	///
453	/// Returns [`Error::ProtocolViolation`] when a client names a redirect URI, which
454	/// the peer would be required to close the session over (draft-22 section 9.2), or
455	/// when the URI exceeds the 8,192-byte wire cap.
456	///
457	/// Returns [`Error::Duplicate`] if this session already sent one. The wire carries
458	/// at most one, so the second is dropped rather than replacing the first, but the
459	/// caller is told rather than left guessing. A session that already closed has
460	/// nothing left to drain, which is no error.
461	pub fn goaway(&self, goaway: goaway::Goaway) -> Result<(), Error> {
462		self.goaway.send(goaway)
463	}
464
465	/// Observe a GOAWAY from the peer, telling us to migrate elsewhere.
466	///
467	/// [`poll`](goaway::Consumer::poll) it with a no-op waiter for a synchronous check, or
468	/// wait on it for one. Once a GOAWAY arrives, this session's routes rank as draining:
469	/// below every eligible route of their claim that is not, whatever their preference or
470	/// cost, though a more specific claim still shadows a broader one. Requests keep opening
471	/// on it until a replacement session's route outranks it, and existing subscriptions keep
472	/// flowing until the session closes. A relay still forwards the routes at their real
473	/// cost, and tells a moq-lite-07 peer they drain so it ranks them alike; an older version
474	/// carries no drain, so its peers rank them as before.
475	pub fn draining(&self) -> goaway::Consumer {
476		self.goaway.consumer()
477	}
478
479	/// Ready once the session carries no subscription or fetch, in either direction.
480	///
481	/// Ready at once while it carries none. A track request still being set up, waiting
482	/// on authorization or the track's info, counts too. Announcements and the other
483	/// control streams don't, so a session can be idle while it still serves discovery.
484	/// A session that sent a GOAWAY can then close without cutting any reader off.
485	#[cfg_attr(feature = "async", kio::wrapper)]
486	pub fn poll_idle(&self, waiter: &kio::Waiter) -> Poll<()> {
487		self.work.poll_idle(waiter)
488	}
489
490	/// Whether the peer was heard within the [`KeepAlive`](crate::transport::KeepAlive)'s `soft` limit, or `None` when the
491	/// session runs without one.
492	pub fn liveness(&self) -> Option<Liveness> {
493		self.liveness.as_ref().map(|liveness| *liveness.read())
494	}
495
496	/// Ready with the peer's liveness once it differs from `last`, or `None` once the session
497	/// ends or when it runs without a [`KeepAlive`](crate::transport::KeepAlive).
498	#[cfg_attr(feature = "async", kio::wrapper)]
499	pub fn poll_liveness_changed(&self, waiter: &kio::Waiter, last: Liveness) -> Poll<Option<Liveness>> {
500		let Some(liveness) = &self.liveness else {
501			return Poll::Ready(None);
502		};
503		let changed = liveness.poll(waiter, |now| match **now != last {
504			true => Poll::Ready(**now),
505			false => Poll::Pending,
506		});
507		changed.map(Result::ok)
508	}
509
510	/// The tokens this side presented and the grant they earned, plus the tokens
511	/// the peer presents. See [`auth`].
512	///
513	/// The handle passed to [`Client::with_auth`](crate::Client::with_auth), or else one
514	/// this session created for itself, which ends with it.
515	///
516	/// On moq-lite-07-wip each side presents its connection's credential right after setup.
517	/// Older versions and moq-transport leave the grant `None`.
518	pub fn auth(&self) -> auth::Handle {
519		self.auth.clone()
520	}
521
522	/// The connection credential this side presents on AUTH, or `None` when this session offers no AUTH.
523	pub(crate) fn credential(&self) -> Option<&auth::Credential> {
524		self.credential.as_ref()
525	}
526
527	/// Ready once the peer accepted the connection credential: with its SETUP, or on
528	/// moq-lite-07-wip the AUTH_OK to the connection's own credential. Ready at once when the
529	/// handshake already carried that answer, and never on moq-lite 03/04, which have none.
530	pub(crate) fn poll_accepted(&self, waiter: &kio::Waiter) -> Poll<()> {
531		self.link.poll_accepted(waiter)
532	}
533
534	/// Whether the peer never answers the connection credential, as on moq-lite 03/04, so
535	/// only uptime suggests it took the credential.
536	pub(crate) fn is_silent(&self) -> bool {
537		self.link.is_silent()
538	}
539
540	/// This session's side of its [`auth`](Self::auth) handle.
541	pub(crate) fn link(&self) -> &auth::Link {
542		&self.link
543	}
544}
545
546/// The handles a protocol driver shares with its [`Session`].
547pub(super) struct Handles {
548	pub stats: crate::stats::Session,
549	pub goaway: goaway::Handle,
550	pub auth: auth::Link,
551	/// The connection credential the driver presented on `auth`, when its version has AUTH.
552	pub credential: Option<auth::Credential>,
553	/// Where the driver publishes [`Estimate`] changes, for a protocol that reports
554	/// them to the peer (moq-lite PROBE). Sampled only while a consumer exists.
555	pub estimate: Option<kio::Producer<Estimate>>,
556	/// The reservations the session probes for.
557	pub bandwidth: bandwidth::Allocator,
558	/// The viewers whose sum the session sends as its PROBE target.
559	pub viewers: bandwidth::Viewers,
560	/// The peer's PROBE target, for a protocol that carries one (moq-lite PROBE).
561	pub peer_target: Option<kio::Consumer<bandwidth::Rate>>,
562	/// What the peer's SETUP advertised as its implementation.
563	pub peer_implementation: crate::setup::PeerImplementation,
564	/// The driver's count of datagrams it routed to no datagram track, for a version that
565	/// carries datagrams.
566	pub datagrams_unrouted: Option<Arc<AtomicU64>>,
567}
568
569impl Session {
570	pub(super) fn new(
571		runtime: crate::time::Deadlines,
572		session: crate::driver::Transport,
573		version: Version,
574		recv_bandwidth: Option<bandwidth::Weak>,
575		protocol: crate::driver::Protocol,
576		handles: Handles,
577	) -> (Self, crate::Driver) {
578		let Handles {
579			goaway,
580			auth,
581			credential,
582			estimate,
583			stats: context,
584			bandwidth,
585			viewers,
586			peer_target,
587			peer_implementation,
588			datagrams_unrouted,
589		} = handles;
590		let goaway = Arc::new(goaway);
591		auth.drain_with(goaway.clone());
592		let wire = session.wire().map(|counters| context.wire(counters));
593		let sample = snapshot(&session);
594		if let Some(estimate) = &estimate
595			&& let Ok(mut current) = estimate.write()
596		{
597			*current = Estimate::from(&sample);
598		}
599
600		// Send bandwidth is version-agnostic: it depends on QUIC backend support.
601		// Seeded with the first sample, so a consumer taken before the sampler
602		// first runs reads the estimate instead of `None`.
603		let (send_bandwidth, send_producer) = if sample.estimated_send_rate.is_some() {
604			let producer = bandwidth::Producer::new();
605			let _ = producer.set(sample.estimated_send_rate);
606			(Some(producer.weak()), Some(producer))
607		} else {
608			(None, None)
609		};
610
611		// Without a sender there is nothing to hand the target to, so don't follow it.
612		let probe = session.probe().map(|sender| Probing {
613			sender,
614			local: bandwidth.target(),
615			peer: peer_target,
616			targets: (bandwidth::Rate::ZERO, bandwidth::Rate::ZERO),
617		});
618
619		let close = kio::Producer::new(None);
620		let closed = kio::Producer::new(None);
621		let closed_consumer = closed.consume();
622		let stats = kio::Shared::new(StatsState {
623			sample,
624			demanded: false,
625		});
626		let work = session.work().clone();
627		let liveness = session.keeps_alive().then(|| kio::Producer::new(Liveness::Live));
628
629		let supervisor = Supervisor {
630			goaway: Some(goaway.deadline(&runtime)),
631			version,
632			context: context.clone(),
633			runtime: runtime.clone(),
634			closed_watch: session.clone(),
635			session,
636			close: Some(close.consume()),
637			closed,
638			stats: stats.clone(),
639			wire,
640			send_bandwidth: send_producer,
641			estimate,
642			probe,
643			sampled: None,
644			mode: SamplerMode::Idle,
645			drain: Drain::Idle,
646			unconfirmed: None,
647			auth: auth.clone(),
648			liveness: liveness.clone(),
649		};
650
651		let session = Self {
652			close,
653			closed: closed_consumer,
654			stats,
655			version,
656			peer_implementation: peer_implementation.consume(),
657			send_bandwidth,
658			recv_bandwidth,
659			bandwidth,
660			viewers,
661			goaway,
662			auth: auth.handle().clone(),
663			link: auth.clone(),
664			credential,
665			work,
666			datagrams_unrouted,
667			liveness: liveness.map(|liveness| liveness.consume()),
668		};
669		let driver = crate::Driver::new(
670			runtime.clone(),
671			crate::driver::State {
672				protocol,
673				supervisor: Some(supervisor),
674				result: None,
675			},
676		);
677
678		(session, driver)
679	}
680}
681
682/// The driver's transport-facing half of a [`Session`]: it executes the
683/// handles' close requests, publishes the transport's terminal error, and
684/// samples the connection stats (including the send-bandwidth estimate) while
685/// anyone is consuming them, and enforces GOAWAY deadlines independently of writes.
686///
687/// Finishes once the transport reports closed, or once a close this side sent goes
688/// unconfirmed past its grace; everything else is moot then.
689pub(crate) struct Supervisor {
690	goaway: Option<goaway::Deadline>,
691	version: Version,
692	/// Where the session's outcome is recorded.
693	context: crate::stats::Session,
694	runtime: crate::time::Deadlines,
695	session: crate::driver::Transport,
696	// A dedicated clone for the close watch, since each pending poll operation
697	// needs its own handle.
698	closed_watch: crate::driver::Transport,
699	/// Handle-side close requests; `None` once one was executed (only the
700	/// first close matters, and the channel closing is the last handle
701	/// dropping).
702	close: Option<kio::Consumer<Option<Close>>>,
703	/// Where the transport's end is published for [`Session::closed`].
704	closed: kio::Producer<Option<Ended>>,
705	stats: kio::Shared<StatsState>,
706	/// The send-rate estimate channel, when the backend reports one. `None`
707	/// also once every consumer is gone for good.
708	send_bandwidth: Option<bandwidth::Producer>,
709	/// Published on change while a consumer exists; see [`Self::poll_sampler`].
710	estimate: Option<kio::Producer<Estimate>>,
711	/// The transport's sender and the targets it probes up to, when it has one.
712	probe: Option<Probing>,
713	/// When the last sample was taken.
714	sampled: Option<crate::time::Instant>,
715	mode: SamplerMode,
716	drain: Drain,
717	/// Set once this side closed the transport: past it, the session ends without the
718	/// transport confirming the close.
719	unconfirmed: Option<crate::time::Deadline>,
720	/// The transport's wire counters, registered under the session's root; dropping records the last reading.
721	wire: Option<crate::stats::Wire>,
722	/// This session's side of its auth handle, closed before the end is published so a
723	/// replacement session built on the same handle never finds this one still active.
724	auth: auth::Link,
725	/// Where the transport's report of the peer's liveness is published, under a keep-alive.
726	/// Dropped with the supervisor, which ends every wait on it.
727	liveness: Option<kio::Producer<Liveness>>,
728}
729
730/// A transport's sender and the two targets it probes up to, whichever is larger.
731///
732/// The directions never mix: these are both rates this side sends at, its own
733/// reservations' and what the peer asks to receive. What this side wants to receive
734/// goes to the peer instead, as its PROBE target.
735struct Probing {
736	sender: crate::transport::Probe,
737	/// This side's reservations.
738	local: bandwidth::Target,
739	/// The peer's PROBE target, when the protocol carries one. `None` once it is gone.
740	peer: Option<kio::Consumer<bandwidth::Rate>>,
741	/// The last local and peer targets read.
742	targets: (bandwidth::Rate, bandwidth::Rate),
743}
744
745impl Probing {
746	fn poll(&mut self, waiter: &kio::Waiter) {
747		while let Poll::Ready(local) = self.local.poll_changed(waiter) {
748			self.targets.0 = local;
749		}
750		// Loop until pending, so the waiter stays armed for the next change.
751		while let Some(peer) = &self.peer {
752			let last = self.targets.1;
753			let polled = peer.poll(waiter, |rate| match **rate != last {
754				true => Poll::Ready(**rate),
755				false => Poll::Pending,
756			});
757			match polled.map(|res| res.ok()) {
758				Poll::Ready(Some(rate)) => self.targets.1 = rate,
759				// The protocol stopped reading the peer; nothing it asked for still holds.
760				Poll::Ready(None) => {
761					self.targets.1 = bandwidth::Rate::ZERO;
762					self.peer = None;
763				}
764				Poll::Pending => break,
765			}
766		}
767		// The peer's target is untrusted, but only sets how high to probe: each probe
768		// scales the current estimate and stays under congestion control.
769		let target = self.targets.0.max(self.targets.1);
770		if self.sender.target() != target {
771			self.sender.set_target(target);
772		}
773	}
774}
775
776/// A [`Session::close`] waiting for the protocol to deliver what it queued.
777enum Drain {
778	/// Nobody asked for one.
779	Idle,
780	/// Requested: close once drained, or at the deadline.
781	Waiting(crate::time::Deadline),
782	/// The drain closed the transport, with this outcome.
783	Done(Result<(), Error>),
784}
785
786enum SamplerMode {
787	/// Nobody wants stats; sampling is paused.
788	Idle,
789	/// Someone does; sample when the deadline elapses.
790	// Keep the deadline under a task bit: advancing this driver's clock then
791	// queues the sample without waking the already-running driver again.
792	Polling {
793		deadline: Box<kio::Tasks<crate::time::Deadline>>,
794	},
795}
796
797impl Supervisor {
798	pub(crate) fn panicked(&mut self, error: Error) {
799		self.session
800			.closing()
801			.local
802			.store(true, std::sync::atomic::Ordering::Relaxed);
803		if let Ok(mut closed) = self.closed.write() {
804			*closed = Some(Ended {
805				err: error.clone(),
806				drain: Some(Err(error.clone())),
807			});
808		}
809		let code = self.version.session_code(&SessionError::Internal);
810		self.session.abort(&error, code, "session driver panicked");
811	}
812	const POLL_INTERVAL: Duration = Duration::from_millis(100);
813
814	pub(crate) fn poll(&mut self, waiter: &kio::Waiter) -> Poll<()> {
815		if let Poll::Ready(err) = self.poll_ended(waiter) {
816			self.end(err);
817			return Poll::Ready(());
818		}
819		self.poll_running(waiter);
820		// A close executed this turn starts its grace, which has to register its wakeup.
821		if let Poll::Ready(err) = self.poll_ended(waiter) {
822			self.end(err);
823			return Poll::Ready(());
824		}
825		Poll::Pending
826	}
827
828	/// Resolve with why the session ended: the transport's terminal error, or this side's
829	/// reason once the transport reports or has had its grace to confirm this side's close.
830	fn poll_ended(&mut self, waiter: &kio::Waiter) -> Poll<Error> {
831		let err = match self.closed_watch.poll_closed(waiter) {
832			Poll::Ready(err) => match err.close_kind() {
833				// The transport only knows this side closed it, so the reason is ours.
834				crate::transport::CloseKind::Closed if err.session_error().is_none() => None,
835				_ => return Poll::Ready(self.version.transport_error(err)),
836			},
837			// A peer that is gone never lets some transports confirm a close, such as a
838			// WebTransport close waiting for its capsule's acknowledgement until the idle
839			// timeout. So a close this side sent, by a handle or the protocol, ends the
840			// session after three round trips and at least [`CLOSE_GRACE`], the time a live
841			// peer takes; the transport goes on delivering it on its own.
842			Poll::Pending => {
843				if self.unconfirmed.is_none() && self.session.closing().is_sent() {
844					let rtt = snapshot(&self.session).rtt.unwrap_or_default();
845					let grace = (rtt * 3).max(CLOSE_GRACE);
846					self.unconfirmed = Some(crate::time::Deadline::after(&self.runtime, grace));
847				}
848				match &mut self.unconfirmed {
849					Some(grace) => {
850						ready!(grace.poll(waiter));
851						None
852					}
853					None => return Poll::Pending,
854				}
855			}
856		};
857		Poll::Ready(err.unwrap_or_else(|| self.session.closing().cause(self.version).unwrap_or(Error::Cancel)))
858	}
859
860	/// Publish the session's end with `err`.
861	fn end(&mut self, err: Error) {
862		// Nothing samples once this returns, but `stats()` keeps serving
863		// this cell, so leave it holding the session's final counters
864		// rather than whichever sample the last demand happened to catch.
865		self.stats.lock().sample = snapshot(&self.session);
866		self.wire.take();
867		let drain = match std::mem::replace(&mut self.drain, Drain::Idle) {
868			Drain::Done(res) => Some(res),
869			_ => None,
870		};
871		// Anything the peer is told is "no error" ended the session cleanly, by
872		// either side: one spelling for the handles and the stats.
873		let err = match SessionError::from(&err) {
874			SessionError::Cancel => Error::Cancel,
875			_ => err,
876		};
877		self.auth.close(err.clone());
878		self.context.end(&err);
879		if let Ok(mut closed) = self.closed.write() {
880			*closed = Some(Ended { err, drain });
881		}
882	}
883
884	/// Run everything a live session does: its GOAWAY deadline, the handles' close
885	/// requests, and the samplers.
886	fn poll_running(&mut self, waiter: &kio::Waiter) {
887		if let Some(goaway) = &mut self.goaway
888			&& let Poll::Ready(timeout) = goaway.poll(waiter)
889		{
890			self.goaway = None;
891			if let Some(timeout) = timeout {
892				tracing::warn!(?timeout, "peer did not leave before the GOAWAY deadline; closing");
893				self.close(Error::GoawayTimeout, &Error::GoawayTimeout.to_string());
894			}
895		}
896
897		// Execute the handle-side close requests. The channel closing is the
898		// last handle dropping, with a request written just before winning over
899		// the implicit cancel. A drain loops back to watch for an abort, which
900		// cuts it short.
901		while let Some(close) = &self.close {
902			let draining = matches!(self.drain, Drain::Waiting(_));
903			let (request, last) = match close.poll(waiter, |state| match &**state {
904				Some(Close::Drain) if draining => Poll::Pending,
905				Some(request) => Poll::Ready(request.clone()),
906				None => Poll::Pending,
907			}) {
908				Poll::Ready(Ok(request)) => (Some(request), false),
909				Poll::Ready(Err(last)) => (last.clone(), true),
910				Poll::Pending => break,
911			};
912			match request {
913				// The last handle dropped without asking for anything: the implicit cancel.
914				None => {
915					self.session
916						.closing()
917						.local
918						.store(true, std::sync::atomic::Ordering::Relaxed);
919					self.close(Error::Cancel, "dropped");
920					self.drain = Drain::Idle;
921					self.close = None;
922				}
923				Some(Close::Abort(err)) => {
924					self.close(err.clone(), &err.to_string());
925					self.drain = Drain::Idle;
926					self.close = None;
927				}
928				Some(Close::Drain) => {
929					if !draining {
930						self.drain = Drain::Waiting(crate::time::Deadline::after(&self.runtime, CLOSE_TIMEOUT));
931					}
932					// No handle is left to abort.
933					if last {
934						self.close = None;
935					}
936				}
937			}
938		}
939
940		self.poll_sampler(waiter);
941
942		if let Some(probe) = &mut self.probe {
943			probe.poll(waiter);
944		}
945
946		self.poll_liveness(waiter);
947	}
948
949	/// Publish each change in the peer's liveness the transport reports.
950	fn poll_liveness(&mut self, waiter: &kio::Waiter) {
951		let Some(liveness) = &self.liveness else {
952			return;
953		};
954		loop {
955			let last = *liveness.read();
956			let Poll::Ready(now) = self.session.poll_liveness(waiter, last) else {
957				return;
958			};
959			match liveness.write() {
960				Ok(mut current) => *current = now,
961				// Every consumer is gone for good.
962				Err(_) => return,
963			}
964		}
965	}
966
967	pub(crate) fn draining(&self) -> bool {
968		matches!(self.drain, Drain::Waiting(_))
969	}
970
971	/// Close the transport over `cause`, this side's reason for ending the session.
972	fn close(&mut self, cause: Error, reason: &str) {
973		let code = self.version.session_code(&SessionError::from(&cause));
974		self.session.abort(&cause, code, reason);
975	}
976
977	/// Finish a requested drain once the protocol owes the peer nothing, or at
978	/// the deadline. Returns whether this closed the transport.
979	///
980	/// Called after the protocol ran this turn, since only then is `drained`
981	/// current.
982	pub(crate) fn poll_drain(&mut self, drained: bool, waiter: &kio::Waiter) -> bool {
983		let Drain::Waiting(deadline) = &mut self.drain else {
984			return false;
985		};
986		let res = match drained {
987			true => Ok(()),
988			false if deadline.poll(waiter).is_ready() => Err(Error::Timeout),
989			false => return false,
990		};
991		self.session
992			.closing()
993			.local
994			.store(true, std::sync::atomic::Ordering::Relaxed);
995		self.close(Error::Cancel, "");
996		self.drain = Drain::Done(res);
997		// The transport is closed, so no later request can change anything.
998		self.close = None;
999		true
1000	}
1001
1002	/// Take one sample, publishing it to the bandwidth and estimate channels.
1003	fn sample(&mut self) -> Stats {
1004		let sample = snapshot(&self.session);
1005		self.sampled = Some(self.runtime.now());
1006		if let Some(producer) = &self.send_bandwidth {
1007			// An error means every consumer is gone for good; the stats cell
1008			// still wants the sample.
1009			if producer.set(sample.estimated_send_rate).is_err() {
1010				self.send_bandwidth = None;
1011			}
1012		}
1013		if let Some(estimate) = &self.estimate
1014			&& let Ok(mut current) = estimate.write()
1015		{
1016			let next = Estimate::from(&sample);
1017			// Only a change wakes the consumers.
1018			if *current != next {
1019				*current = next;
1020			}
1021		}
1022		sample
1023	}
1024
1025	/// Take one sample for the readers that asked, and arm the next deadline.
1026	fn sample_demanded(&mut self) {
1027		let sample = self.sample();
1028		let mut stats = self.stats.lock();
1029		stats.sample = sample;
1030		stats.demanded = false;
1031		drop(stats);
1032		let next = crate::time::Deadline::after(&self.runtime, Self::POLL_INTERVAL);
1033		match &mut self.mode {
1034			SamplerMode::Polling { deadline } => deadline.push(next),
1035			SamplerMode::Idle => {
1036				let mut deadline = kio::Tasks::new();
1037				deadline.push(next);
1038				self.mode = SamplerMode::Polling {
1039					deadline: Box::new(deadline),
1040				};
1041			}
1042		}
1043	}
1044
1045	fn poll_sampler(&mut self, waiter: &kio::Waiter) {
1046		self.poll_demanded(waiter);
1047
1048		// An estimate consumer (a PROBE stream) samples only when the driver runs
1049		// anyway, never on a timer of its own: a session nothing wakes is sending
1050		// nothing, so its estimate has nothing new to say. The driver polls this
1051		// before the protocol, so the estimate a consumer reads is at most one
1052		// interval old.
1053		let Some(estimate) = &self.estimate else { return };
1054		if estimate.poll_wanted_changed(waiter, false).is_pending() {
1055			return;
1056		}
1057		let now = self.runtime.now();
1058		if self
1059			.sampled
1060			.is_none_or(|at| now.duration_since(at) >= Self::POLL_INTERVAL)
1061		{
1062			// Not into the stats cell: writing it would wake this sampler's own
1063			// registration there, and stats readers demand their own samples.
1064			self.sample();
1065		}
1066	}
1067
1068	/// Sample on an interval while a bandwidth consumer or a stats reader wants it.
1069	fn poll_demanded(&mut self, waiter: &kio::Waiter) {
1070		loop {
1071			match &mut self.mode {
1072				SamplerMode::Idle => {
1073					// Demand is a bandwidth consumer appearing or a stats read.
1074					let mut demanded = match &self.send_bandwidth {
1075						Some(producer) => match producer.poll_wanted_changed(waiter, false) {
1076							Poll::Ready(Ok(_)) => true,
1077							Poll::Ready(Err(_)) => {
1078								self.send_bandwidth = None;
1079								false
1080							}
1081							Poll::Pending => false,
1082						},
1083						None => false,
1084					};
1085					demanded |= self
1086						.stats
1087						.poll(waiter, |state| match state.demanded {
1088							true => Poll::Ready(()),
1089							false => Poll::Pending,
1090						})
1091						.is_ready();
1092					if !demanded {
1093						return;
1094					}
1095					self.sample_demanded();
1096				}
1097				SamplerMode::Polling { deadline } => {
1098					if deadline.poll(waiter).is_pending() {
1099						return;
1100					}
1101					// The interval elapsed: pause unless someone still cares.
1102					let wanted = self
1103						.send_bandwidth
1104						.as_ref()
1105						.is_some_and(|producer| producer.demand().wanted());
1106					if !wanted && !self.stats.read().demanded {
1107						self.mode = SamplerMode::Idle;
1108						continue;
1109					}
1110					self.sample_demanded();
1111					// Loop so the fresh deadline registers the waiter.
1112				}
1113			}
1114		}
1115	}
1116}
1117
1118/// A [`Stats`] snapshot of the transport's metrics and wire counters.
1119fn snapshot<S: crate::transport::poll::Session>(session: &S) -> Stats {
1120	// Metrics first: a transport that polls its byte counts refreshes its wire while reading them.
1121	let metrics = session.metrics();
1122	let wire = session.wire();
1123	Stats {
1124		rtt: metrics.rtt(),
1125		estimated_send_rate: metrics.estimated_send_rate().map(bandwidth::Rate::from_bps),
1126		bytes_sent: wire.as_ref().map(crate::transport::Wire::sent_bytes),
1127		bytes_received: wire.as_ref().map(crate::transport::Wire::received_bytes),
1128		bytes_lost: metrics.bytes_lost(),
1129		packets_sent: metrics.packets_sent(),
1130		packets_received: metrics.packets_received(),
1131		packets_lost: metrics.packets_lost(),
1132		streams_evicted: metrics.streams_evicted(),
1133		credit_stalls: wire.as_ref().map(crate::transport::Wire::credit_stalls),
1134		credit_stalled: wire.as_ref().map(crate::transport::Wire::credit_stalled),
1135		// Counted by the protocol, not the transport: filled in by `Session::stats`.
1136		datagrams_unrouted: None,
1137	}
1138}
1139
1140// The point of the sever: the handle's auto-traits no longer depend on which
1141// transport the runtime drives, so every consumer (moq-ffi needs Send + Sync)
1142// works over every transport, pinned `!Send` ones included.
1143const _: () = {
1144	const fn assert_send_sync<T: Send + Sync>() {}
1145	assert_send_sync::<Session>();
1146};
1147
1148/// Session-local advertisement withdrawal; the source origin remains shared.
1149#[derive(Clone, Default)]
1150pub(crate) struct Withdrawal(kio::Shared<WithdrawalState>);
1151
1152#[derive(Default)]
1153struct WithdrawalState {
1154	closing: bool,
1155	active: usize,
1156}
1157
1158impl Withdrawal {
1159	pub(crate) fn begin(&self) {
1160		self.0.lock().closing = true;
1161	}
1162
1163	pub(crate) fn poll(&self, waiter: &kio::Waiter) -> Poll<()> {
1164		self.0
1165			.poll(
1166				waiter,
1167				|state| if state.closing { Poll::Ready(()) } else { Poll::Pending },
1168			)
1169			.map(|_| ())
1170	}
1171
1172	pub(crate) fn drained(&self) -> bool {
1173		self.0.read().active == 0
1174	}
1175
1176	pub(crate) fn register(&self) -> Withdrawing {
1177		self.0.lock().active += 1;
1178		Withdrawing(self.clone())
1179	}
1180}
1181
1182pub(crate) struct Withdrawing(Withdrawal);
1183
1184impl Drop for Withdrawing {
1185	fn drop(&mut self) {
1186		self.0.0.lock().active -= 1;
1187	}
1188}
1189
1190/// The subscriptions and fetches a session carries in either direction, which
1191/// [`Session::idle`] waits to reach zero.
1192#[derive(Clone, Default)]
1193pub(crate) struct Work(kio::Shared<usize>);
1194
1195impl Work {
1196	/// Count one subscription or fetch until the returned guard drops.
1197	pub(crate) fn start(&self) -> Working {
1198		*self.0.lock() += 1;
1199		Working(self.clone())
1200	}
1201
1202	fn poll_idle(&self, waiter: &kio::Waiter) -> Poll<()> {
1203		self.0
1204			.poll(
1205				waiter,
1206				|count| if **count == 0 { Poll::Ready(()) } else { Poll::Pending },
1207			)
1208			.map(|_| ())
1209	}
1210}
1211
1212/// One subscription or fetch counted in [`Work`], released on drop.
1213pub(crate) struct Working(Work);
1214
1215impl Drop for Working {
1216	fn drop(&mut self) {
1217		*self.0.0.lock() -= 1;
1218	}
1219}
1220
1221/// Bounds on what one peer can make a session hold, where its transport does not already.
1222///
1223/// Each request holds a stream of its own, so the transport's stream credit bounds those.
1224/// A peer that announces past `announces` loses the session, closed with
1225/// `TOO_MANY_REQUESTS`. The stats sessions rows report announcement and subscription peaks.
1226///
1227/// ```
1228/// let mut limits = moq_net::session::Limits::default();
1229/// limits.announces = 1_000;
1230/// limits.live_edges = Some(256 << 20);
1231/// let client = moq_net::Client::new().with_limits(limits);
1232/// ```
1233#[derive(Clone, Copy, Debug, PartialEq, Eq)]
1234#[non_exhaustive]
1235pub struct Limits {
1236	/// Broadcasts (moq-lite) or namespaces (moq-transport) the peer may have announced to us.
1237	pub announces: usize,
1238
1239	/// Bytes the newest group of every track we receive from the peer may hold in all.
1240	///
1241	/// The cache never evicts a live track's newest group, so a peer holding many quiet
1242	/// tracks would otherwise hold one group each past any cache capacity. Past this, the
1243	/// session sheds its own live edges in delivery's priority order, the lowest-priority
1244	/// track and then the edge that moved longest ago first: the frames readers took (a
1245	/// compressed track's inflated copies aside), then whole edges, of which the one being
1246	/// written keeps its newest frame. `None` leaves them unbounded.
1247	pub live_edges: Option<u64>,
1248}
1249
1250impl Default for Limits {
1251	/// Generous enough for a relay mesh carrying a large origin; lower it for untrusted peers.
1252	fn default() -> Self {
1253		Self {
1254			announces: 100_000,
1255			live_edges: None,
1256		}
1257	}
1258}
1259
1260/// A count of live entries shared across a session, refused past its cap.
1261#[derive(Clone)]
1262pub(crate) struct Slots {
1263	live: Arc<std::sync::atomic::AtomicUsize>,
1264	max: usize,
1265	/// Where the most this session has held is reported.
1266	stats: Option<(crate::stats::Session, crate::stats::Cap)>,
1267}
1268
1269impl Slots {
1270	pub(crate) fn new(max: usize) -> Self {
1271		Self {
1272			live: Default::default(),
1273			max,
1274			stats: None,
1275		}
1276	}
1277
1278	/// Report how many are held to `stats`, as `cap`'s peak.
1279	pub(crate) fn with_stats(mut self, stats: &crate::stats::Session, cap: crate::stats::Cap) -> Self {
1280		stats.track_held(cap, &self.live);
1281		self.stats = Some((stats.clone(), cap));
1282		self
1283	}
1284
1285	/// How many more slots may be taken right now.
1286	pub(crate) fn available(&self) -> usize {
1287		self.max
1288			.saturating_sub(self.live.load(std::sync::atomic::Ordering::Acquire))
1289	}
1290
1291	/// Take one slot until the returned guard drops, or [`Error::TooManyRequests`] at the cap.
1292	///
1293	/// A peer whose own request runs past its limits loses the session.
1294	pub(crate) fn acquire(&self) -> Result<Slot, Error> {
1295		use std::sync::atomic::Ordering;
1296		let held = self
1297			.live
1298			.fetch_update(Ordering::AcqRel, Ordering::Acquire, |live| {
1299				(live < self.max).then_some(live + 1)
1300			})
1301			.map_err(|_| Error::TooManyRequests)?
1302			+ 1;
1303		Ok(self.held(held))
1304	}
1305
1306	/// Count one entry the transport already bounds until the returned guard drops, past the
1307	/// cap too, so entries taken with [`Self::acquire`] see it.
1308	pub(crate) fn hold(&self) -> Slot {
1309		let held = self.live.fetch_add(1, std::sync::atomic::Ordering::AcqRel) + 1;
1310		self.held(held)
1311	}
1312
1313	fn held(&self, held: usize) -> Slot {
1314		if let Some((stats, cap)) = &self.stats {
1315			stats.hold(*cap, held as u64);
1316		}
1317		Slot(self.live.clone())
1318	}
1319}
1320
1321impl Default for Slots {
1322	/// Unlimited, for sessions and tests that configure nothing.
1323	fn default() -> Self {
1324		Self::new(usize::MAX)
1325	}
1326}
1327
1328/// One taken [`Slots`] entry, released on drop.
1329pub(crate) struct Slot(Arc<std::sync::atomic::AtomicUsize>);
1330
1331impl Drop for Slot {
1332	fn drop(&mut self) {
1333		self.0.fetch_sub(1, std::sync::atomic::Ordering::AcqRel);
1334	}
1335}
1336
1337#[cfg(all(test, feature = "async"))]
1338mod tests;