Skip to main content

moq_net/model/
datagram.rs

1//! Datagram tracks: live, unreliable payloads addressed by their own sequence.
2//!
3//! A datagram track is fixed as one when it is created, independent of any stream track of
4//! the same name. Each datagram is one self-contained payload carried in a single QUIC
5//! datagram: best-effort, unordered, and never retransmitted, cached, or fetched. It has a
6//! sequence from the track's own counter and a timestamp, and no group.
7//!
8//! A broadcast creates a [`Producer`] with
9//! [`broadcast::Producer::create_datagrams`](crate::broadcast::Producer::create_datagrams),
10//! and a reader asks for a [`Consumer`] with
11//! [`broadcast::Consumer::datagrams`](crate::broadcast::Consumer::datagrams). A consumer
12//! is live from when it is created: it never receives a datagram written before it. A
13//! created track is in the broadcast's [listing](crate::broadcast::Tracks) until it ends.
14//!
15//! Delivery is best-effort per hop: a session drops (with a debug log) any datagram whose
16//! encoded body exceeds the transport's datagram size, and sessions that can't carry
17//! datagrams at all (moq-lite before 05, or stream-only transports like WebSocket) never
18//! deliver them. Moq-transport maps a datagram track onto SUBSCRIBE and OBJECT_DATAGRAM,
19//! with the sequence as the group ID and object ID 0.
20//!
21//! Moq-lite 07 asks for a datagram track on a request of its own. Moq-lite 05 and 06 carry a
22//! name's groups and datagrams on one subscription, as moq-transport does: a session serves
23//! an old subscription with both of the name's tracks, and a subscriber keeps only the kind
24//! it asked for, sharing one subscription with any reader of the other kind. Two limits
25//! follow on those versions:
26//!
27//! - A subscription carries the datagram track that exists when it starts, so create a
28//!   name's datagram track before, or with, its stream track.
29//! - The wire never says a name has no datagram track, so a datagram reader of a name with
30//!   only a stream track receives nothing until that track ends.
31//! - The wire never says which kind a subscription asks for, so a publisher serves it from
32//!   the stream track when one is published, and otherwise from whichever kind answers
33//!   first: a local datagram track answers without waiting for a stream request handler,
34//!   which need not answer a name it doesn't serve.
35
36use std::{
37	collections::VecDeque,
38	sync::Arc,
39	task::{Poll, ready},
40};
41
42use bytes::Bytes;
43
44use crate::{Error, Result, Timescale, Timestamp, broadcast, stats};
45
46/// Hard ceiling on a datagram payload, matching the QUIC DATAGRAM frame limit.
47///
48/// This only bounds buffering; the real limit is per hop. Each session drops a datagram whose
49/// encoded body exceeds the transport's current datagram size (roughly the path MTU minus QUIC
50/// and MoQ header overhead), so callers should keep payloads well below the minimum path MTU
51/// of 1200 bytes (e.g. a single audio frame).
52pub(crate) const MAX_PAYLOAD: usize = u16::MAX as usize;
53
54/// How many datagrams a track holds for consumers that have not read them yet.
55///
56/// A consumer more than this far behind skips to the oldest one still held, so a stalled
57/// reader costs the track at most this many payloads.
58const MAX_BUFFERED: usize = 64;
59
60/// How many payload bytes a track holds for consumers that have not read them yet, beyond
61/// which it drops the oldest, though never the newest. Datagrams that fit a path are well
62/// under this; it bounds a local writer of large payloads.
63const MAX_BUFFERED_BYTES: usize = 64 * 1024;
64
65/// The default subscriber priority of a [`Consumer`].
66const DEFAULT_PRIORITY: i8 = 0;
67
68/// A single unreliable payload: its sequence, its timestamp, and the bytes.
69#[derive(Clone, Debug, PartialEq, Eq)]
70pub struct Datagram {
71	/// The datagram track's own sequence number.
72	pub sequence: u64,
73	/// Presentation timestamp in the track's timescale, or on a scale-less track
74	/// [`Timestamp::unscaled`] at its sequence.
75	pub timestamp: Timestamp,
76	/// The datagram payload.
77	pub payload: Bytes,
78}
79
80/// Publisher-side properties of a datagram track, fixed when it is created.
81#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
82#[non_exhaustive]
83pub struct Info {
84	/// Units per second of each datagram's timestamp, or `None` for a track without one.
85	///
86	/// A track is all timed or all untimed: a write that doesn't match is refused with
87	/// [`Error::TimestampMismatch`].
88	pub timescale: Option<Timescale>,
89	/// The publisher's priority for this track, higher first, defaulting to 0. It breaks
90	/// ties between subscriptions of equal subscriber priority.
91	pub priority: i8,
92}
93
94impl Info {
95	/// Set the timestamp scale, or `None` for an untimed track, returning `self` for chaining.
96	pub fn with_timescale(mut self, timescale: impl Into<Option<Timescale>>) -> Self {
97		self.timescale = timescale.into();
98		self
99	}
100
101	/// Set the publisher's priority, returning `self` for chaining.
102	pub fn with_priority(mut self, priority: i8) -> Self {
103		self.priority = priority;
104		self
105	}
106
107	/// `timestamp` at this track's [`timescale`](Self::timescale).
108	///
109	/// A track is all timed or all scale-less: a timestamp that doesn't match it, or one the
110	/// track's scale can't hold, is [`Error::TimestampMismatch`]. A writer that changes
111	/// state before its datagram reaches the track, such as encrypting it, rescales first so
112	/// a refused timestamp changes nothing.
113	pub fn rescale(&self, timestamp: Timestamp) -> Result<Timestamp> {
114		match (timestamp.scale(), self.timescale) {
115			(Some(_), Some(timescale)) => timestamp.convert(timescale).map_err(|_| Error::TimestampMismatch),
116			(None, None) => Ok(timestamp),
117			_ => Err(Error::TimestampMismatch),
118		}
119	}
120
121	/// Produce a standalone datagram track with this info, outside any broadcast.
122	#[cfg(test)]
123	pub(crate) fn produce(self, name: impl Into<Arc<str>>) -> Producer {
124		Producer::new(name.into(), Some(self))
125	}
126}
127
128#[derive(Default)]
129struct State {
130	// `None` while a request waits for a handler to accept it.
131	info: Option<Info>,
132	buffer: VecDeque<Datagram>,
133	// The payload bytes `buffer` holds.
134	bytes: usize,
135	// The absolute index of `buffer[0]`, so consumers keep a cursor past what was dropped.
136	offset: u64,
137	// The sequence `append` assigns next: one past the highest written, or `None` once
138	// `u64::MAX` was written and no sequence follows it.
139	next: Option<u64>,
140	// Set once the track ends: `Ok` for a finish.
141	end: Option<Result<()>>,
142	// Live producer-side handles: producers and an unanswered request.
143	producers: usize,
144	// Each live consumer's priority, or None for passive forwarding over an existing stream.
145	priorities: slab::Slab<Option<i8>>,
146	// The broadcast's listing of a track its producer created, withdrawn once the track ends.
147	listed: Option<broadcast::Unlist>,
148}
149
150impl State {
151	fn closed(&self) -> Result<()> {
152		match &self.end {
153			None => Ok(()),
154			Some(Ok(())) => Err(Error::Closed),
155			Some(Err(err)) => Err(err.clone()),
156		}
157	}
158
159	fn push(&mut self, datagram: Datagram) {
160		self.bytes += datagram.payload.len();
161		while self.buffer.len() >= MAX_BUFFERED || (!self.buffer.is_empty() && self.bytes > MAX_BUFFERED_BYTES) {
162			let dropped = self.buffer.pop_front().expect("not empty");
163			self.bytes -= dropped.payload.len();
164			self.offset += 1;
165		}
166		self.next = match (self.next, datagram.sequence.checked_add(1)) {
167			(Some(next), Some(after)) => Some(next.max(after)),
168			_ => None,
169		};
170		self.buffer.push_back(datagram);
171	}
172
173	/// End the track, returning its listing to withdraw once this lock is released, since
174	/// the broadcast's lock is taken first.
175	#[must_use = "drop the listing after releasing the lock"]
176	fn end(&mut self, end: Result<()>) -> Option<broadcast::Unlist> {
177		if self.end.is_some() {
178			return None;
179		}
180		let finished = end.is_ok();
181		// A finish leaves what is buffered for the consumers already reading; an error
182		// ends the track at once, so nobody reads what is left.
183		let unread = end.is_err() || self.priorities.is_empty();
184		self.end = Some(end);
185		if unread {
186			self.release();
187		}
188		self.listed.take().map(|listed| listed.finished(finished))
189	}
190
191	/// Drop what is buffered: nobody can read it any more. A consumer joining later starts
192	/// past it, so this holds for an ended track once its last consumer leaves.
193	fn release(&mut self) {
194		self.offset += self.buffer.len() as u64;
195		self.buffer.clear();
196		self.bytes = 0;
197	}
198
199	/// Whether a consumer at `cursor` has a datagram to read: past what was dropped, it reads
200	/// the oldest one still held.
201	fn has_next(&self, cursor: u64) -> bool {
202		!self.buffer.is_empty() && self.offset + (self.buffer.len() as u64) > cursor
203	}
204
205	fn priority(&self) -> Option<i8> {
206		self.priorities.iter().filter_map(|(_, priority)| *priority).max()
207	}
208}
209
210/// The broadcast's handle on a datagram track, which keeps nothing alive.
211#[derive(Clone)]
212pub(super) struct Weak {
213	name: Arc<str>,
214	state: kio::Shared<State>,
215}
216
217impl Weak {
218	/// Join the track as a new consumer, unless it already ended.
219	pub(super) fn try_consume(&self, stats: stats::Scope) -> Option<Consumer> {
220		Consumer::join(self.name.clone(), &self.state, stats, Some(DEFAULT_PRIORITY))
221	}
222
223	/// Observe a live track without adding demand; its stream subscription already holds that.
224	pub(super) fn observe(&self, stats: stats::Scope) -> Option<Consumer> {
225		Consumer::join(self.name.clone(), &self.state, stats, None)
226	}
227}
228
229impl super::WeakEntry for Weak {
230	fn is_closed(&self) -> bool {
231		self.state.read().end.is_some()
232	}
233
234	fn same_channel(&self, other: &Self) -> bool {
235		self.state.is_clone(&other.state)
236	}
237}
238
239/// Writes datagrams to a datagram track.
240///
241/// Clones share the track and its sequence counter. The track ends on [`Self::finish`],
242/// [`Self::abort`], or the last producer dropping, which consumers see as
243/// [`Error::Dropped`].
244pub struct Producer {
245	name: Arc<str>,
246	info: Info,
247	state: kio::Shared<State>,
248	stats: stats::Scope,
249	// The value `poll_priority_changed` last returned, or `None` before it returned any.
250	prev: Option<Option<i8>>,
251}
252
253impl Producer {
254	pub(super) fn new(name: Arc<str>, info: Option<Info>) -> Self {
255		let state = State {
256			info,
257			next: Some(0),
258			producers: 1,
259			..Default::default()
260		};
261		Self {
262			name,
263			info: info.unwrap_or_default(),
264			state: kio::Shared::new(state),
265			stats: stats::Scope::default(),
266			prev: None,
267		}
268	}
269
270	pub(super) fn with_stats(mut self, scope: stats::Scope) -> Self {
271		self.stats = scope;
272		self
273	}
274
275	/// Keep the track in its broadcast's listing until it ends. Called under the broadcast's lock.
276	pub(super) fn listed(self, unlist: broadcast::Unlist) -> Self {
277		self.state.lock().listed = Some(unlist);
278		self
279	}
280
281	pub(super) fn weak(&self) -> Weak {
282		Weak {
283			name: self.name.clone(),
284			state: self.state.clone(),
285		}
286	}
287
288	/// The track's name within its broadcast.
289	pub fn name(&self) -> &str {
290		&self.name
291	}
292
293	/// The track's properties.
294	pub fn info(&self) -> &Info {
295		&self.info
296	}
297
298	/// Append a datagram with the next sequence number, returning that sequence.
299	///
300	/// A scale-less track has no time, so its datagram's [`Timestamp::unscaled`] names the
301	/// sequence instead, as its key names a group. A timestamp that doesn't match the track
302	/// is [`Error::TimestampMismatch`]. Keep payloads well under the 1200-byte minimum path
303	/// MTU: a hop drops a datagram that does not fit.
304	pub fn append<B: crate::IntoBytes>(&mut self, timestamp: Timestamp, payload: B) -> Result<u64> {
305		let mut state = self.state.lock();
306		let sequence = match timestamp.scale() {
307			Some(_) => state.next.ok_or(crate::coding::BoundsExceeded)?,
308			None => timestamp.value(),
309		};
310		self.push(
311			&mut state,
312			Datagram {
313				sequence,
314				timestamp,
315				payload: payload.into_bytes(),
316			},
317		)?;
318		Ok(sequence)
319	}
320
321	/// Insert a datagram with an explicit sequence, as a relay forwarding one does.
322	///
323	/// [`Self::append`] continues past the highest sequence inserted. Nothing checks the
324	/// sequence otherwise: datagrams are unordered, so a repeat or an older one is delivered.
325	pub fn insert(&mut self, datagram: Datagram) -> Result<()> {
326		let mut state = self.state.lock();
327		self.push(&mut state, datagram)
328	}
329
330	fn push(&self, state: &mut State, mut datagram: Datagram) -> Result<()> {
331		if datagram.payload.len() > MAX_PAYLOAD {
332			return Err(Error::FrameTooLarge);
333		}
334		state.closed()?;
335		datagram.timestamp = self.info.rescale(datagram.timestamp)?;
336		// A scale-less datagram's timestamp is its sequence.
337		if datagram.timestamp.scale().is_none() && datagram.timestamp.value() != datagram.sequence {
338			return Err(Error::TimestampMismatch);
339		}
340		self.stats.meter().datagram(datagram.payload.len() as u64);
341		state.push(datagram);
342		Ok(())
343	}
344
345	/// A new consumer of the track, starting with the next datagram written.
346	pub fn consume(&self) -> Consumer {
347		Consumer::join(
348			self.name.clone(),
349			&self.state,
350			stats::Scope::default(),
351			Some(DEFAULT_PRIORITY),
352		)
353		.unwrap_or_else(|| Consumer::ended(self.name.clone(), &self.state))
354	}
355
356	/// End the track cleanly: consumers read `None` once they have read what is buffered.
357	pub fn finish(self) {
358		let unlist = self.state.lock().end(Ok(()));
359		drop(unlist);
360	}
361
362	/// End the track with an error.
363	pub fn abort(self, err: Error) {
364		let unlist = self.state.lock().end(Err(err));
365		drop(unlist);
366	}
367
368	/// The highest subscriber priority among the track's consumers, or `None` when it has none.
369	pub fn priority(&self) -> Option<i8> {
370		self.state.read().priority()
371	}
372
373	/// [`priority`](Self::priority) once it differs from what this handle last returned:
374	/// immediately on the first call, then on each change.
375	#[cfg_attr(feature = "async", kio::wrapper)]
376	pub fn poll_priority_changed(&mut self, waiter: &kio::Waiter) -> Poll<Option<i8>> {
377		let priority = match self.prev {
378			None => self.priority(),
379			Some(last) => ready!(self.poll_priority(waiter, last)),
380		};
381		self.prev = Some(priority);
382		Poll::Ready(priority)
383	}
384
385	/// Resolves to [`Self::priority`] once it differs from `last`.
386	#[cfg_attr(not(feature = "async"), allow(dead_code, reason = "async-only"))]
387	pub(crate) fn poll_priority(&self, waiter: &kio::Waiter, last: Option<i8>) -> Poll<Option<i8>> {
388		let state = ready!(self.state.poll(waiter, |state| match state.priority() == last {
389			true => Poll::Pending,
390			false => Poll::Ready(()),
391		}));
392		Poll::Ready(state.priority())
393	}
394
395	/// Ready once the track has no consumer; see [`Self::close_unused`].
396	#[cfg_attr(not(feature = "async"), allow(dead_code, reason = "async-only"))]
397	pub(crate) fn poll_unused(&self, waiter: &kio::Waiter) -> Poll<()> {
398		let _state = ready!(self.state.poll(waiter, |state| match state.priorities.is_empty() {
399			true => Poll::Ready(()),
400			false => Poll::Pending,
401		}));
402		Poll::Ready(())
403	}
404
405	/// End the track with [`Error::Cancel`] if it has no consumer, returning whether it ended.
406	///
407	/// Atomic with a consumer joining, so a session letting an unread track go never strands
408	/// a reader that arrived meanwhile: that reader either keeps the track or finds it ended
409	/// and asks for it again.
410	#[cfg_attr(not(feature = "async"), allow(dead_code, reason = "async-only"))]
411	pub(crate) fn close_unused(&self) -> bool {
412		let mut state = self.state.lock();
413		if !state.priorities.is_empty() {
414			return false;
415		}
416		let unlist = state.end(Err(Error::Cancel));
417		drop(state);
418		drop(unlist);
419		true
420	}
421
422	/// Whether this is the same track as `other`.
423	#[cfg_attr(not(feature = "async"), allow(dead_code, reason = "async-only"))]
424	pub(crate) fn is_clone(&self, other: &Self) -> bool {
425		self.state.is_clone(&other.state)
426	}
427}
428
429impl Clone for Producer {
430	fn clone(&self) -> Self {
431		self.state.lock().producers += 1;
432		Self {
433			name: self.name.clone(),
434			info: self.info,
435			state: self.state.clone(),
436			stats: self.stats.clone(),
437			prev: None,
438		}
439	}
440}
441
442impl Drop for Producer {
443	fn drop(&mut self) {
444		let mut state = self.state.lock();
445		state.producers -= 1;
446		if state.producers == 0 {
447			let unlist = state.end(Err(Error::Dropped));
448			drop(state);
449			drop(unlist);
450		}
451	}
452}
453
454/// A datagram track a consumer asked for that a handler has yet to serve.
455///
456/// Yielded by [`broadcast::DatagramRequests::poll_requested`](crate::broadcast::DatagramRequests::poll_requested).
457/// [`Self::accept`] it with the track's [`Info`] to start producing, or [`Self::reject`] it.
458/// Dropping it rejects it with [`Error::Dropped`].
459pub struct Request {
460	producer: Producer,
461}
462
463impl Request {
464	pub(super) fn new(name: Arc<str>) -> Self {
465		Self {
466			producer: Producer::new(name, None),
467		}
468	}
469
470	pub(super) fn with_stats(mut self, scope: stats::Scope) -> Self {
471		self.producer = self.producer.with_stats(scope);
472		self
473	}
474
475	pub(super) fn weak(&self) -> Weak {
476		self.producer.weak()
477	}
478
479	/// The requested track's name.
480	pub fn name(&self) -> &str {
481		self.producer.name()
482	}
483
484	/// Whether the request ended, such as by its last waiting consumer leaving.
485	pub(super) fn is_closed(&self) -> bool {
486		self.producer.state.read().end.is_some()
487	}
488
489	/// The highest subscriber priority among the consumers waiting, or `None` once they all left.
490	pub fn priority(&self) -> Option<i8> {
491		self.producer.priority()
492	}
493
494	/// [`Producer::poll_unused`] for a request.
495	#[cfg_attr(not(feature = "async"), allow(dead_code, reason = "async-only"))]
496	pub(crate) fn poll_unused(&self, waiter: &kio::Waiter) -> Poll<()> {
497		self.producer.poll_unused(waiter)
498	}
499
500	/// [`Producer::close_unused`] for a request nobody waits for any more.
501	#[cfg_attr(not(feature = "async"), allow(dead_code, reason = "async-only"))]
502	pub(crate) fn close_unused(&self) -> bool {
503		self.producer.close_unused()
504	}
505
506	/// Serve the track with `info`, returning its producer.
507	pub fn accept(self, info: Info) -> Producer {
508		let mut producer = self.producer;
509		producer.state.lock().info = Some(info);
510		producer.info = info;
511		producer
512	}
513
514	/// Refuse the track: its consumers read `err`.
515	pub fn reject(self, err: Error) {
516		self.producer.abort(err);
517	}
518}
519
520/// Reads a datagram track's datagrams, in arrival order, from when it was created.
521///
522/// Each consumer holds a subscriber priority that the track's publisher sees aggregated as
523/// the highest among its consumers. A clone keeps the original's priority and position.
524pub struct Consumer {
525	name: Arc<str>,
526	state: kio::Shared<State>,
527	// This consumer's entry in `State::priorities`, or `None` for one created on an ended track.
528	slot: Option<usize>,
529	// The absolute index of the next datagram to read.
530	cursor: u64,
531	stats: stats::Scope,
532	// A wire publisher counts each datagram once the transport takes it, see [`Self::delegate`].
533	delegated: bool,
534}
535
536impl Consumer {
537	/// Join a live track, or `None` once it ended.
538	fn join(name: Arc<str>, state: &kio::Shared<State>, stats: stats::Scope, priority: Option<i8>) -> Option<Self> {
539		let mut guard = state.lock();
540		if guard.end.is_some() {
541			return None;
542		}
543		let slot = guard.priorities.insert(priority);
544		let cursor = guard.offset + guard.buffer.len() as u64;
545		drop(guard);
546		Some(Self {
547			name,
548			state: state.clone(),
549			slot: Some(slot),
550			cursor,
551			stats,
552			delegated: false,
553		})
554	}
555
556	fn ended(name: Arc<str>, state: &kio::Shared<State>) -> Self {
557		// Past what a finish left buffered, which is for the consumers already reading.
558		let cursor = {
559			let state = state.read();
560			state.offset + state.buffer.len() as u64
561		};
562		Self {
563			name,
564			state: state.clone(),
565			slot: None,
566			cursor,
567			stats: stats::Scope::default(),
568			delegated: false,
569		}
570	}
571
572	/// Stop counting datagrams as they are read, and return the scope a wire publisher
573	/// counts each one under once the transport takes it.
574	#[cfg_attr(not(feature = "async"), allow(dead_code, reason = "async-only"))]
575	pub(crate) fn delegate(&mut self) -> stats::Scope {
576		self.delegated = true;
577		self.stats.clone()
578	}
579
580	pub(super) fn with_stats(mut self, scope: stats::Scope) -> Self {
581		self.stats = scope;
582		self
583	}
584
585	/// The track's name within its broadcast.
586	pub fn name(&self) -> &str {
587		&self.name
588	}
589
590	/// The track's properties, once its publisher accepted it.
591	#[cfg_attr(feature = "async", kio::wrapper)]
592	pub fn poll_info(&self, waiter: &kio::Waiter) -> Poll<Result<Info>> {
593		let state = ready!(
594			self.state
595				.poll(waiter, |state| match state.info.is_some() || state.end.is_some() {
596					true => Poll::Ready(()),
597					false => Poll::Pending,
598				})
599		);
600		match (state.info, &state.end) {
601			(Some(info), _) => Poll::Ready(Ok(info)),
602			(None, Some(Err(err))) => Poll::Ready(Err(err.clone())),
603			(None, _) => Poll::Ready(Err(Error::Closed)),
604		}
605	}
606
607	/// The next datagram, or `None` once the track finished and this consumer read what it
608	/// buffered. An aborted track errors at once.
609	///
610	/// A consumer that fell behind skips the datagrams the track no longer holds.
611	#[cfg_attr(feature = "async", kio::wrapper)]
612	pub fn poll_recv(&mut self, waiter: &kio::Waiter) -> Poll<Result<Option<Datagram>>> {
613		let cursor = self.cursor;
614		let state = ready!(self.state.poll(waiter, |state| {
615			match state.end.is_some() || state.has_next(cursor) {
616				true => Poll::Ready(()),
617				false => Poll::Pending,
618			}
619		}));
620		// Buffered datagrams first: a finished track still delivers them.
621		if !state.has_next(cursor) {
622			let end = state.end.clone().expect("ready only once ended or buffered");
623			return Poll::Ready(end.map(|()| None));
624		}
625		let index = self.cursor.max(state.offset);
626		let datagram = state.buffer[(index - state.offset) as usize].clone();
627		drop(state);
628		self.cursor = index + 1;
629		if !self.delegated {
630			self.stats.meter().datagram(datagram.payload.len() as u64);
631		}
632		Poll::Ready(Ok(Some(datagram)))
633	}
634
635	/// This consumer's subscriber priority.
636	pub fn priority(&self) -> i8 {
637		self.slot
638			.and_then(|slot| self.state.read().priorities.get(slot).copied().flatten())
639			.unwrap_or(DEFAULT_PRIORITY)
640	}
641
642	/// Set this consumer's subscriber priority, higher first.
643	pub fn set_priority(&mut self, priority: i8) {
644		if let Some(slot) = self.slot {
645			self.state.lock().priorities[slot] = Some(priority);
646		}
647	}
648
649	/// Another consumer at the same position that adds no demand, until its priority is set.
650	#[cfg_attr(not(feature = "async"), allow(dead_code, reason = "async-only"))]
651	pub(crate) fn observe(&self) -> Self {
652		let slot = self.slot.map(|_| self.state.lock().priorities.insert(None));
653		Self {
654			name: self.name.clone(),
655			state: self.state.clone(),
656			slot,
657			cursor: self.cursor,
658			stats: self.stats.clone(),
659			delegated: false,
660		}
661	}
662
663	/// Whether this reads the same track as `other`.
664	#[cfg_attr(not(feature = "async"), allow(dead_code, reason = "async-only"))]
665	pub(crate) fn is_clone(&self, other: &Self) -> bool {
666		self.state.is_clone(&other.state)
667	}
668}
669
670impl Clone for Consumer {
671	fn clone(&self) -> Self {
672		let slot = self.slot.map(|slot| {
673			let mut state = self.state.lock();
674			let priority = state.priorities[slot];
675			state.priorities.insert(priority)
676		});
677		Self {
678			name: self.name.clone(),
679			state: self.state.clone(),
680			slot,
681			cursor: self.cursor,
682			stats: self.stats.clone(),
683			delegated: self.delegated,
684		}
685	}
686}
687
688impl Drop for Consumer {
689	fn drop(&mut self) {
690		if let Some(slot) = self.slot {
691			let mut state = self.state.lock();
692			state.priorities.remove(slot);
693			// Nobody waits for a request no handler accepted yet: withdraw it, so a handler
694			// that stops polling never holds requests nobody reads.
695			if state.priorities.is_empty() && state.info.is_none() {
696				let unlisted = state.end(Err(Error::Cancel));
697				debug_assert!(
698					unlisted.is_none(),
699					"only a created track is listed, and it has its info"
700				);
701			}
702			// The last reader of a finished track leaves what it never read.
703			if state.priorities.is_empty() && state.end.is_some() {
704				state.release();
705			}
706		}
707	}
708}
709
710#[cfg(test)]
711mod tests {
712	use super::*;
713
714	fn recv(consumer: &mut Consumer) -> Poll<Result<Option<Datagram>>> {
715		consumer.poll_recv(&kio::Waiter::noop())
716	}
717
718	/// A scale-less datagram's timestamp: its sequence.
719	fn seq(sequence: u64) -> Timestamp {
720		Timestamp::unscaled(sequence)
721	}
722
723	fn ms(millis: u64) -> Timestamp {
724		Timestamp::from_millis(millis).unwrap()
725	}
726
727	fn sequence(consumer: &mut Consumer) -> u64 {
728		match recv(consumer) {
729			Poll::Ready(Ok(Some(datagram))) => datagram.sequence,
730			other => panic!("expected a datagram, got {other:?}"),
731		}
732	}
733
734	#[test]
735	fn passive_forwarding_keeps_the_tail_without_adding_demand() {
736		let mut producer = Info::default().produce("audio");
737		let mut observer = producer.weak().observe(stats::Scope::default()).unwrap();
738		let mut copy = observer.clone();
739		assert_eq!(producer.priority(), None);
740		let mut reader = producer.consume();
741		reader.set_priority(-7);
742		assert_eq!(producer.priority(), Some(-7));
743		drop(reader);
744		assert_eq!(producer.priority(), None);
745		producer.append(seq(0), &b"tail"[..]).unwrap();
746		producer.finish();
747		for consumer in [&mut observer, &mut copy] {
748			let Poll::Ready(Ok(Some(datagram))) = consumer.poll_recv(&kio::Waiter::noop()) else {
749				panic!("tail lost");
750			};
751			assert_eq!(datagram.payload.as_ref(), b"tail");
752			assert!(matches!(
753				consumer.poll_recv(&kio::Waiter::noop()),
754				Poll::Ready(Ok(None))
755			));
756		}
757	}
758
759	#[test]
760	fn append_counts_its_own_sequence_past_inserts() {
761		let mut producer = Info::default().with_timescale(Timescale::MILLI).produce("dg");
762		let mut consumer = producer.consume();
763		assert_eq!(producer.append(ms(0), "a").unwrap(), 0);
764		producer
765			.insert(Datagram {
766				sequence: 10,
767				timestamp: ms(10),
768				payload: Bytes::from_static(b"b"),
769			})
770			.unwrap();
771		// An older one is still delivered, and moves nothing back.
772		producer
773			.insert(Datagram {
774				sequence: 3,
775				timestamp: ms(3),
776				payload: Bytes::from_static(b"c"),
777			})
778			.unwrap();
779		assert_eq!(producer.append(ms(11), "d").unwrap(), 11);
780		let got: Vec<u64> = (0..4).map(|_| sequence(&mut consumer)).collect();
781		assert_eq!(got, [0, 10, 3, 11]);
782		assert!(recv(&mut consumer).is_pending());
783	}
784
785	/// Past `u64::MAX` no sequence remains, so `append` refuses instead of repeating it.
786	#[test]
787	fn append_refuses_once_the_sequence_is_spent() {
788		let mut producer = Info::default().with_timescale(Timescale::MILLI).produce("dg");
789		producer
790			.insert(Datagram {
791				sequence: u64::MAX,
792				timestamp: ms(0),
793				payload: Bytes::from_static(b"last"),
794			})
795			.unwrap();
796		assert!(matches!(producer.append(ms(1), "x"), Err(Error::BoundsExceeded(_))));
797	}
798
799	#[test]
800	fn a_consumer_starts_live() {
801		let mut producer = Info::default().produce("dg");
802		producer.append(seq(0), "old").unwrap();
803		let mut consumer = producer.consume();
804		assert!(recv(&mut consumer).is_pending());
805		producer.append(seq(1), "new").unwrap();
806		assert_eq!(sequence(&mut consumer), 1);
807	}
808
809	#[test]
810	fn a_slow_consumer_skips_to_the_oldest_held() {
811		let mut producer = Info::default().produce("dg");
812		let mut consumer = producer.consume();
813		for sequence in 0..MAX_BUFFERED as u64 + 5 {
814			producer.append(seq(sequence), "x").unwrap();
815		}
816		assert_eq!(sequence(&mut consumer), 5);
817	}
818
819	#[test]
820	fn a_slow_consumer_holds_a_bounded_number_of_bytes() {
821		let mut producer = Info::default().produce("dg");
822		let mut consumer = producer.consume();
823		let payload = Bytes::from(vec![0; MAX_BUFFERED_BYTES / 4]);
824		for sequence in 0..8 {
825			producer.append(seq(sequence), payload.clone()).unwrap();
826		}
827		// Four fit, so the oldest four went.
828		assert_eq!(sequence(&mut consumer), 4);
829		// The newest is always held, even alone over the budget.
830		let mut producer = Info::default().produce("dg");
831		let mut consumer = producer.consume();
832		for sequence in 0..2 {
833			producer.append(seq(sequence), vec![0; MAX_PAYLOAD]).unwrap();
834		}
835		assert_eq!(sequence(&mut consumer), 1);
836	}
837
838	#[test]
839	fn timestamps_must_match_the_track() {
840		let mut timed = Info::default().with_timescale(Timescale::MILLI).produce("dg");
841		let mut consumer = timed.consume();
842		assert!(matches!(timed.append(seq(0), "x"), Err(Error::TimestampMismatch)));
843		timed.append(Timestamp::from_secs(1).unwrap(), "x").unwrap();
844		let Poll::Ready(Ok(Some(datagram))) = recv(&mut consumer) else {
845			panic!("expected a datagram");
846		};
847		// Converted into the track's scale.
848		assert_eq!(datagram.timestamp, Timestamp::from_millis(1000).unwrap());
849		let mut untimed = Info::default().produce("dg");
850		assert!(matches!(
851			untimed.append(Timestamp::from_secs(1).unwrap(), "x"),
852			Err(Error::TimestampMismatch)
853		));
854		// A scale-less datagram's timestamp names its sequence, so another is a mismatch.
855		let wrong = Datagram {
856			sequence: 4,
857			timestamp: seq(5),
858			payload: Bytes::from_static(b"x"),
859		};
860		assert!(matches!(untimed.insert(wrong), Err(Error::TimestampMismatch)));
861		assert_eq!(untimed.append(seq(4), "x").unwrap(), 4);
862	}
863
864	#[test]
865	fn the_end_reaches_consumers() {
866		let mut producer = Info::default().produce("dg");
867		let mut finished = producer.consume();
868		producer.clone().finish();
869		assert!(matches!(recv(&mut finished), Poll::Ready(Ok(None))));
870		assert!(matches!(producer.append(seq(0), "x"), Err(Error::Closed)));
871
872		let producer = Info::default().produce("dg");
873		let mut dropped = producer.consume();
874		drop(producer);
875		assert!(matches!(recv(&mut dropped), Poll::Ready(Err(Error::Dropped))));
876	}
877
878	#[test]
879	fn a_finish_delivers_what_is_buffered() {
880		let mut producer = Info::default().produce("dg");
881		let mut consumer = producer.consume();
882		producer.append(seq(0), "a").unwrap();
883		producer.append(seq(1), "b").unwrap();
884		producer.finish();
885		assert_eq!(sequence(&mut consumer), 0);
886		assert_eq!(sequence(&mut consumer), 1);
887		assert!(matches!(recv(&mut consumer), Poll::Ready(Ok(None))));
888
889		// A consumer arriving after the finish never reads them.
890		let mut producer = Info::default().produce("dg");
891		let _reading = producer.consume();
892		producer.append(seq(0), "a").unwrap();
893		producer.clone().finish();
894		let mut late = producer.consume();
895		assert!(matches!(recv(&mut late), Poll::Ready(Ok(None))));
896
897		// Nobody left to read them, they go: on a finish with no consumer, or with the last
898		// consumer of a finished track.
899		let mut producer = Info::default().produce("dg");
900		producer.append(seq(0), "a").unwrap();
901		producer.clone().finish();
902		assert!(producer.state.read().buffer.is_empty());
903		let mut producer = Info::default().produce("dg");
904		let reading = producer.consume();
905		producer.append(seq(0), "a").unwrap();
906		producer.clone().finish();
907		assert_eq!(producer.state.read().buffer.len(), 1);
908		drop(reading);
909		assert!(producer.state.read().buffer.is_empty());
910		assert_eq!(producer.state.read().bytes, 0);
911
912		// An abort drops them.
913		let mut producer = Info::default().produce("dg");
914		let mut consumer = producer.consume();
915		producer.append(seq(0), "a").unwrap();
916		producer.abort(Error::Cancel);
917		assert!(matches!(recv(&mut consumer), Poll::Ready(Err(Error::Cancel))));
918	}
919
920	#[test]
921	fn the_publisher_sees_the_highest_priority() {
922		let producer = Info::default().produce("dg");
923		assert_eq!(producer.priority(), None);
924		let mut low = producer.consume();
925		let mut high = low.clone();
926		high.set_priority(5);
927		low.set_priority(-3);
928		assert_eq!(producer.priority(), Some(5));
929		assert!(producer.poll_priority(&kio::Waiter::noop(), Some(5)).is_pending());
930		drop(high);
931		assert_eq!(
932			producer.poll_priority(&kio::Waiter::noop(), Some(5)),
933			Poll::Ready(Some(-3))
934		);
935		assert!(!producer.close_unused());
936		drop(low);
937		assert!(producer.close_unused());
938	}
939
940	#[test]
941	fn priority_changed_reports_the_current_value_then_each_change() {
942		let waiter = kio::Waiter::noop();
943		let mut producer = Info::default().produce("dg");
944		assert_eq!(producer.poll_priority_changed(&waiter), Poll::Ready(None));
945		assert!(producer.poll_priority_changed(&waiter).is_pending());
946		let mut consumer = producer.consume();
947		consumer.set_priority(4);
948		assert_eq!(producer.poll_priority_changed(&waiter), Poll::Ready(Some(4)));
949		assert!(producer.poll_priority_changed(&waiter).is_pending());
950		// A clone watches on its own, starting from the current value.
951		let mut clone = producer.clone();
952		assert_eq!(clone.poll_priority_changed(&waiter), Poll::Ready(Some(4)));
953		drop(consumer);
954		assert_eq!(producer.poll_priority_changed(&waiter), Poll::Ready(None));
955	}
956
957	#[test]
958	fn a_request_resolves_its_consumers() {
959		let request = Request::new("dg".into());
960		let consumer = request.weak().try_consume(stats::Scope::default()).unwrap();
961		assert!(consumer.poll_info(&kio::Waiter::noop()).is_pending());
962		let info = Info::default().with_priority(3);
963		let _producer = request.accept(info);
964		assert!(matches!(consumer.poll_info(&kio::Waiter::noop()), Poll::Ready(Ok(got)) if got == info));
965
966		let request = Request::new("dg".into());
967		let mut consumer = request.weak().try_consume(stats::Scope::default()).unwrap();
968		request.reject(Error::NotFound);
969		assert!(matches!(recv(&mut consumer), Poll::Ready(Err(Error::NotFound))));
970		assert!(matches!(
971			consumer.poll_info(&kio::Waiter::noop()),
972			Poll::Ready(Err(Error::NotFound))
973		));
974	}
975}