Skip to main content

moq_net/model/
subscription.rs

1use std::{
2	collections::BTreeMap,
3	ops::{Bound, RangeBounds},
4	time::Duration,
5};
6
7mod cover;
8mod window;
9pub(super) use cover::{Cover, minus};
10pub(crate) use window::Accounted;
11pub(crate) use window::Resolved;
12pub(super) use window::{Budget, Containing, Found, Holdings, Join, Joining, Unheld, Unplaced, Window};
13
14/// Subscriber-side preferences for receiving a track.
15///
16/// Each subscriber holds its own [`Subscription`]; the publisher observes an
17/// aggregate across all live subscribers via [`crate::track::Producer::subscription`].
18/// A subscriber can change its preferences after the fact with
19/// [`crate::track::Subscriber::update`].
20#[derive(Clone, Debug, PartialEq, Eq)]
21#[non_exhaustive]
22pub struct Subscription {
23	/// The spans of the track to deliver; see [`Range`].
24	///
25	/// The default is one range from [`Start::LATEST`]: the latest group, skipping each the
26	/// moment a newer one arrives. An empty list asks for nothing.
27	///
28	/// A request to the publisher, aggregated across every live subscriber as the union of
29	/// their ranges, and this subscriber's read filter: it reads only the groups its own
30	/// ranges cover, whatever another subscriber widens the union to.
31	/// [`crate::track::Subscriber::with_range`] narrows the reads further. See [Local cursor
32	/// vs wire preference](crate::track::Subscriber#local-cursor-vs-wire-preference).
33	pub ranges: Vec<Range>,
34	/// Whether this reader needs the source's live feed, not only its history: a wire
35	/// publisher owes its peer an answer naming the live edge, which only the upstream's own
36	/// answer gives. A session holding no upstream subscription for its copy subscribes again
37	/// for such a reader, whatever its ranges. Aggregated as any: one such reader is enough.
38	pub(crate) feed: bool,
39	/// Whether this read, a session serving its peer, adds no demand while every range lies
40	/// at or below the newest group the track reached: it reads the cache and its misses go to
41	/// the track's fills, as a fetch's do, so neither the publisher nor a relay's upstream sees
42	/// it. Never aggregated.
43	pub(crate) history: bool,
44	/// The frames this reader already holds of the group a range starts at, so that range asks
45	/// for it from the frame after them rather than whole: a route switch resuming on a new
46	/// copy. Only a range whose start is exactly that group's start uses
47	/// it. Aggregated only when every reader resumes: the lowest position then.
48	pub(crate) resume: Option<Position>,
49	/// The group each live join among [`Self::ranges`] was already placed at, by its index
50	/// there: a route switch asks a new copy for a join an earlier copy placed, which starts at
51	/// that group as a time start would and still goes stale past its `max`. Its lag places
52	/// nothing. moq-lite-07 carries one as a `Joined` start; older wires as a time start under
53	/// the one max age, which takes its `max` (see [`Self::start`] and [`Self::max_age`]).
54	pub(crate) placed: BTreeMap<u64, u64>,
55	/// Where a range ending at that group stops: before this frame, rather than through the
56	/// group's end. A route switch capping the copy it replaces where the new one resumes (see
57	/// [`Self::resume`]). Only a range whose end is exactly that group's start uses it.
58	/// Aggregated only when every reader caps: the highest position then. Only lite-07
59	/// carries it; an older wire ends at the group's end.
60	pub(crate) cap: Option<Position>,
61	/// The time starts a received copy's readers wait on: the copy can't prove where the
62	/// publisher would start them, so its session asks its upstream with a range of its own
63	/// from each, sorted. Only an aggregate holds any.
64	pub(crate) asks: Vec<u64>,
65	/// The live joins a received copy's readers wait on: the copy can't prove where the
66	/// publisher would start them, so its session asks its upstream with a range of its own
67	/// for each that no unanswered range answers. Only an aggregate holds any.
68	pub(crate) joins: Vec<JoinAsk>,
69}
70
71/// A live join a received copy's readers wait on, by its [`Start::Live`] lag and its end, with
72/// the widest staleness budget one waits with and the newest answer any of them saw before it
73/// began waiting: only an answer recorded after that is fresh for every one of them.
74#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
75pub(crate) struct JoinAsk {
76	pub min: Option<Duration>,
77	pub end: Option<u64>,
78	/// The widest [`Start::Live`] `max` among the readers waiting, as a budget.
79	pub budget: Duration,
80	pub since: u64,
81}
82
83impl JoinAsk {
84	/// The widest [`Start::Live`] `max` among the readers waiting.
85	#[cfg_attr(not(feature = "async"), allow(dead_code, reason = "async-only"))]
86	pub(crate) fn max(&self) -> Option<Duration> {
87		max_of(self.budget)
88	}
89}
90
91/// The widest staleness budget `ranges` give a group: none while a history range is asked
92/// for, and otherwise the largest live join's `max`.
93pub(super) fn widest<'a>(ranges: impl IntoIterator<Item = &'a Range>) -> Duration {
94	(ranges.into_iter())
95		.filter(|range| !range.is_empty())
96		.map(Range::budget)
97		.max()
98		.unwrap_or(Duration::ZERO)
99}
100
101/// A [`Start::Live`] `max` as a budget: `None` waits as long as anything could.
102pub(crate) fn budget(max: Option<Duration>) -> Duration {
103	max.unwrap_or(Duration::MAX)
104}
105
106/// A budget as a [`Start::Live`] `max`: `Duration::MAX` is no limit.
107pub(crate) fn max_of(budget: Duration) -> Option<Duration> {
108	Some(budget).filter(|budget| *budget != Duration::MAX)
109}
110
111/// Which of a subscription's groups comes first: the publisher sends its pending groups in
112/// this order, and `recv_group` hands out the groups it holds in it. Before moq-lite-07 the
113/// publisher sends newest first whatever this asks.
114///
115/// An order only: it never decides *whether* a group is delivered. A history
116/// range ([`Start::Time`] or [`Start::Oldest`]) delivers every group it covers, and a
117/// [`Start::Live`] range skips what its `max` judges stale, so an ascending subscriber that
118/// wants a backlog drains it from a history range or a `max` that covers it.
119#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]
120pub enum Order {
121	/// Oldest first, draining a backlog in key order.
122	Ascending,
123	/// Newest first, so congestion sheds the backlog rather than the live edge.
124	#[default]
125	Descending,
126}
127
128/// A span of a track to deliver: from where [`Self::start`] places it through the group
129/// containing `end`, a time in the track's timescale (a bare start on a scale-less track).
130///
131/// Every range names whole groups: a subscription always starts at a group's first frame,
132/// since a group is the unit of decodability, and an end includes its group. A range from
133/// [`Start::Time`] 2 through 6 delivers every group from the one containing time 2 through the
134/// one containing time 6. An end before a time start is empty.
135///
136/// Only a group reached through a [`Start::Live`] range alone can go stale. A group several
137/// ranges cover takes the largest `max` among them, and never goes stale while any history
138/// range covers it.
139///
140/// Each range carries its own [`Self::priority`] and [`Self::order`], so one subscription can
141/// follow the live edge urgently while it backfills history at a lower priority.
142#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
143pub struct Range {
144	/// Where delivery starts; see [`Start`].
145	pub start: Start,
146	/// Where delivery stops, including the group containing this time, or `None` to keep
147	/// following the live edge.
148	pub end: Option<u64>,
149	/// How urgently this range's groups go out, higher first, defaulting to 0. Higher values
150	/// preempt lower ones when bandwidth is constrained. A group several ranges cover goes out
151	/// at the highest priority among the ranges still wanting it.
152	pub priority: i8,
153	/// Which of this range's pending groups the publisher sends first, and the order
154	/// `recv_group` hands them out in; see [`Order`]. Among ranges of one priority, any
155	/// [`Order::Descending`] one wins, so a live range sheds the backlog first.
156	pub order: Order,
157}
158
159/// A range's priority and group order: how urgently, and in what order, its groups go out.
160#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]
161pub(crate) struct Policy {
162	/// Higher goes out first; 0 is the midpoint.
163	pub priority: i8,
164	/// Which pending group goes out first.
165	pub order: Order,
166}
167
168impl Policy {
169	/// What `policies` ask as a whole, as a wire without a policy per range carries it: the
170	/// highest priority, newest first if any at that priority is. The default without any.
171	pub(crate) fn top(policies: impl IntoIterator<Item = Self>) -> Self {
172		policies
173			.into_iter()
174			.reduce(|top, policy| match top.covers(&policy) {
175				true => top,
176				false => policy,
177			})
178			.unwrap_or_default()
179	}
180
181	/// What `ranges` ask as a whole; see [`Self::top`].
182	pub(crate) fn of<'a>(ranges: impl IntoIterator<Item = &'a Range>) -> Self {
183		Self::top(ranges.into_iter().map(Range::policy))
184	}
185
186	/// Whether a group sent at this policy already serves one asked at `other`, so a range at
187	/// `other` that this one's ranges cover adds nothing: a higher priority, or the same one in
188	/// the same order or newest first, which wins a tie.
189	pub(crate) fn covers(&self, other: &Self) -> bool {
190		self.priority > other.priority
191			|| (self.priority == other.priority && (self.order == other.order || self.order == Order::Descending))
192	}
193
194	/// A key sorting every policy after each one that [covers](Self::covers) it.
195	pub(crate) fn rank(&self) -> (std::cmp::Reverse<i8>, std::cmp::Reverse<Order>) {
196		(std::cmp::Reverse(self.priority), std::cmp::Reverse(self.order))
197	}
198}
199
200/// Where a [`Range`] starts.
201///
202/// This is the `Start` Anchor on the moq-lite wire.
203#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
204pub enum Start {
205	/// The oldest group the publisher still holds: a floor for history, whose groups are
206	/// delivered in full, bounded only by how long the publisher keeps them
207	/// ([`Info::max_age`](crate::track::Info::max_age)).
208	Oldest,
209	/// The group containing this time: the newest one starting at or before it, unless that group
210	/// ended whole at or before the time ([`group::Producer::finish_at`](crate::group::Producer::finish_at)).
211	/// A time past a whole group's span lies in a pause no group contains, so the range starts at
212	/// the next group. A floor for history, like [`Self::Oldest`]: its groups never go stale.
213	///
214	/// A time resolves at the hop that serves it, from the starts of the groups it holds. When
215	/// none does, a hop whose [`Requests`](crate::track::Requests) handler serves its history
216	/// asks it for the group containing the time (see
217	/// [`FillGroups::floor`](crate::track::FillGroups::floor)), reading nothing until it
218	/// answers; otherwise, or when the handler can't tell, it reaches back to the oldest group.
219	/// While no group is held at all it waits for one, reading nothing of its range meanwhile.
220	/// A relay's copy that can't tell which group contains a time asks its upstream and waits
221	/// for the answer.
222	Time(u64),
223	/// A live join `min` behind the live edge, whose groups go stale `max` behind it.
224	///
225	/// Carried in whole milliseconds, rounded up. moq-lite before 07 and moq-transport cannot
226	/// carry it, so it goes out as [`Self::Oldest`] there, under the subscription-wide max age
227	/// those wires carry instead.
228	Live {
229		/// How far behind the live edge to join: the group containing the live edge minus this
230		/// lag, so a player's buffer arrives full instead of filling in real time, and zero
231		/// starts at the latest group. `None` sets no lag limit: the join reaches back past
232		/// every group, taking each one `max` still allows.
233		///
234		/// The hop serving it measures the live edge in media time, from the newest frame it
235		/// holds, rounded up to whole ticks, and on a scale-less track by arrival on its own
236		/// clock. It resolves that time as a [`Self::Time`] start would, so a publisher looks it
237		/// up in its history, then starts past any group there that `max` already expired. A relay's copy forwards each join to its
238		/// upstream as its own range and starts it where that range's answer does. A range
239		/// resolves once, so a live edge that moves later moves nothing already started.
240		min: Option<Duration>,
241		/// How long a superseded group stays worth delivering, measured from the live edge, or
242		/// `None` for as long as the publisher keeps it.
243		///
244		/// `Some(Duration::ZERO)` skips immediately: group 8 arriving means group 7 is
245		/// abandoned, timed or not. A larger budget tolerates that much reordering before
246		/// giving up. This never *adds* delay, since the bound is only reached once newer data
247		/// is already that far ahead. Read in order, `None` waits at a missing group until it
248		/// resolves; see [`track::Ordered`](crate::track::Ordered) for where that can block.
249		/// A `max` below `min` skips the join's own oldest groups.
250		///
251		/// Changing only `max` on a range already live, with
252		/// [`Subscriber::update`](crate::track::Subscriber::update), keeps where it joined,
253		/// both here and upstream. Encoded as milliseconds in a QUIC varint, so a duration of
254		/// `2^62` milliseconds or more goes out as no limit. Clamped to the publisher's
255		/// [`Info::max_age`](crate::track::Info::max_age), since waiting for a group longer
256		/// than it is kept around cannot produce it.
257		///
258		/// # Where it is enforced
259		///
260		/// At both ends, and neither alone is enough. The publisher skips a group that has
261		/// aged out instead of putting it on the wire, which bounds a backlog before it
262		/// costs bandwidth. But what reaches the publisher is the aggregate across every
263		/// subscriber, resolved in favor of the most tolerant one, so that gate is only ever
264		/// as tight as the most patient viewer. The subscriber applies its own budget again
265		/// as it reads, where only its own ranges are in play.
266		///
267		/// This bounds a *subscription*.
268		/// [`track::Consumer::fetch_group`](crate::track::Consumer::fetch_group) is exempt:
269		/// it names one old group explicitly, so there is no live edge to be late against.
270		///
271		/// # How staleness is measured
272		///
273		/// By two clocks, and a group is stale once either reaches the budget. Both start at
274		/// its immediate servable successor, so the newest group is stale only once it finished
275		/// whole and the wall clock passed its arrival plus its span by the budget: the last group
276		/// of a paused or finished track ages out too.
277		///
278		/// In presentation time, a group is measured by its *reach*, where its successor
279		/// begins, against the newest frame of the latest group: it cannot present past its
280		/// successor, so once everything it could still hold falls outside the budget it is
281		/// provably useless. The candidate needs no timestamp of its own, so an empty or
282		/// stalled group is bounded by its stamped successor the same way.
283		///
284		/// In wall-clock time, a group is measured by how long ago its successor arrived at
285		/// this hop. That bounds what media time can't: a peer whose timestamps stop
286		/// advancing, a successor that never presents a frame, and an untimed track
287		/// (pre-Lite05 moq-lite, or moq-transport without TIMESCALE), which is judged by the
288		/// wall clock alone. A read waiting in a superseded group wakes at that deadline only
289		/// when something collects the track's cache pool: an origin's driver does, and a
290		/// standalone track needs [`Pool::poll`](crate::cache::Pool::poll) called, as its idle
291		/// expiry already does. Otherwise it is judged only when something else wakes the read.
292		max: Option<Duration>,
293	},
294}
295
296impl Start {
297	/// The latest group, skipping each the moment a newer one arrives: a live viewer holding
298	/// no buffer.
299	pub const LATEST: Self = Self::Live {
300		min: Some(Duration::ZERO),
301		max: Some(Duration::ZERO),
302	};
303
304	/// A live join with no lag limit, so it takes every group still within `max` of the live
305	/// edge: what a wire before lite-07 asks with its one `Subscriber Max Age` and no start.
306	#[cfg(any(feature = "async", test))]
307	pub(crate) const fn within(max: Duration) -> Self {
308		Self::Live {
309			min: None,
310			max: Some(max),
311		}
312	}
313}
314
315/// Every group from where the start places it, following the live edge, at priority 0 newest
316/// first.
317impl From<Start> for Range {
318	fn from(start: Start) -> Self {
319		Self {
320			start,
321			end: None,
322			priority: 0,
323			order: Order::Descending,
324		}
325	}
326}
327
328/// What [`Subscription::default`] asks: the latest group, skipping each the moment a newer one
329/// arrives, at priority 0 newest first.
330impl Default for Range {
331	fn default() -> Self {
332		Self::from(Start::LATEST)
333	}
334}
335
336impl Range {
337	/// Set the delivery priority, returning `self` for chaining.
338	pub fn with_priority(mut self, priority: i8) -> Self {
339		self.priority = priority;
340		self
341	}
342
343	/// Set which pending group the publisher sends first, returning `self` for chaining.
344	pub fn with_order(mut self, order: Order) -> Self {
345		self.order = order;
346		self
347	}
348
349	/// This range's priority and order.
350	pub(crate) fn policy(&self) -> Policy {
351		Policy {
352			priority: self.priority,
353			order: self.order,
354		}
355	}
356
357	/// This range at `policy`'s priority and order.
358	pub(crate) fn with_policy(self, policy: Policy) -> Self {
359		Self {
360			priority: policy.priority,
361			order: policy.order,
362			..self
363		}
364	}
365
366	/// Whether `other` names the same span whatever its policy and live join's `max`: the
367	/// change a reader retunes in place, keeping where the range started.
368	pub(crate) fn retunes(&self, other: &Self) -> bool {
369		let start = match (self.start, other.start) {
370			(Start::Live { min, .. }, Start::Live { min: other, .. }) => min == other,
371			(start, other) => start == other,
372		};
373		start && self.end == other.end
374	}
375
376	/// Whether this range, its start `placed` or not, reads only groups it names: empty, or
377	/// from an exact group (a lite-07 Position) through an end. Judged a range at a time, as
378	/// [`Subscription::exact_bounded`] judges every range.
379	pub(crate) fn exact_bounded(&self, placed: bool) -> bool {
380		self.is_empty() || placed && matches!(self.start, Start::Time(_)) && self.end.is_some_and(|end| end < u64::MAX)
381	}
382
383	/// Whether this range certainly delivers nothing, wherever the latest group lands.
384	pub(crate) fn is_empty(&self) -> bool {
385		matches!((self.start, self.end), (Start::Time(start), Some(end)) if end < start)
386	}
387
388	/// The time this range starts from, `None` when it doesn't name one.
389	pub(crate) fn time(&self) -> Option<u64> {
390		match self.start {
391			Start::Time(time) => Some(time),
392			Start::Oldest | Start::Live { .. } => None,
393		}
394	}
395
396	/// The staleness budget of the groups this range covers: its `max` for a live join, and
397	/// none for history.
398	pub(crate) fn budget(&self) -> Duration {
399		match self.start {
400			Start::Live { max, .. } => budget(max),
401			Start::Oldest | Start::Time(_) => Duration::MAX,
402		}
403	}
404
405	/// This range as a live join of the same lag and end, which a change of `max` alone
406	/// keeps: the key a join is placed and answered under.
407	pub(crate) fn join(&self) -> Option<(Option<Duration>, Option<u64>)> {
408		match self.start {
409			Start::Live { min, .. } => Some((min, self.end)),
410			Start::Oldest | Start::Time(_) => None,
411		}
412	}
413
414	/// Whether this range follows the live edge from no time: a live join, or one reaching
415	/// back from the oldest group, with no end.
416	pub(crate) fn is_open(&self) -> bool {
417		self.time().is_none() && self.end.is_none()
418	}
419
420	/// A range holding nothing: nothing sorts below group 0, so an exclusive end there holds
421	/// nothing, whatever the start.
422	pub(crate) const EMPTY: Self = Self {
423		start: Start::Time(1),
424		end: Some(0),
425		priority: 0,
426		order: Order::Descending,
427	};
428
429	/// Every group the publisher holds, following the live edge, at priority 0 newest first.
430	pub const ALL: Self = Self {
431		start: Start::Oldest,
432		end: None,
433		priority: 0,
434		order: Order::Descending,
435	};
436
437	/// Whether this range asks for every group the publisher holds, whatever its policy.
438	#[cfg_attr(not(feature = "async"), allow(dead_code, reason = "async-only"))]
439	pub(crate) fn is_all(&self) -> bool {
440		self.start == Start::Oldest && self.end.is_none()
441	}
442
443	/// The range from group `start` up to the exclusive group `end`, or onward for `None`:
444	/// what a legacy wire's bounds become. `None` when it holds nothing, which an exclusive
445	/// end of 0 says whatever the start.
446	#[cfg(any(feature = "async", test))]
447	pub(crate) fn span(start: Option<u64>, end: Option<u64>) -> Option<Self> {
448		let end = match end {
449			Some(end) => Some(end.checked_sub(1)?),
450			None => None,
451		};
452		let start = start.map_or(Start::Oldest, Start::Time);
453		let range = Self {
454			start,
455			end,
456			..Self::ALL
457		};
458		(!range.is_empty()).then_some(range)
459	}
460}
461
462/// A live join's lag in whole milliseconds, rounded up, as the wire carries it, so a start is
463/// never newer than the lag allows.
464pub(crate) fn live_millis(min: Duration) -> u64 {
465	u64::try_from(min.as_nanos().div_ceil(1_000_000)).unwrap_or(u64::MAX)
466}
467
468/// The union of `ranges` in a canonical order, without empty or redundant ranges: the
469/// reference for the track's incremental union.
470///
471/// Ranges of one [`Policy`] merge as [`spans`] does. Across policies a range folds only into
472/// what ranges at policies [covering](Policy::covers) its own already ask, since folding it
473/// anywhere else would lose its priority or order: it is dropped once those cover its span.
474#[cfg(test)]
475pub(super) fn union(ranges: impl IntoIterator<Item = Range>) -> Vec<Range> {
476	let mut classes = BTreeMap::<_, (Policy, Vec<Range>)>::new();
477	for range in ranges {
478		let policy = range.policy();
479		classes
480			.entry(policy.rank())
481			.or_insert((policy, Vec::new()))
482			.1
483			.push(range);
484	}
485	// Every policy before one in this order covers it.
486	let mut above: Vec<Range> = Vec::new();
487	let mut union = Vec::new();
488	for (policy, class) in classes.into_values() {
489		let merged = spans(class);
490		let covered = spans(above.iter().copied());
491		for range in &merged {
492			if spans(above.iter().copied().chain([*range])) != covered {
493				union.push(range.with_policy(policy));
494			}
495		}
496		above.extend(merged);
497	}
498	union.sort_unstable();
499	union
500}
501
502/// The union of `ranges`' spans whatever their policies, each at the default one.
503///
504/// Time spans merge where they overlap or touch, as the group starts they cover. The rest
505/// can't be placed without the live edge, so only an open range drops what it certainly
506/// covers: the open time span drops ranges starting inside it, and a range from the oldest
507/// group following the live edge covers everything. A live join reaches no further back than
508/// its lag, so it covers nothing else, and live joins of the same lag and end are one range
509/// under the largest `max` among them: where a join lands doesn't depend on it.
510#[cfg(test)]
511fn spans(ranges: impl IntoIterator<Item = Range>) -> Vec<Range> {
512	let ranges: Vec<Range> = (ranges.into_iter())
513		.filter(|range| !range.is_empty())
514		.map(|range| range.with_policy(Policy::default()))
515		.collect();
516	if ranges.contains(&Range::ALL) {
517		return vec![Range::ALL];
518	}
519	let mut joins = std::collections::BTreeMap::<(Option<Duration>, Option<u64>), Duration>::new();
520	for range in &ranges {
521		if let Some(join) = range.join() {
522			let widest = joins.entry(join).or_default();
523			*widest = (*widest).max(range.budget());
524		}
525	}
526
527	// An end at the last start covers every group, as an open one does.
528	let mut spans: Vec<(u64, Option<u64>)> = ranges
529		.iter()
530		.filter_map(|range| Some((range.time()?, range.end.and_then(|end| end.checked_add(1)))))
531		.collect();
532	spans.sort_unstable();
533	let mut runs: Vec<(u64, Option<u64>)> = Vec::new();
534	for (start, end) in spans {
535		match runs.last_mut() {
536			Some(last) if last.1.is_none_or(|last| start <= last) => {
537				last.1 = last.1.zip(end).map(|(last, end)| last.max(end));
538			}
539			_ => runs.push((start, end)),
540		}
541	}
542
543	let mut union: Vec<Range> = runs
544		.into_iter()
545		.map(|(start, end)| Range {
546			start: Start::Time(start),
547			end: end.map(|end| end - 1),
548			..Range::ALL
549		})
550		.collect();
551	// A range with no time start can't be placed against the time spans. One from the oldest
552	// group takes in every one from there ending before it.
553	union.extend(
554		(ranges.iter())
555			.filter(|range| range.start == Start::Oldest)
556			.max_by_key(|range| range.end),
557	);
558	union.extend(joins.into_iter().map(|((min, end), budget)| Range {
559		start: Start::Live {
560			min,
561			max: max_of(budget),
562		},
563		end,
564		..Range::ALL
565	}));
566	union.sort_unstable();
567	union.dedup();
568	union
569}
570
571impl Default for Subscription {
572	fn default() -> Self {
573		Self {
574			ranges: vec![Range::default()],
575			feed: false,
576			history: false,
577			resume: None,
578			placed: BTreeMap::new(),
579			cap: None,
580			asks: Vec::new(),
581			joins: Vec::new(),
582		}
583	}
584}
585
586impl Subscription {
587	/// The one `Subscriber Max Age` a wire before lite-07 carries for this subscription: no
588	/// limit while a history range is asked for, and otherwise the largest live join's `max`.
589	#[cfg_attr(not(feature = "async"), allow(dead_code, reason = "async-only"))]
590	pub(crate) fn max_age(&self) -> Option<Duration> {
591		max_of(self.widest())
592	}
593
594	/// The widest staleness budget any range gives a group: none while a history range is
595	/// asked for, and otherwise the largest live join's `max`.
596	pub(crate) fn widest(&self) -> Duration {
597		widest(&self.ranges)
598	}
599
600	/// The narrowest staleness budget any live join asks, `Duration::MAX` when none does.
601	#[cfg_attr(not(feature = "async"), allow(dead_code, reason = "async-only"))]
602	pub(crate) fn narrowest(&self) -> Duration {
603		(self.ranges.iter())
604			.filter_map(|range| match range.start {
605				Start::Live { max, .. } => Some(budget(max)),
606				Start::Oldest | Start::Time(_) => None,
607			})
608			.min()
609			.unwrap_or(Duration::MAX)
610	}
611
612	/// Replace [`Self::ranges`], returning `self` for chaining.
613	pub fn with_ranges(mut self, ranges: impl IntoIterator<Item = Range>) -> Self {
614		self.ranges = ranges.into_iter().collect();
615		self.placed.clear();
616		self
617	}
618
619	/// The lowest start any range names, or `None` when one has no start (or none is asked
620	/// for).
621	///
622	/// The form a wire without ranges carries: a floor below which nothing is requested.
623	pub(crate) fn start(&self) -> Option<u64> {
624		let mut floor: Option<u64> = None;
625		for (range, time) in self.times() {
626			if range.is_empty() {
627				continue;
628			}
629			let start = time?;
630			floor = Some(floor.map_or(start, |floor| floor.min(start)));
631		}
632		floor
633	}
634
635	/// Whether every range starts at an exact group (a lite-07 Position) and ends, and nothing
636	/// asks for the live feed or waits on an upstream answer to place a start: a read whose
637	/// groups are named outright, which history can answer whole.
638	pub(crate) fn exact_bounded(&self) -> bool {
639		let exact = (0..).zip(&self.ranges).all(|(index, range)| {
640			range.is_empty() || matches!(range.start, Start::Time(_)) && self.placed.contains_key(&index)
641		});
642		exact
643			&& !self.feed
644			&& self.asks.is_empty()
645			&& self.joins.is_empty()
646			&& self.start().is_some()
647			&& self.end().is_some()
648	}
649
650	/// Each range with the time it starts from: its own, or the group a live join was
651	/// [placed](Self::placed) at.
652	pub(crate) fn times(&self) -> impl Iterator<Item = (&Range, Option<u64>)> + '_ {
653		(0..)
654			.zip(&self.ranges)
655			.map(|(index, range)| (range, self.placed.get(&index).copied().or_else(|| range.time())))
656	}
657
658	/// The exclusive end past every range, or `None` when one is open. An empty list, or one
659	/// of empty ranges, ends at group 0.
660	///
661	/// The form a wire without ranges carries, alongside [`Self::start`].
662	pub(crate) fn end(&self) -> Option<u64> {
663		let mut end = Some(0);
664		for range in self.ranges.iter().filter(|range| !range.is_empty()) {
665			end = end.max(Some(range.end?.checked_add(1)?));
666		}
667		end
668	}
669
670	/// Replace the ranges with one from `start` (or no start) up to [`Self::end`], returning
671	/// `self` for chaining: the form a wire without ranges carries.
672	#[cfg(any(feature = "async", test))]
673	pub(crate) fn with_start(self, start: impl Into<Option<u64>>) -> Self {
674		let end = self.end();
675		self.with_span(start.into(), end)
676	}
677
678	/// Replace the ranges with one from [`Self::start`] up to the exclusive `end`, or onward
679	/// for `None`, returning `self` for chaining: the form a wire without ranges carries.
680	#[cfg(any(feature = "async", test))]
681	pub(crate) fn with_end(self, end: impl Into<Option<u64>>) -> Self {
682		let start = self.start();
683		self.with_span(start, end.into())
684	}
685
686	/// The one span keeps the policy the ranges ask as a whole, as a wire carrying one span
687	/// carries one policy.
688	#[cfg(any(feature = "async", test))]
689	fn with_span(self, start: Option<u64>, end: Option<u64>) -> Self {
690		let policy = self.policy();
691		self.with_ranges(Range::span(start, end).map(|range| range.with_policy(policy)))
692	}
693
694	/// These preferences with every range sent in `order`: what a wire carrying one order
695	/// per subscription asks.
696	#[cfg_attr(not(feature = "async"), allow(dead_code, reason = "async-only"))]
697	pub(crate) fn ordered(mut self, order: Order) -> Self {
698		for range in &mut self.ranges {
699			range.order = order;
700		}
701		self
702	}
703
704	/// These preferences with every range sent at `priority`: what a wire carrying one
705	/// priority per subscription asks.
706	#[cfg_attr(not(feature = "async"), allow(dead_code, reason = "async-only"))]
707	pub(crate) fn prioritized(mut self, priority: i8) -> Self {
708		for range in &mut self.ranges {
709			range.priority = priority;
710		}
711		self
712	}
713
714	/// The priority and order these ranges ask as a whole: see [`Policy::top`]. What a wire
715	/// carrying one policy per subscription carries, and the order a reader hands its groups
716	/// out in.
717	#[cfg_attr(not(feature = "async"), allow(dead_code, reason = "async-only"))]
718	pub(crate) fn policy(&self) -> Policy {
719		Policy::of(&self.ranges)
720	}
721}
722
723impl Range {
724	/// This range raised to start no earlier than `floor` and stop before `end`, the
725	/// exclusive end, without ever widening it.
726	///
727	/// `resolved` names where it resolved, so a start becomes its own group, raised to `floor`,
728	/// and an end capped at `end`. A start not resolved keeps its time, since the floor may lie
729	/// before it, so the caller drops what it resolves to below `floor`; an end not resolved
730	/// becomes the bound.
731	pub(super) fn clamped(&self, floor: Option<u64>, end: Option<u64>, resolved: Option<Resolved>) -> Self {
732		let resolved = resolved.filter(|_| floor.is_some() || end.is_some());
733		let start = match resolved {
734			Some(resolved) => Start::Time(resolved.start),
735			None => self.start,
736		};
737		let start = match (start, floor) {
738			(Start::Time(start), Some(floor)) => Start::Time(start.max(floor)),
739			(start, _) => start,
740		};
741		let requested = match (self.end, resolved.and_then(|resolved| resolved.end)) {
742			(Some(_), Some(resolved)) => match resolved.checked_sub(1) {
743				Some(last) => Some(last),
744				None => return Self::EMPTY,
745			},
746			(requested, _) => requested,
747		};
748		let end = match (requested, end.map(|end| end.checked_sub(1))) {
749			(requested, None) => requested,
750			(_, Some(None)) => return Self::EMPTY,
751			(Some(requested), Some(Some(last))) => Some(requested.min(last)),
752			(_, Some(Some(last))) => Some(last),
753		};
754		Self { start, end, ..*self }
755	}
756}
757
758impl Range {
759	/// This range as a copy asked from `floor` through the exclusive `end` asks for it, and the
760	/// group it is [placed](Subscription::placed) at: as [`Self::clamped`] places it, except a
761	/// live join, which stays itself, placed at the group [`Self::clamped`] starts it at. As a
762	/// time start it would read as history, whose groups never go stale.
763	pub(super) fn asked(
764		&self,
765		floor: Option<u64>,
766		end: Option<u64>,
767		resolved: Option<Resolved>,
768	) -> (Self, Option<u64>) {
769		let clamped = self.clamped(floor, end, resolved);
770		match (self.start, clamped.start) {
771			(Start::Live { .. }, Start::Time(group)) if !clamped.is_empty() => (
772				Self {
773					start: self.start,
774					end: clamped.end,
775					..*self
776				},
777				Some(group),
778			),
779			_ => (clamped, None),
780		}
781	}
782}
783
784/// Group spans for unit tests whose groups start at consecutive keys, where a span of
785/// starts counts groups.
786#[cfg(test)]
787impl Range {
788	/// The groups starting in `range`.
789	pub(crate) fn groups(range: impl RangeBounds<u64>) -> Self {
790		let start = match range.start_bound() {
791			Bound::Included(start) => Some(*start),
792			Bound::Excluded(start) => Some(start.saturating_add(1)),
793			Bound::Unbounded => None,
794		};
795		let end = match range.end_bound() {
796			Bound::Included(end) => end.checked_add(1),
797			Bound::Excluded(end) => Some(*end),
798			Bound::Unbounded => None,
799		};
800		Self::span(start, end).unwrap_or(Self::EMPTY)
801	}
802}
803
804#[cfg(test)]
805impl Subscription {
806	/// These preferences reading only the groups starting in `range`.
807	///
808	/// The one range keeps the policy the ranges ask as a whole.
809	pub(crate) fn with_range(self, range: impl RangeBounds<u64>) -> Self {
810		let policy = self.policy();
811		self.with_ranges([Range::groups(range).with_policy(policy)])
812	}
813
814	/// These preferences under a staleness budget the way a subscription-wide max age used to
815	/// apply one: [`Start::LATEST`] and [`Start::Oldest`] take every group still within `max`
816	/// (see [`Start::within`]), or every group for `None`; another live join keeps its lag
817	/// and takes `max`; a time start is history either way.
818	pub(crate) fn with_max(mut self, max: impl Into<Option<Duration>>) -> Self {
819		let max = max.into();
820		for range in &mut self.ranges {
821			range.start = match range.start {
822				Start::Oldest | Start::LATEST => match max {
823					Some(max) => Start::within(max),
824					None => Start::Oldest,
825				},
826				Start::Live { min, .. } => Start::Live { min, max },
827				Start::Time(time) => Start::Time(time),
828			};
829		}
830		self
831	}
832}
833
834/// The most demanding request across subscribers, folded in one at a time: the reference
835/// the track's counted aggregate is checked against.
836#[cfg(test)]
837#[derive(Default)]
838pub(super) struct Combined {
839	sub: Option<Subscription>,
840	/// The placed joins folded in, by the group each was placed at, its end, and its policy,
841	/// with the widest budget asked of each.
842	placed: BTreeMap<(u64, Option<u64>, Policy), Duration>,
843}
844
845#[cfg(test)]
846impl Combined {
847	/// Fold in one subscriber's preferences.
848	pub(super) fn add(&mut self, sub: &Subscription) {
849		let mut unplaced = Vec::new();
850		for (index, range) in (0..).zip(&sub.ranges) {
851			match sub.placed.get(&index) {
852				Some(group) => {
853					let budget = self.placed.entry((*group, range.end, range.policy())).or_default();
854					*budget = (*budget).max(range.budget());
855				}
856				None => unplaced.push(*range),
857			}
858		}
859		let Some(combined) = &mut self.sub else {
860			self.sub = Some(Subscription {
861				placed: BTreeMap::new(),
862				..sub.clone().with_ranges(unplaced)
863			});
864			return;
865		};
866		combined.ranges.extend(unplaced);
867		combined.feed |= sub.feed;
868		combined.resume = combined.resume.zip(sub.resume).map(|(a, b)| a.min(b));
869		combined.cap = combined.cap.zip(sub.cap).map(|(a, b)| a.max(b));
870	}
871
872	/// The aggregate, or `None` without a subscriber.
873	pub(super) fn finish(self) -> Option<Subscription> {
874		let mut combined = self.sub?;
875		combined.ranges = union(std::mem::take(&mut combined.ranges));
876		// Each placed join after the union, its lag placing nothing.
877		for ((group, end, policy), budget) in self.placed {
878			combined.placed.insert(combined.ranges.len() as u64, group);
879			combined.ranges.push(
880				Range {
881					start: Start::Live {
882						min: Some(Duration::ZERO),
883						max: max_of(budget),
884					},
885					end,
886					..Range::ALL
887				}
888				.with_policy(policy),
889			);
890		}
891		Some(combined)
892	}
893}
894
895/// A frame-precise point in a track: a group, by its start, and a frame index within it.
896///
897/// Ordered lexicographically, so comparing positions is the same as comparing groups
898/// and only falling back to frames within one. This is the model's counterpart of the
899/// wire's (`Group`, `Frame`) pairs on SUBSCRIBE and FETCH.
900///
901/// Pairing the two is the point: a frame index counts from the start of a group, so it
902/// means nothing on its own. Carrying them together makes "frame 5 of nothing"
903/// unrepresentable rather than merely undefined.
904#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]
905#[non_exhaustive]
906pub struct Position {
907	/// Where the group starts, in its track's timescale.
908	pub group: u64,
909	/// The frame index within the group, numbered from 0 in write order.
910	pub frame: u64,
911}
912
913impl Position {
914	/// Frame `frame` of the group starting at `group`.
915	pub fn new(group: u64, frame: u64) -> Self {
916		Self { group, frame }
917	}
918
919	/// The first frame of `group`.
920	///
921	/// As an exclusive end this means "everything before `group`"; as a start it means
922	/// "`group` from the beginning".
923	pub fn group(group: u64) -> Self {
924		Self { group, frame: 0 }
925	}
926
927	/// The first group this exclusive end excludes whole, `None` past the last group: the
928	/// boundary a wire that cannot name a frame carries as the track's end.
929	pub(crate) fn final_key(self) -> Option<u64> {
930		self.group.checked_add(u64::from(self.frame != 0))
931	}
932}
933
934/// The first index an end bound withholds, or `None` for no cap: the form cursors store
935/// and compare with [`before_end`]. An inclusive bound at `u64::MAX` has nothing above it,
936/// so it is no cap at all.
937fn exclusive_end(bound: Bound<&u64>) -> Option<u64> {
938	match bound {
939		Bound::Included(index) => index.checked_add(1),
940		Bound::Excluded(&index) => Some(index),
941		Bound::Unbounded => None,
942	}
943}
944
945// Normalize discrete ranges once, including the empty range above the last index.
946pub(super) fn key_bounds(range: impl RangeBounds<u64>) -> (u64, Option<u64>) {
947	let start = match range.start_bound() {
948		Bound::Included(&start) => start,
949		Bound::Excluded(&start) => match start.checked_add(1) {
950			Some(start) => start,
951			None => return (u64::MAX, Some(u64::MAX)),
952		},
953		Bound::Unbounded => 0,
954	};
955	(start, exclusive_end(range.end_bound()))
956}
957
958/// Whether `key` is strictly below an exclusive cap. `None` is unbounded.
959pub(super) fn before_end(key: u64, end: Option<u64>) -> bool {
960	end.is_none_or(|end| key < end)
961}
962
963#[cfg(test)]
964mod tests {
965	use super::*;
966
967	fn combine(subscriptions: &[Subscription]) -> Option<Subscription> {
968		let mut combined = Combined::default();
969		for sub in subscriptions {
970			combined.add(sub);
971		}
972		combined.finish()
973	}
974
975	/// Groups from `start` up to the exclusive `end`, or onward for `None`.
976	fn groups(start: u64, end: impl Into<Option<u64>>) -> Range {
977		Range {
978			start: Start::Time(start),
979			end: end.into().map(|end| end - 1),
980			..Default::default()
981		}
982	}
983
984	fn range(start: impl Into<Option<u64>>, end: impl Into<Option<u64>>) -> Range {
985		Range {
986			start: start.into().map_or(Start::Oldest, Start::Time),
987			end: end.into(),
988			..Default::default()
989		}
990	}
991
992	fn ranges(subscriptions: &[Subscription]) -> Vec<Range> {
993		combine(subscriptions).unwrap().ranges
994	}
995
996	fn join(min: Duration, max: Option<Duration>) -> Range {
997		Range::from(Start::Live { min: Some(min), max })
998	}
999
1000	fn joining(min: Duration) -> Subscription {
1001		Subscription::default().with_ranges([join(min, Some(Duration::ZERO))])
1002	}
1003
1004	/// A legacy span becomes inclusive times: an exclusive end of 0 holds nothing, whatever
1005	/// the start, and an end of 1 holds group 0.
1006	#[test]
1007	fn legacy_spans_become_inclusive_time_ranges() {
1008		assert_eq!(Range::span(Some(2), Some(6)), Some(range(2, 5)));
1009		assert_eq!(Range::span(None, Some(6)), Some(range(None, 5)));
1010		assert_eq!(Range::span(Some(2), None), Some(range(2, None)));
1011		assert_eq!(Range::span(None, None), Some(Range::ALL));
1012		assert_eq!(Range::span(Some(0), Some(0)), None);
1013		assert_eq!(Range::span(None, Some(0)), None);
1014		assert_eq!(Range::span(Some(5), Some(5)), None);
1015		assert_eq!(Range::span(Some(0), Some(1)), Some(range(0, 0)));
1016		assert!(Range::EMPTY.is_empty());
1017	}
1018
1019	#[test]
1020	fn cursor_bounds_are_total_at_the_extremes() {
1021		// A cursor cap is the first index it withholds; an inclusive bound at the last
1022		// index withholds nothing.
1023		assert_eq!(key_bounds(..0), (0, Some(0)));
1024		assert_eq!(key_bounds(..=5), (0, Some(6)));
1025		assert_eq!(key_bounds(..=u64::MAX), (0, None));
1026		assert_eq!(key_bounds(..), (0, None));
1027		assert_eq!(key_bounds((Bound::Unbounded, Bound::Included(5))), key_bounds(..6));
1028	}
1029
1030	/// The bounds a wire without ranges carries: the lowest start and the highest exclusive
1031	/// end, either one lost to a range without it.
1032	#[test]
1033	fn bounds_project_the_ranges_for_older_wires() {
1034		let sub = Subscription::default();
1035		assert_eq!((sub.start(), sub.end()), (None, None));
1036
1037		let sub = Subscription::default().with_ranges([groups(2, 4), groups(7, 9)]);
1038		assert_eq!((sub.start(), sub.end()), (Some(2), Some(9)));
1039
1040		// An explicit start at 0 is a floor, unlike the default.
1041		let sub = Subscription::default().with_ranges([groups(0, None)]);
1042		assert_eq!((sub.start(), sub.end()), (Some(0), None));
1043
1044		let sub = Subscription::default().with_ranges([groups(2, 4), Range::ALL]);
1045		assert_eq!((sub.start(), sub.end()), (None, None));
1046
1047		// Nothing asked for is the empty range.
1048		let sub = Subscription::default().with_ranges([]);
1049		assert_eq!(sub.end(), Some(0));
1050
1051		let sub = Subscription::default().with_start(5).with_end(10);
1052		assert_eq!((sub.start(), sub.end()), (Some(5), Some(10)));
1053		// No start and no end is every group, which a wire without ranges can't tell from no
1054		// start at all.
1055		assert_eq!(
1056			sub.with_start(None).with_end(None),
1057			Subscription::default().with_ranges([Range::ALL])
1058		);
1059	}
1060
1061	/// The aggregate is the union: overlapping and adjacent time ranges merge, an open range
1062	/// absorbs what starts inside it, a range from the oldest group absorbs everything, and
1063	/// live joins of one lag and end merge under their widest `max`.
1064	#[test]
1065	fn combined_ranges_are_the_union() {
1066		let sub = |ranges: &[Range]| Subscription::default().with_ranges(ranges.iter().copied());
1067
1068		assert_eq!(
1069			ranges(&[sub(&[groups(2, 5)]), sub(&[groups(4, 8)])]),
1070			vec![groups(2, 8)]
1071		);
1072		assert_eq!(
1073			ranges(&[sub(&[groups(2, 5)]), sub(&[groups(5, 8)])]),
1074			vec![groups(2, 8)],
1075			"adjacent ranges merge"
1076		);
1077		assert_eq!(
1078			ranges(&[sub(&[groups(2, 5)]), sub(&[groups(6, 8)])]),
1079			vec![groups(2, 5), groups(6, 8)],
1080			"a gap stays a gap"
1081		);
1082		assert_eq!(
1083			ranges(&[sub(&[groups(2, 5), groups(9, None)]), sub(&[groups(4, None)])]),
1084			vec![groups(2, None)]
1085		);
1086		assert_eq!(ranges(&[sub(&[groups(2, 5)]), sub(&[Range::ALL])]), vec![Range::ALL]);
1087
1088		// A live join reaches back only by its lag, so the history beside it stays asked, and
1089		// each lag is a range of its own.
1090		let two = Duration::from_secs(2);
1091		let five = Duration::from_secs(5);
1092		assert_eq!(
1093			ranges(&[sub(&[groups(2, 5)]), joining(two), joining(five), joining(two)]),
1094			vec![
1095				groups(2, 5),
1096				join(two, Some(Duration::ZERO)),
1097				join(five, Some(Duration::ZERO))
1098			]
1099		);
1100		// Unless another reader starts at the oldest group.
1101		assert_eq!(
1102			ranges(&[sub(&[groups(2, 5)]), joining(two), sub(&[Range::ALL])]),
1103			vec![Range::ALL]
1104		);
1105
1106		// Joins of one lag land on the same group whatever their `max`, so they merge under
1107		// the widest, and no limit is the widest of all.
1108		assert_eq!(
1109			ranges(&[sub(&[join(two, Some(five))]), joining(two)]),
1110			vec![join(two, Some(five))]
1111		);
1112		assert_eq!(
1113			ranges(&[sub(&[join(two, Some(five))]), sub(&[join(two, None)])]),
1114			vec![join(two, None)]
1115		);
1116		// A join's end keeps it apart from an open one of the same lag.
1117		let ended = Range {
1118			end: Some(9),
1119			..join(two, Some(five))
1120		};
1121		assert_eq!(
1122			ranges(&[sub(&[ended]), joining(two)]),
1123			vec![join(two, Some(Duration::ZERO)), ended]
1124		);
1125
1126		// A range from the oldest group with an end takes in every one ending before it.
1127		let oldest = |end| Range {
1128			start: Start::Oldest,
1129			end: Some(end),
1130			..Default::default()
1131		};
1132		assert_eq!(
1133			ranges(&[sub(&[oldest(5)]), sub(&[oldest(3)]), sub(&[oldest(5)])]),
1134			vec![oldest(5)]
1135		);
1136
1137		// Empty ranges ask for nothing.
1138		assert_eq!(ranges(&[sub(&[groups(5, 5)])]), Vec::<Range>::new());
1139		assert_eq!(ranges(&[sub(&[]), sub(&[groups(1, 2)])]), vec![groups(1, 2)]);
1140	}
1141
1142	/// A copy asked from a floor gets a resolved live join with a `max` as a live join taking
1143	/// every group within it, so its groups still go stale there; one with no `max`, and
1144	/// history, are asked from where they resolved.
1145	#[test]
1146	fn a_resolved_live_join_is_asked_placed_with_its_max() {
1147		let max = Duration::from_secs(2);
1148		let join = |max, end| Range {
1149			start: Start::Live {
1150				min: Some(Duration::from_millis(2)),
1151				max,
1152			},
1153			end,
1154			..Default::default()
1155		};
1156		let at = |start, end| {
1157			Some(Resolved {
1158				start,
1159				end,
1160				floored: true,
1161			})
1162		};
1163		// Placed at the floor it is raised to, still the join it was.
1164		assert_eq!(
1165			join(Some(max), None).asked(Some(10), None, at(8, None)),
1166			(join(Some(max), None), Some(10))
1167		);
1168		assert_eq!(
1169			join(Some(max), None).asked(Some(6), None, at(8, None)),
1170			(join(Some(max), None), Some(8))
1171		);
1172		// Its end where it resolved, as a placed one's.
1173		assert_eq!(
1174			join(Some(max), Some(500)).asked(Some(10), None, at(8, Some(12))),
1175			(join(Some(max), Some(11)), Some(10))
1176		);
1177		// With no max too.
1178		let (asked, placed) = join(None, None).asked(Some(10), None, at(8, None));
1179		assert_eq!((asked, placed), (join(None, None), Some(10)));
1180		assert_eq!(
1181			groups(8, None).asked(Some(10), None, at(8, None)),
1182			(groups(10, None), None)
1183		);
1184		// Not yet resolved: asked as it is, for the copy to place.
1185		assert_eq!(
1186			join(Some(max), None).asked(Some(10), None, None),
1187			(join(Some(max), None), None)
1188		);
1189		// Capped at where it resolved: nothing, whatever its `max`.
1190		assert!(join(Some(max), None).asked(None, Some(8), at(8, None)).0.is_empty());
1191	}
1192
1193	/// Combining is order-independent and stops changing once it covers everyone.
1194	#[test]
1195	fn combined_ranges_settle() {
1196		let a = Subscription::default().with_ranges([groups(2, 5), Range::ALL]);
1197		let b = Subscription::default().with_ranges([groups(4, 9)]);
1198		assert_eq!(combine(&[a.clone(), b.clone()]), combine(&[b.clone(), a.clone()]));
1199
1200		let combined = combine(&[a.clone(), b]);
1201		assert_eq!(
1202			combine(&[combined.clone().unwrap(), a]),
1203			combined,
1204			"a subset adds nothing"
1205		);
1206	}
1207
1208	/// The policy a set of ranges asks as a whole: the highest priority, and newest first if
1209	/// any range at it is.
1210	#[test]
1211	fn the_top_policy_is_the_highest_priority_newest_first() {
1212		let at = |priority, order| Range::ALL.with_priority(priority).with_order(order);
1213		let policy = |ranges: &[Range]| {
1214			let policy = Policy::of(ranges);
1215			(policy.priority, policy.order)
1216		};
1217		assert_eq!(policy(&[]), (0, Order::Descending));
1218		assert_eq!(policy(&[at(0, Order::Ascending)]), (0, Order::Ascending));
1219		assert_eq!(
1220			policy(&[at(0, Order::Ascending), at(0, Order::Descending)]),
1221			(0, Order::Descending)
1222		);
1223		assert_eq!(
1224			policy(&[at(0, Order::Descending), at(0, Order::Ascending)]),
1225			(0, Order::Descending)
1226		);
1227		assert_eq!(
1228			policy(&[at(-1, Order::Descending), at(2, Order::Ascending)]),
1229			(2, Order::Ascending)
1230		);
1231	}
1232
1233	/// A covered range folds only into one at a policy covering its own: a higher priority,
1234	/// or the same one newest first or in its order. Otherwise both stay, so neither the
1235	/// priority nor the order of the covered one is lost upstream.
1236	#[test]
1237	fn a_range_folds_only_into_a_covering_policy() {
1238		let sub = |ranges: &[Range]| Subscription::default().with_ranges(ranges.iter().copied());
1239		let live = Range::default().with_priority(5);
1240		let all = |priority, order| Range::ALL.with_priority(priority).with_order(order);
1241
1242		// A live join under a lower-priority ALL stays, so its priority is still asked.
1243		assert_eq!(
1244			ranges(&[sub(&[live]), sub(&[all(0, Order::Descending)])]),
1245			vec![all(0, Order::Descending), live]
1246		);
1247		// Under a higher-priority one it adds nothing.
1248		assert_eq!(
1249			ranges(&[sub(&[live]), sub(&[all(9, Order::Ascending)])]),
1250			vec![all(9, Order::Ascending)]
1251		);
1252		// At one priority, newest first covers oldest first but not the reverse.
1253		assert_eq!(
1254			ranges(&[
1255				sub(&[groups(2, 5).with_order(Order::Ascending)]),
1256				sub(&[all(0, Order::Descending)])
1257			]),
1258			vec![all(0, Order::Descending)]
1259		);
1260		assert_eq!(
1261			ranges(&[sub(&[groups(2, 5)]), sub(&[all(0, Order::Ascending)])]),
1262			vec![all(0, Order::Ascending), groups(2, 5)]
1263		);
1264		// Time spans of one policy merge; across policies a span only partly
1265		// covered stays whole.
1266		assert_eq!(
1267			ranges(&[
1268				sub(&[groups(2, 5).with_priority(1), groups(4, 8).with_priority(1)]),
1269				sub(&[groups(3, 7), groups(6, 9)])
1270			]),
1271			vec![groups(2, 8).with_priority(1), groups(3, 9)]
1272		);
1273		// Ranges of several covering policies together cover a span.
1274		assert_eq!(
1275			ranges(&[
1276				sub(&[groups(2, 5).with_priority(2), groups(5, 8).with_priority(1)]),
1277				sub(&[groups(3, 7)])
1278			]),
1279			vec![groups(2, 5).with_priority(2), groups(5, 8).with_priority(1)]
1280		);
1281	}
1282}