Skip to main content

moq_net/model/track/
fill.rs

1//! Fills: the groups readers miss, asked of a [`Requests`](super::Requests) handler by range.
2//!
3//! A miss is a key a reader wants that the cache doesn't hold and the live feed will
4//! never deliver. A reader joins the fill already covering it, or queues a new one, and a
5//! handler serves each fill it takes as one bounded run: [`FillGroups::accept`] for each group it
6//! has, [`FillGroups::drop_groups`] for the rest.
7//!
8//! A fill serves under what its readers ask now: a reader changing its priority or
9//! order moves every fill it waits on, queued or taken. Only the first group's start frame
10//! stays as the handler took it, since a handler may have asked its source for it already;
11//! a reader wanting earlier frames of that group asks a fill of its own.
12
13use std::{
14	collections::{BTreeMap, HashMap, VecDeque, btree_map},
15	ops,
16	sync::Arc,
17	task::Poll,
18};
19
20use rangemap::{RangeMap, RangeSet};
21
22use super::{Info, Order, Position, TrackState};
23use crate::{Error, Result, StreamError, group, util::SendCell};
24
25/// The fills a track's readers asked for, queued or taken by a handler, under one lock.
26#[derive(Default)]
27pub(in crate::model) struct FillState {
28	// Live `Requests` handles: a fill queues only while one can take it.
29	handlers: usize,
30	next: u64,
31	// Every fill not yet ended, queued or taken, by id.
32	pending: HashMap<u64, Pending>,
33	// The queued subset, oldest first.
34	queue: VecDeque<u64>,
35	// The fill each unresolved key waits on, so a second reader joins it rather than
36	// asking again.
37	covers: RangeMap<u64, u64>,
38}
39
40/// One fill until it ends.
41struct Pending {
42	start: Position,
43	end: u64,
44	// Exclusive frame cap in the last group; None asks through the original end.
45	frame_end: Option<u64>,
46	// For a time start, the oldest key its group, the newest starting at or before the
47	// time, may start at.
48	floor: Option<u64>,
49	// What its joins ask with now, shared with them and its handler.
50	asks: kio::Shared<Asks>,
51	queued: bool,
52	// A flight: a separate copy of one group from its start frame, which no other reader
53	// joins by key; see [`FillState::fly`].
54	flight: bool,
55	// How many joins still read each key: one a reader narrowed away is no longer owed.
56	wants: RangeMap<u64, u32>,
57	// What it answered that no join has picked up yet, which holds back the next group: see
58	// [`FillGroups::poll_wanted_changed`].
59	unseen: RangeSet<u64>,
60	// What it answered that no join took yet: the first in its order is held in the cache for
61	// them (see [`super::held`]). A join taking a group, or no longer reading it, takes it for
62	// all.
63	untaken: RangeSet<u64>,
64	// How many joins are their reader's front, the fill holding the next group that reader
65	// takes: only a fill some reader fronts holds a group, so each reader holds one at most.
66	fronts: u32,
67	// Readers hold consumers, so it counts the fill's demand; the handler's copy says what
68	// became of each key.
69	result: kio::Producer<Outcome>,
70}
71
72impl Pending {
73	/// Count one more join reading `groups`.
74	fn want(&mut self, groups: ops::Range<u64>) {
75		let mut counts: Vec<(ops::Range<u64>, u32)> = self
76			.wants
77			.overlapping(&groups)
78			.map(|(run, count)| (run.start.max(groups.start)..run.end.min(groups.end), count + 1))
79			.collect();
80		counts.extend(self.wants.gaps(&groups).map(|gap| (gap, 1)));
81		for (run, count) in counts {
82			self.wants.insert(run, count);
83		}
84	}
85
86	/// Count one join out of reading `groups`, which it counted in. Returns the runs nobody
87	/// reads any more.
88	fn unwant(&mut self, groups: ops::Range<u64>) -> Vec<ops::Range<u64>> {
89		self.unseen.remove(groups.clone());
90		self.untaken.remove(groups.clone());
91		let counts: Vec<(ops::Range<u64>, u32)> = self
92			.wants
93			.overlapping(&groups)
94			.map(|(run, count)| (run.start.max(groups.start)..run.end.min(groups.end), count - 1))
95			.collect();
96		let mut unwanted = Vec::new();
97		for (run, count) in counts {
98			match count {
99				0 => {
100					self.wants.remove(run.clone());
101					unwanted.push(run);
102				}
103				count => self.wants.insert(run, count),
104			}
105		}
106		unwanted
107	}
108
109	/// The runs of `span` a join still reads.
110	fn wanted(&self, span: &ops::Range<u64>) -> RangeSet<u64> {
111		self.wants
112			.overlapping(span)
113			.map(|(run, _)| run.start.max(span.start)..run.end.min(span.end))
114			.collect()
115	}
116}
117
118/// What a reader asks its fills with, which it may change while they are out.
119#[derive(Clone, Copy, Debug, PartialEq, Eq)]
120pub(in crate::model) struct Asking {
121	pub priority: i8,
122	pub order: Order,
123}
124
125/// What a fill's joins ask with, counted so a join arriving, leaving, or changing its mind
126/// costs its own entry rather than a pass over every join.
127#[derive(Default)]
128struct Asks {
129	priorities: BTreeMap<i8, usize>,
130	descending: usize,
131}
132
133impl Asks {
134	fn add(&mut self, asking: &Asking) {
135		*self.priorities.entry(asking.priority).or_default() += 1;
136		if asking.order == Order::Descending {
137			self.descending += 1;
138		}
139	}
140
141	fn remove(&mut self, asking: &Asking) {
142		fn take<K: Ord>(counts: &mut BTreeMap<K, usize>, key: K) {
143			let btree_map::Entry::Occupied(mut entry) = counts.entry(key) else {
144				unreachable!("only a counted ask is removed");
145			};
146			*entry.get_mut() -= 1;
147			if *entry.get() == 0 {
148				entry.remove();
149			}
150		}
151		take(&mut self.priorities, asking.priority);
152		if asking.order == Order::Descending {
153			self.descending -= 1;
154		}
155	}
156
157	/// The most urgent priority asked.
158	fn priority(&self) -> i8 {
159		self.priorities.last_key_value().map_or(0, |(priority, _)| *priority)
160	}
161
162	/// Newest first once any join asks for it, as any descending subscriber makes a
163	/// subscription.
164	fn order(&self) -> Order {
165		match self.descending {
166			0 => Order::Ascending,
167			_ => Order::Descending,
168		}
169	}
170}
171
172/// What became of a fill's keys, shared with every reader that joined it.
173#[derive(Default)]
174pub(crate) struct Outcome {
175	accepted: RangeSet<u64>,
176	// Why each refused run was refused; refusing a key again replaces why.
177	refused: RangeMap<u64, Refusal>,
178	refusals: u64,
179	// Accepted or refused, kept as answers arrive so a fill answered group by group costs
180	// the runs each answer touches, not every answer before it.
181	resolved: RangeSet<u64>,
182	// Each accepted copy short of the whole group, which a later copy may displace from the
183	// cache before a reader takes it. A whole copy covers every other, so none displaces it.
184	partial: BTreeMap<u64, group::Handle>,
185	// The group a time start's fill accepted below the time, created or already cached, held so
186	// where it ends is known even once the cache lets it go.
187	answer: Option<group::Handle>,
188	// What it held, answered or still landing, that a debt evicted with no room to hold it
189	// again beside the pins and the other holds: a refill would be evicted the same way, so a
190	// reader finding the eviction gives it up, and a lite-07 recovery is not asked again.
191	// Kept until no join reads it, so neither a grace nor a debt forgets it.
192	unfit: RangeSet<u64>,
193}
194
195impl Outcome {
196	/// Why `key` was refused, if it was.
197	pub(crate) fn refused(&self, key: u64) -> Option<&Error> {
198		self.refused.get(&key).map(|refusal| &refusal.err)
199	}
200
201	pub(super) fn is_accepted(&self, key: u64) -> bool {
202		self.accepted.contains(&key)
203	}
204
205	/// The keys of `groups` it answered that a debt evicted with no room to hold them again.
206	pub(super) fn unfit(&self, groups: &ops::Range<u64>) -> RangeSet<u64> {
207		self.unfit
208			.overlapping(groups)
209			.map(|run| run.start.max(groups.start)..run.end.min(groups.end))
210			.collect()
211	}
212
213	/// The group a time start's fill accepted below the time.
214	pub(super) fn answer(&self) -> Option<&group::Handle> {
215		self.answer.as_ref()
216	}
217
218	/// What a time start's fill answered, once `time`'s key is: `None` while it is out.
219	pub(super) fn time_start(&self, time: u64) -> Option<TimeStart> {
220		if let Some(run) = self.accepted.iter().next() {
221			return Some(TimeStart::Group(run.start));
222		}
223		match self.refused.get(&time) {
224			Some(refusal) if refusal.hole.is_some() => Some(TimeStart::Dropped),
225			Some(refusal) => Some(TimeStart::Refused(refusal.err.clone())),
226			// Answered and forgotten: nobody reads it any more.
227			None if self.resolved.contains(&time) => Some(TimeStart::Unanswered),
228			None => None,
229		}
230	}
231
232	/// The partial copy accepted for `key`, if it still holds `frames`.
233	pub(super) fn partial(&self, key: u64, frames: group::Bounds) -> Option<group::Handle> {
234		self.partial.get(&key).filter(|copy| copy.covers(frames)).cloned()
235	}
236
237	/// What was answered within `wanted`: accepted, or refused with why and the hole its source
238	/// named, if any.
239	#[expect(
240		clippy::type_complexity,
241		reason = "each answer pairs a run with its outcome; naming it would only move the type"
242	)]
243	pub(super) fn within(
244		&self,
245		wanted: &RangeSet<u64>,
246	) -> Vec<(ops::Range<u64>, std::result::Result<(), (Error, Option<super::Hole>)>)> {
247		let mut answers = Vec::new();
248		for run in wanted.iter() {
249			for accepted in self.accepted.overlapping(run) {
250				answers.push((accepted.start.max(run.start)..accepted.end.min(run.end), Ok(())));
251			}
252			for (refused, refusal) in self.refused.overlapping(run) {
253				let groups = refused.start.max(run.start)..refused.end.min(run.end);
254				answers.push((groups, Err((refusal.err.clone(), refusal.hole.clone()))));
255			}
256		}
257		answers
258	}
259
260	fn accept(&mut self, groups: ops::Range<u64>) {
261		self.unfit.remove(groups.clone());
262		self.accepted.insert(groups.clone());
263		self.resolved.insert(groups);
264	}
265
266	fn refuse(&mut self, groups: ops::Range<u64>, err: Error, hole: Option<super::Hole>) {
267		if groups.is_empty() {
268			return;
269		}
270		let id = self.refusals;
271		self.refusals += 1;
272		self.refused.insert(groups.clone(), Refusal { id, err, hole });
273		self.resolved.insert(groups);
274	}
275}
276
277/// What a time start's fill answered.
278pub(super) enum TimeStart {
279	/// The group containing the time.
280	Group(u64),
281	/// No group from the fill's floor through the time.
282	Dropped,
283	/// Refused with this error, saying nothing of where the time falls.
284	Refused(Error),
285	/// Nothing answers it: no handler is left to.
286	Unanswered,
287}
288
289/// One refusal, equal only to itself: the map keeps a run it refused whole, but never merges
290/// two refusals whose errors may differ.
291#[derive(Clone)]
292struct Refusal {
293	id: u64,
294	err: Error,
295	// The hole the source named, its word that it has none of them (or never produced them),
296	// rather than refused for now.
297	hole: Option<super::Hole>,
298}
299
300impl PartialEq for Refusal {
301	fn eq(&self, other: &Self) -> bool {
302		self.id == other.id
303	}
304}
305
306impl Eq for Refusal {}
307
308/// A reader's request: the run `start.group..end`, from `start.frame` in its first group.
309pub(super) struct Ask {
310	pub start: Position,
311	pub end: u64,
312	pub frame_end: Option<u64>,
313	pub asking: Asking,
314}
315
316/// A reader's place in one fill: the part of it the reader wants.
317pub(super) struct Join {
318	fills: kio::Shared<FillState>,
319	id: u64,
320	/// The keys of the fill this reader asked for.
321	pub groups: ops::Range<u64>,
322	// The part of `groups` it still reads, counted in the fill's wants.
323	held: RangeSet<u64>,
324	// Counts this reader in the fill's demand; `None` only while dropping.
325	outcome: Option<kio::Consumer<Outcome>>,
326	attempt: kio::ProducerPassive<Outcome>,
327	// What this reader asks the fill with, counted in its asks.
328	asking: Asking,
329	asks: kio::Shared<Asks>,
330	// Whether this is its reader's front, counted in the fill's fronts.
331	front: bool,
332}
333
334impl Join {
335	pub(super) fn outcome(&self) -> &kio::Consumer<Outcome> {
336		self.outcome.as_ref().expect("held until dropped")
337	}
338
339	/// Ask the fill with `asking` from now on, queued or taken.
340	pub(super) fn update(&mut self, asking: &Asking) {
341		if self.asking == *asking {
342			return;
343		}
344		let mut asks = self.asks.lock();
345		asks.remove(&self.asking);
346		asks.add(asking);
347		self.asking = *asking;
348	}
349}
350
351impl Drop for Join {
352	fn drop(&mut self) {
353		self.asks.lock().remove(&self.asking);
354		// Joins take the lock, so leaving under it is atomic with one: a joiner either keeps
355		// the fill wanted, or finds it withdrawn and asks afresh rather than joining a fill
356		// its handler is about to drop.
357		let mut fills = self.fills.lock();
358		drop(self.outcome.take());
359		if !fills.pending.get(&self.id).is_some_and(|pending| self.is_ours(pending)) {
360			return;
361		}
362		if self.front {
363			fills.pending.get_mut(&self.id).expect("checked above").fronts -= 1;
364		}
365		for run in std::mem::take(&mut self.held).iter() {
366			fills.unwant(self.id, run.clone());
367		}
368		if !self.attempt.wanted() {
369			fills.withdraw(self.id);
370		}
371	}
372}
373
374impl Join {
375	fn is_ours(&self, pending: &Pending) -> bool {
376		pending.result.passive().is_clone(&self.attempt)
377	}
378
379	/// The part of the fill the reader still reads.
380	pub(super) fn held(&self) -> &RangeSet<u64> {
381		&self.held
382	}
383
384	/// Whether the reader holds none of the fill any more.
385	pub(super) fn is_empty(&self) -> bool {
386		self.held.is_empty()
387	}
388
389	/// Make this its reader's front, the fill holding the next group the reader takes, or
390	/// stop: a reader fronts one fill at a time, so it holds one group at most.
391	pub(super) fn set_front(&mut self, front: bool) {
392		if self.front == front {
393			return;
394		}
395		self.front = front;
396		let mut fills = self.fills.lock();
397		if let Some(pending) = fills.pending.get_mut(&self.id)
398			&& self.is_ours(pending)
399		{
400			match front {
401				true => pending.fronts += 1,
402				false => pending.fronts -= 1,
403			}
404		}
405	}
406
407	/// The reader picked up `groups` the fill answered, so its handler may serve the next one.
408	pub(super) fn saw(&self, groups: &RangeSet<u64>) {
409		let mut fills = self.fills.lock();
410		// Read first: a mutable borrow wakes every poll parked on the fills.
411		if !fills
412			.pending
413			.get(&self.id)
414			.is_some_and(|pending| self.is_ours(pending) && groups.iter().any(|run| pending.unseen.overlaps(run)))
415		{
416			return;
417		}
418		let unseen = &mut fills.pending.get_mut(&self.id).expect("checked above").unseen;
419		for run in groups.iter() {
420			unseen.remove(run.clone());
421		}
422	}
423
424	/// The caller took `key`, which it still reads through the fill: the fill holds it no
425	/// longer and may serve its next group.
426	pub(super) fn took(&self, key: u64) {
427		let Some(end) = key.checked_add(1) else {
428			return;
429		};
430		let mut fills = self.fills.lock();
431		// Read first: a mutable borrow wakes every poll parked on the fills.
432		if !fills.pending.get(&self.id).is_some_and(|pending| {
433			self.is_ours(pending) && (pending.unseen.contains(&key) || pending.untaken.contains(&key))
434		}) {
435			return;
436		}
437		let pending = fills.pending.get_mut(&self.id).expect("checked above");
438		pending.unseen.remove(key..end);
439		pending.untaken.remove(key..end);
440	}
441
442	/// Stop reading `lost`, so the fill no longer owes this reader any of it.
443	pub(super) fn release(&mut self, lost: &RangeSet<u64>) {
444		let released: Vec<ops::Range<u64>> = lost
445			.overlapping(&self.groups)
446			.flat_map(|run| {
447				self.held
448					.overlapping(run)
449					.map(move |held| held.start.max(run.start)..held.end.min(run.end))
450			})
451			.collect();
452		if released.is_empty() {
453			return;
454		}
455		for run in &released {
456			self.held.remove(run.clone());
457		}
458		let mut fills = self.fills.lock();
459		if !fills.pending.get(&self.id).is_some_and(|pending| self.is_ours(pending)) {
460			return;
461		}
462		for run in released {
463			fills.unwant(self.id, run);
464		}
465	}
466}
467
468impl FillState {
469	pub(super) fn add_handler(&mut self) {
470		self.handlers += 1;
471	}
472
473	/// Count a handler out. The last one leaving drops what it never took, so every reader
474	/// waiting on those fills finds them gone; a fill already taken stays with its handler.
475	pub(super) fn remove_handler(&mut self) {
476		self.handlers -= 1;
477		if self.handlers > 0 {
478			return;
479		}
480		for id in std::mem::take(&mut self.queue) {
481			self.end(id);
482		}
483	}
484
485	pub(super) fn has_handlers(&self) -> bool {
486		self.handlers > 0
487	}
488
489	pub(super) fn has_queued(&self) -> bool {
490		!self.queue.is_empty()
491	}
492
493	/// Whether no fill is pending, queued or taken.
494	#[cfg(all(test, feature = "async"))]
495	pub(super) fn is_empty(&self) -> bool {
496		self.pending.is_empty() && self.queue.is_empty() && self.covers.is_empty()
497	}
498
499	/// Join every fill covering `ask`, queueing a new one for each run none covers. Returns
500	/// the joins, and the runs nobody can fill: no handler is alive to take a new fill.
501	pub(super) fn join(&mut self, shared: &kio::Shared<FillState>, ask: &Ask) -> (Vec<Join>, Vec<ops::Range<u64>>) {
502		let span = ask.start.group..ask.end;
503		let mut joins = Vec::new();
504		let mut unfillable = Vec::new();
505		if span.is_empty() {
506			return (joins, unfillable);
507		}
508		let covered: Vec<(ops::Range<u64>, u64)> = self
509			.covers
510			.overlapping(&span)
511			.map(|(groups, id)| (groups.start.max(span.start)..groups.end.min(span.end), *id))
512			.collect();
513		let mut gaps: Vec<ops::Range<u64>> = self.covers.gaps(&span).collect();
514		for (mut groups, id) in covered {
515			let pending = self.pending.get_mut(&id).expect("a covered key names a pending fill");
516			if groups.start == pending.start.group {
517				// A reader starting in an earlier group wants this one whole.
518				let frame = match ask.start.group == groups.start {
519					true => ask.start.frame,
520					false => 0,
521				};
522				if frame < pending.start.frame {
523					match pending.queued {
524						true => pending.start.frame = frame,
525						// Taken: its handler may have asked its source from the later frame
526						// already, so the earlier frames are a fill of their own.
527						false => {
528							gaps.push(groups.start..groups.start + 1);
529							groups.start += 1;
530						}
531					}
532				}
533			}
534			if !groups.is_empty() && groups.end == pending.end {
535				let end = if groups.end == ask.end { ask.frame_end } else { None };
536				if pending.frame_end.is_some_and(|cap| end.is_none_or(|end| end > cap)) {
537					if pending.queued {
538						pending.frame_end = end;
539					} else {
540						// The source already saw the cap: the missing suffix asks for its own copy.
541						gaps.push(groups.end - 1..groups.end);
542						groups.end -= 1;
543					}
544				}
545			}
546			if groups.is_empty() {
547				continue;
548			}
549			pending.want(groups.clone());
550			pending.asks.lock().add(&ask.asking);
551			joins.push(Join {
552				fills: shared.clone(),
553				id,
554				held: RangeSet::from_iter([groups.clone()]),
555				groups,
556				outcome: Some(pending.result.consume()),
557				attempt: pending.result.passive(),
558				asking: ask.asking,
559				asks: pending.asks.clone(),
560				front: false,
561			});
562		}
563		// Queued in the reader's order, so a descending reader's newest fragment goes first.
564		gaps.sort_unstable_by_key(|gap| gap.start);
565		if ask.asking.order == Order::Descending {
566			gaps.reverse();
567		}
568		let takes = self.has_handlers();
569		for groups in gaps {
570			if !takes {
571				unfillable.push(groups);
572				continue;
573			}
574			let id = self.next;
575			self.next += 1;
576			let start = match groups.start == ask.start.group {
577				true => ask.start,
578				false => Position::group(groups.start),
579			};
580			let result = kio::Producer::<Outcome>::default();
581			let mut asks = Asks::default();
582			asks.add(&ask.asking);
583			let asks = kio::Shared::new(asks);
584			joins.push(Join {
585				fills: shared.clone(),
586				id,
587				groups: groups.clone(),
588				held: RangeSet::from_iter([groups.clone()]),
589				outcome: Some(result.consume()),
590				attempt: result.passive(),
591				asking: ask.asking,
592				asks: asks.clone(),
593				front: false,
594			});
595			// A taken fill's first group split off above keeps that fill, routed here instead.
596			self.covers.insert(groups.clone(), id);
597			self.pending.insert(
598				id,
599				Pending {
600					start,
601					end: groups.end,
602					frame_end: if groups.end == ask.end { ask.frame_end } else { None },
603					floor: None,
604					asks,
605					queued: true,
606					flight: false,
607					wants: RangeMap::from_iter([(groups.clone(), 1)]),
608					unseen: RangeSet::new(),
609					untaken: RangeSet::new(),
610					fronts: 0,
611					result,
612				},
613			);
614			self.queue.push_back(id);
615		}
616		(joins, unfillable)
617	}
618
619	/// Join or queue a flight of group `key` from `frame`: a fill answered with a copy
620	/// of its own, which no reader joins by key, since a copy shed past its readers
621	/// holds nothing for one asking earlier. Readers asking from the same frame before it is
622	/// answered share it. `None` while no handler can take it.
623	pub(super) fn fly(
624		&mut self,
625		shared: &kio::Shared<FillState>,
626		key: u64,
627		frame: u64,
628		asking: Asking,
629	) -> Option<Join> {
630		let groups = key..key.checked_add(1)?;
631		if self.handlers == 0 {
632			return None;
633		}
634		let boarding = self.pending.iter_mut().find(|(_, pending)| {
635			pending.flight
636				&& pending.start == Position { group: key, frame }
637				&& !pending.result.read().resolved.contains(&key)
638		});
639		let id = match boarding {
640			Some((id, pending)) => {
641				pending.want(groups.clone());
642				pending.asks.lock().add(&asking);
643				*id
644			}
645			None => {
646				let id = self.next;
647				self.next += 1;
648				let mut asks = Asks::default();
649				asks.add(&asking);
650				self.pending.insert(
651					id,
652					Pending {
653						start: Position { group: key, frame },
654						end: groups.end,
655						frame_end: None,
656						floor: None,
657						asks: kio::Shared::new(asks),
658						queued: true,
659						flight: true,
660						wants: RangeMap::from_iter([(groups.clone(), 1)]),
661						unseen: RangeSet::new(),
662						untaken: RangeSet::new(),
663						fronts: 0,
664						result: Default::default(),
665					},
666				);
667				self.queue.push_back(id);
668				id
669			}
670		};
671		let pending = &self.pending[&id];
672		Some(Join {
673			fills: shared.clone(),
674			id,
675			held: RangeSet::from_iter([groups.clone()]),
676			groups,
677			outcome: Some(pending.result.consume()),
678			attempt: pending.result.passive(),
679			asking,
680			asks: pending.asks.clone(),
681			front: false,
682		})
683	}
684
685	/// Queue a fill of the group containing `time`, a reader's time start no held group
686	/// resolves, with the join waiting on its answer: the group starting at `time`, or else the
687	/// newest one before it, starting at or after `floor`. It joins nothing and nothing joins
688	/// it, since an answer below `time` says nothing of the keys another reader asks. `None`
689	/// while no handler can take it.
690	pub(super) fn time_start(
691		&mut self,
692		shared: &kio::Shared<FillState>,
693		time: u64,
694		floor: u64,
695		asking: Asking,
696	) -> Option<Join> {
697		let groups = time..time.checked_add(1)?;
698		if self.handlers == 0 {
699			return None;
700		}
701		let id = self.next;
702		self.next += 1;
703		let result = kio::Producer::<Outcome>::default();
704		let mut asks = Asks::default();
705		asks.add(&asking);
706		let asks = kio::Shared::new(asks);
707		let join = Join {
708			fills: shared.clone(),
709			id,
710			groups: groups.clone(),
711			held: RangeSet::from_iter([groups.clone()]),
712			outcome: Some(result.consume()),
713			attempt: result.passive(),
714			asking,
715			asks: asks.clone(),
716			front: true,
717		};
718		self.pending.insert(
719			id,
720			Pending {
721				start: Position::group(time),
722				end: groups.end,
723				frame_end: None,
724				floor: Some(floor.min(time)),
725				asks,
726				queued: true,
727				flight: false,
728				wants: RangeMap::from_iter([(groups, 1)]),
729				unseen: RangeSet::new(),
730				untaken: RangeSet::new(),
731				fronts: 1,
732				result,
733			},
734		);
735		self.queue.push_back(id);
736		Some(join)
737	}
738
739	/// Count a join out of reading `groups` of fill `id`. What nobody reads any more is no
740	/// longer routed to it: a reader wanting it later asks afresh rather than joining a fetch
741	/// being cancelled, so a key a fill stops owing stays unowed. Its answers are
742	/// forgotten too, so a wide fill holds the answers its readers have yet to take, not one
743	/// per group its source answered.
744	fn unwant(&mut self, id: u64, groups: ops::Range<u64>) {
745		let Some(pending) = self.pending.get_mut(&id) else {
746			return;
747		};
748		let unwanted = pending.unwant(groups);
749		let answered = {
750			let outcome = pending.result.read();
751			unwanted.iter().any(|run| {
752				outcome.refused.overlaps(run) || outcome.accepted.overlaps(run) || outcome.unfit.overlaps(run)
753			})
754		};
755		if answered && let Ok(mut outcome) = pending.result.write() {
756			for run in &unwanted {
757				outcome.refused.remove(run.clone());
758				outcome.accepted.remove(run.clone());
759				outcome.unfit.remove(run.clone());
760			}
761		}
762		for run in unwanted {
763			for range in self.routed(id, &run) {
764				self.covers.remove(range);
765			}
766		}
767	}
768
769	/// A debt evicted `key`, which fill `id` held, with no room to hold it again: see
770	/// `Outcome::unfit`. Only while a join still reads it, which bounds it by the fill's wants.
771	pub(super) fn unfit(&self, id: u64, key: u64) {
772		if let Some(pending) = self.pending.get(&id)
773			&& pending.wants.contains_key(&key)
774			&& let Ok(mut outcome) = pending.result.write()
775		{
776			outcome.unfit.insert(key..key + 1);
777		}
778	}
779
780	/// Whether a join of fill `id` still reads `key`.
781	pub(super) fn wants(&self, id: u64, key: u64) -> bool {
782		self.pending
783			.get(&id)
784			.is_some_and(|pending| pending.wants.contains_key(&key))
785	}
786
787	/// Whether fill `id` holds `key` for a reader: a join still reads it, and some reader
788	/// fronts the fill.
789	pub(super) fn holds_for(&self, id: u64, key: u64) -> bool {
790		self.pending
791			.get(&id)
792			.is_some_and(|pending| pending.fronts > 0 && pending.wants.contains_key(&key))
793	}
794
795	/// Whether some reader fronts fill `id`.
796	fn fronted(&self, id: u64) -> bool {
797		self.pending.get(&id).is_some_and(|pending| pending.fronts > 0)
798	}
799
800	/// Whether a join of fill `id` still reads any of `groups`.
801	#[cfg_attr(not(feature = "async"), allow(dead_code, reason = "async-only"))]
802	fn wants_any(&self, id: u64, groups: &ops::Range<u64>) -> bool {
803		self.pending
804			.get(&id)
805			.is_some_and(|pending| pending.wants.overlaps(groups))
806	}
807
808	/// Take the oldest queued fill, still pending (joinable) until it ends.
809	fn pop(&mut self) -> Option<u64> {
810		let id = self.queue.pop_front()?;
811		let pending = self.pending.get_mut(&id).expect("a queued fill is pending");
812		pending.queued = false;
813		Some(id)
814	}
815
816	/// Drop fill `id`: nobody wants it, so it records nothing.
817	fn withdraw(&mut self, id: u64) {
818		let Some(pending) = self.pending.get(&id) else {
819			return;
820		};
821		if pending.queued {
822			self.queue.retain(|queued| *queued != id);
823		}
824		self.end(id);
825	}
826
827	/// The parts of `groups` routed to fill `id`.
828	fn routed(&self, id: u64, groups: &ops::Range<u64>) -> Vec<ops::Range<u64>> {
829		self.covers
830			.overlapping(groups)
831			.filter(|(_, covering)| **covering == id)
832			.map(|(range, _)| range.start.max(groups.start)..range.end.min(groups.end))
833			.collect()
834	}
835
836	/// Forget fill `id`, closing it for its readers.
837	fn end(&mut self, id: u64) {
838		let Some(pending) = self.pending.remove(&id) else {
839			return;
840		};
841		for range in self.routed(id, &(pending.start.group..pending.end)) {
842			self.covers.remove(range);
843		}
844	}
845}
846
847/// The pieces of `gap` once `skip` is taken out of it.
848fn without(gap: ops::Range<u64>, skip: Option<u64>) -> impl Iterator<Item = ops::Range<u64>> {
849	let pieces = match skip {
850		Some(skip) if gap.contains(&skip) => [gap.start..skip, skip + 1..gap.end],
851		_ => [gap, 0..0],
852	};
853	pieces.into_iter().filter(|piece| !piece.is_empty())
854}
855
856/// Stop routing readers wanting `groups` to fill `id`: they were answered. Reads first, so
857/// an answer that changes nothing wakes no handler parked on the queue.
858fn uncover(fills: &kio::Shared<FillState>, id: u64, groups: ops::Range<u64>) {
859	let mut fills = fills.lock();
860	let routed = fills.routed(id, &groups);
861	for range in routed {
862		fills.covers.remove(range);
863	}
864}
865
866/// Pop the next queued fill, or surface the track's abort once none is queued.
867pub(super) fn poll_requested(
868	state: &kio::Producer<TrackState>,
869	fills: &kio::Shared<FillState>,
870	waiter: &kio::Waiter,
871) -> Poll<Result<FillGroups>> {
872	// Prefer serving a queued fill, even if the track has since aborted.
873	if let Poll::Ready(mut guard) = fills.poll(waiter, |fills| match fills.has_queued() {
874		true => Poll::Ready(()),
875		false => Poll::Pending,
876	}) {
877		let id = guard.pop().expect("predicate guaranteed a fill");
878		let pending = guard.pending.get(&id).expect("popped fill is pending");
879		let (start, end, frame_end, floor, flight) = (
880			pending.start,
881			pending.end,
882			pending.frame_end,
883			pending.floor,
884			pending.flight,
885		);
886		let (asks, result) = (pending.asks.clone(), pending.result.clone());
887		drop(guard);
888		// Built with the fills unlocked, so no other lock nests under theirs.
889		let inner = Inner {
890			state: state.clone(),
891			fills: fills.clone(),
892			id,
893			start,
894			end,
895			frame_end,
896			floor,
897			flight,
898			asks,
899			result,
900		};
901		return Poll::Ready(Ok(FillGroups {
902			inner: Arc::new(SendCell::new(inner)),
903			prev: None,
904		}));
905	}
906
907	// No fill queued: surface a track abort so the handler loop can exit.
908	match state.poll_ref(waiter, |state| match state.outcome.aborted() {
909		Some(err) => Poll::Ready(err.clone()),
910		None => Poll::Pending,
911	}) {
912		Poll::Ready(Ok(err)) => Poll::Ready(Err(err)),
913		Poll::Ready(Err(closed)) => Poll::Ready(Err(closed.outcome.aborted().cloned().unwrap_or(Error::Dropped))),
914		Poll::Pending => Poll::Pending,
915	}
916}
917
918/// A run of groups readers miss, for a [`Requests`](super::Requests) handler to serve.
919///
920/// It names `start.group` up to the exclusive [`end`](Self::end), the first group from
921/// [`start`](Self::start)'s frame. A reader's time start that no group the cache holds places
922/// asks for the group containing that time as a fill one key wide, from the time, whose first
923/// group may start below it: see [`floor`](Self::floor). Its [`priority`](Self::priority)
924/// and [`order`](Self::order) follow its readers as they
925/// change, so read them as each group is served. The handler calls [`accept`](Self::accept) for each group
926/// it has and [`drop_groups`](Self::drop_groups) for the rest, one group at a time as
927/// [`poll_wanted_changed`](Self::poll_wanted_changed) yields them, so it writes no faster than its
928/// readers read. Serve the fills you take concurrently: each waits on its own readers, so
929/// serving them in turn holds every fill behind the readers of the one before. Dropping the fill names
930/// whatever is left as dropped while a reader still wants it; once nobody does, the fill is
931/// withdrawn and records nothing, so stop serving it once [`wanted`](Self::wanted) is `None`.
932/// A reader narrowing its ranges may leave a single group, so stop serving that one when
933/// [`poll_unwanted`](Self::poll_unwanted) is ready and move on to [`wanted`](Self::wanted).
934///
935/// A clone serves the same fill, and the fill is settled once the last clone drops. Each
936/// clone watches on its own, so its first [`poll_wanted_changed`](Self::poll_wanted_changed)
937/// reports the current value.
938pub struct FillGroups {
939	// Its track state reaches every group of the track, so the cell proves `Send` once
940	// here instead of inside every session machine holding a fill.
941	inner: Arc<SendCell<Inner>>,
942	// The value `poll_wanted_changed` last returned, or `None` before it returned any.
943	prev: Option<Option<u64>>,
944}
945
946impl Clone for FillGroups {
947	fn clone(&self) -> Self {
948		Self {
949			inner: self.inner.clone(),
950			prev: None,
951		}
952	}
953}
954
955/// The state a fill and its per-group handles share. The last one dropping settles what
956/// was left.
957struct Inner {
958	state: kio::Producer<TrackState>,
959	fills: kio::Shared<FillState>,
960	id: u64,
961	start: Position,
962	end: u64,
963	// Exclusive frame cap in the last group; None asks through the original end.
964	frame_end: Option<u64>,
965	// A time start's floor; see [`FillGroups::floor`].
966	floor: Option<u64>,
967	// Answered with a copy of its own rather than the cache's; see [`FillState::fly`].
968	flight: bool,
969	asks: kio::Shared<Asks>,
970	result: kio::Producer<Outcome>,
971}
972
973impl FillGroups {
974	/// The first group to fill, and the frame within it to start from.
975	pub fn start(&self) -> Position {
976		self.inner.start
977	}
978
979	/// The oldest group the first group may start at: [`start`](Self::start)'s, unless that is a
980	/// reader's time start no group the cache holds places. Then the first group is the one
981	/// containing that time: the group starting at it, or else the newest one starting before
982	/// it, at or after the floor; once that group ends whole at or before the time, the reader
983	/// starts past it, at its End. A handler knowing its groups only by key serves that key as
984	/// any other; one that can tell which group holds the time, as from an index, may
985	/// [`accept`](Self::accept) that group instead, or [`drop_groups`](Self::drop_groups) the
986	/// key when none does. The reader starts where the answer says, never where the groups
987	/// the cache holds happen to say: a drop, or the fill closed unanswered, says no group
988	/// starts from the floor through the time, so it starts at the group just below the floor
989	/// (at its End once the time is past that group's span), or past the time when the floor is
990	/// 0. A [refusal](Self::refuse_groups) fails the reader
991	/// with its error until its ranges change.
992	pub fn floor(&self) -> u64 {
993		self.inner.floor.unwrap_or(self.inner.start.group)
994	}
995
996	/// Whether it answers a reader's time start, whose first group is the one containing the
997	/// time from the [`floor`](Self::floor) through it, even when the floor is the time
998	/// itself: a drop then says no group starts there, and a refusal fails the reader.
999	pub fn is_time_start(&self) -> bool {
1000		self.inner.floor.is_some()
1001	}
1002
1003	/// Whether this fill asks for a separate flight copy of one group rather than the shared
1004	/// cache slot.
1005	#[cfg_attr(not(feature = "async"), allow(dead_code, reason = "async-only"))]
1006	pub(crate) fn is_flight(&self) -> bool {
1007		self.inner.flight
1008	}
1009
1010	/// The frame group `key` starts from: [`start`](Self::start)'s frame for the first
1011	/// group, 0 for the rest.
1012	pub fn frame_start(&self, key: u64) -> u64 {
1013		self.inner.frame_start(key)
1014	}
1015
1016	/// The exclusive end group.
1017	pub fn end(&self) -> u64 {
1018		self.inner.end
1019	}
1020
1021	/// The most urgent delivery priority among the readers waiting on it now.
1022	pub fn priority(&self) -> i8 {
1023		self.inner.asks.read().priority()
1024	}
1025
1026	/// Which end to fill first now: [`Order::Descending`] is newest first.
1027	pub fn order(&self) -> Order {
1028		self.inner.asks.read().order()
1029	}
1030
1031	/// Insert group `key` into the track's cache, handing it to the readers waiting on
1032	/// it, and return a [`group::Producer`] to fill.
1033	///
1034	/// On a track this publisher accepted, a group past every one it produced is its live feed,
1035	/// which its subscriptions deliver too; one below is history, served only to whoever misses
1036	/// it. A relay's copy leaves that to its upstream's subscription.
1037	///
1038	/// The group starts at [`start`](Self::start)'s frame when it is the first group, so the
1039	/// frames written keep the indices they have in the group. A key from the
1040	/// [`floor`](Self::floor) up to the start's answers the start with that group, from its
1041	/// first frame. `info` sets the track's [`Info`] if it hasn't been accepted yet (a fetch
1042	/// with no live subscription), and is ignored otherwise. Returns `None` if the group was
1043	/// already answered or cached. Errors with [`Error::InvalidRange`] outside the fill,
1044	/// [`Error::Skipped`] if the track skipped it, or the track's abort error.
1045	///
1046	/// A group is named by its frame 0's timestamp, so on a timed track writing frame 0 at any
1047	/// other time is [`Error::TimestampMismatch`].
1048	pub fn accept(&self, key: u64, info: impl Into<Option<Info>>) -> Result<Option<group::Producer>> {
1049		Ok(self.inner.accept(key, info.into())?.map(group::Producer::keyed))
1050	}
1051
1052	/// Name `groups` as never to be delivered: the source no longer has them. Readers stop
1053	/// waiting for them, and the track records them so nobody asks again. Only the groups a
1054	/// reader still reads count; the rest of the fill was never owed.
1055	pub fn drop_groups(&self, groups: ops::Range<u64>) {
1056		let owed = self.inner.owed(groups);
1057		self.inner
1058			.drop_groups(&owed, Error::NotFound, super::Hole::drop(StreamError::NotFound));
1059	}
1060
1061	/// Refuse `groups` with `err` without saying the source lost them, as when serving them
1062	/// failed for now or this request asks what the source can't serve. The readers waiting
1063	/// now stop waiting, and a later reader asks again. Only the groups a reader still reads
1064	/// count, as with [`Self::drop_groups`].
1065	pub fn refuse_groups(&self, groups: ops::Range<u64>, err: Error) {
1066		let owed = self.inner.owed(groups);
1067		self.inner.refuse(&owed, err);
1068	}
1069
1070	/// Name `groups` as never produced, as the source answered a request for them: readers
1071	/// pass over them, as over a skip the track recorded, however soon the cache forgets it.
1072	#[cfg_attr(not(feature = "async"), allow(dead_code, reason = "async-only"))]
1073	pub(crate) fn skip_groups(&self, groups: ops::Range<u64>) {
1074		let owed = self.inner.owed(groups);
1075		self.inner.drop_groups(&owed, Error::Skipped, super::Hole::Skip);
1076	}
1077
1078	/// Poll until no reader waits on this fill: it is withdrawn, so stop serving it.
1079	#[cfg_attr(not(feature = "async"), allow(dead_code, reason = "async-only"))]
1080	pub(crate) fn poll_withdrawn(&self, waiter: &kio::Waiter) -> Poll<()> {
1081		self.inner.result.poll_wanted_changed(waiter, true).map(drop)
1082	}
1083
1084	/// Whether a reader still waits for group `key` from this fill: false once every
1085	/// reader took it or narrowed past it, or nobody waits on the fill. A group stops being
1086	/// wanted for good; once accepted and taken, [`group::Producer::demand`](crate::group::Producer::demand)
1087	/// says who reads it.
1088	pub fn is_wanted(&self, key: u64) -> bool {
1089		self.inner.is_wanted(key)
1090	}
1091
1092	/// Resolves once no reader waits for group `key` from this fill, so stop serving it.
1093	#[cfg_attr(feature = "async", kio::wrapper)]
1094	pub fn poll_unwanted(&self, key: u64, waiter: &kio::Waiter) -> Poll<()> {
1095		self.inner.poll_unwanted(key, waiter)
1096	}
1097
1098	/// The fill's id, which its holds go by.
1099	#[cfg(all(test, feature = "async"))]
1100	pub(super) fn id(&self) -> u64 {
1101		self.inner.id
1102	}
1103
1104	/// How many answer runs the fill still holds for its readers.
1105	#[cfg(all(test, feature = "async"))]
1106	pub(super) fn answers(&self) -> usize {
1107		let outcome = self.inner.result.read();
1108		outcome.refused.iter().count() + outcome.accepted.iter().count()
1109	}
1110
1111	/// The runs answered so far, even once their readers consumed the answers.
1112	#[cfg(all(test, feature = "async"))]
1113	pub(super) fn resolved_runs(&self) -> Vec<ops::Range<u64>> {
1114		self.inner.result.read().resolved.iter().cloned().collect()
1115	}
1116
1117	/// The next group still owed in the fill's order: a reader still reads it, and it was
1118	/// neither answered nor delivered live since it was asked. `None` once none is owed or
1119	/// no reader waits on the fill, so stop serving it. It does not wait for the readers to
1120	/// take what was served before it; [`poll_wanted_changed`](Self::poll_wanted_changed) does.
1121	pub fn wanted(&self) -> Option<u64> {
1122		self.wanted_except(None)
1123	}
1124
1125	/// [`Self::wanted`], passing over `skip`.
1126	fn wanted_except(&self, skip: Option<u64>) -> Option<u64> {
1127		if !self.inner.result.wanted() {
1128			return None;
1129		}
1130		loop {
1131			let wanted = self.inner.wanted();
1132			let key = {
1133				let outcome = self.inner.result.read();
1134				let mut gaps = wanted
1135					.iter()
1136					.flat_map(|run| outcome.resolved.gaps(run))
1137					.flat_map(|gap| without(gap, skip));
1138				match self.order() {
1139					Order::Ascending => gaps.next().map(|gap| gap.start),
1140					Order::Descending => gaps.last().map(|gap| gap.end - 1),
1141				}
1142			};
1143			let front = self.inner.untaken_front();
1144			let Some(key) = key else {
1145				self.inner.sync_holds(front, None);
1146				return None;
1147			};
1148			// The live feed may have delivered it since: answered by the cache, not the source.
1149			// Never a flight's, which the cached copy shed.
1150			let cached = !self.inner.flight
1151				&& self
1152					.inner
1153					.state
1154					.read()
1155					.covering_range(key, self.inner.bounds(key))
1156					.is_some();
1157			if !cached {
1158				// Waiting on a run, the fill holds its first group to land, unless it holds one
1159				// a reader has yet to take.
1160				let awaiting = front
1161					.is_none()
1162					.then(|| (self.run_from(key, self.inner.owed_around(key)), self.order()));
1163				self.inner.sync_holds(front, awaiting);
1164				return Some(key);
1165			}
1166			// Held as it is answered, if it is the first a reader has yet to take and a reader
1167			// fronts the fill: the pool may evict anything else before the reader gets to it.
1168			// Checked again under the lock that holds it, since an eviction may have taken it
1169			// since.
1170			if front.is_none() && self.inner.fills.read().fronted(self.inner.id) {
1171				let Ok(mut state) = TrackState::modify(&self.inner.state) else {
1172					return Some(key);
1173				};
1174				if state.covering_range(key, self.inner.bounds(key)).is_none() {
1175					continue;
1176				}
1177				state.hold_fill(self.inner.id, Some(key), None);
1178			}
1179			if !self.inner.answer_cached(key) {
1180				return Some(key);
1181			}
1182		}
1183	}
1184
1185	/// The next group to serve: [`wanted`](Self::wanted) once it differs from what this handle
1186	/// last returned and every group this fill answered reached a reader, which picks it up
1187	/// when it next reads. `None` once the fill is withdrawn, or answered and taken: keep the
1188	/// fill until then, since the cache holds what a reader has yet to take only while the
1189	/// fill lives. The first call returns at once, unless a group already answered has yet to
1190	/// reach a reader.
1191	///
1192	/// So `while let Some(key) = fill.wanted_changed().await` writes one group at a time
1193	/// as the fastest reader reads on. The cache holds the first group in the fill's order that
1194	/// a reader has yet to take, which no eviction takes before it does: a fill holds at most
1195	/// one group, however far its readers fall behind, and a reader asks again for any other
1196	/// it loses. A reader reading in another order than the fill's picks up groups it cannot
1197	/// take yet, so the fill moves on.
1198	#[cfg_attr(feature = "async", kio::wrapper)]
1199	pub fn poll_wanted_changed(&mut self, waiter: &kio::Waiter) -> Poll<Option<u64>> {
1200		// Arm every input of `wanted` before reading it, so a change in between still wakes:
1201		// the readers leaving, narrowing, or taking a group, the answers, the order, and a
1202		// group arriving through the live feed, which the cache then answers.
1203		let _ = self.inner.result.poll_wanted_changed(waiter, true);
1204		let _ = self.inner.result.poll_ref(waiter, |_| Poll::<()>::Pending);
1205		let _ = self.inner.state.poll_ref(waiter, |_| Poll::<()>::Pending);
1206		let _ = self.inner.fills.poll(waiter, |_| Poll::Pending);
1207		let _ = self.inner.asks.poll(waiter, |_| Poll::Pending);
1208		let wanted = self.wanted();
1209		let waits = match wanted {
1210			Some(_) => self.inner.is_unseen(),
1211			None => self.inner.untaken_front().is_some(),
1212		};
1213		if self.prev == Some(wanted) || waits {
1214			return Poll::Pending;
1215		}
1216		self.prev = Some(wanted);
1217		Poll::Ready(wanted)
1218	}
1219
1220	/// Poll until every group this fill answered reached a reader, or nobody waits on the
1221	/// fill, as [`Self::poll_wanted_changed`] paces.
1222	#[cfg_attr(not(feature = "async"), allow(dead_code, reason = "async-only"))]
1223	pub(crate) fn poll_paced(&self, waiter: &kio::Waiter) -> Poll<()> {
1224		if self.poll_withdrawn(waiter).is_ready() {
1225			return Poll::Ready(());
1226		}
1227		let id = self.inner.id;
1228		self.inner
1229			.fills
1230			.poll(waiter, |fills| match fills.pending.get(&id) {
1231				Some(pending) if !pending.unseen.is_empty() => Poll::Pending,
1232				_ => Poll::Ready(()),
1233			})
1234			.map(drop)
1235	}
1236
1237	/// Poll until a reader took every group this fill answered, or nobody waits on the fill:
1238	/// the cache holds what a reader has yet to take only while the fill lives.
1239	#[cfg_attr(not(feature = "async"), allow(dead_code, reason = "async-only"))]
1240	pub(crate) fn poll_taken(&self, waiter: &kio::Waiter) -> Poll<()> {
1241		if self.poll_withdrawn(waiter).is_ready() {
1242			return Poll::Ready(());
1243		}
1244		let _ = self.inner.fills.poll(waiter, |_| Poll::<()>::Pending);
1245		let _ = self.inner.asks.poll(waiter, |_| Poll::<()>::Pending);
1246		match self.inner.untaken_front() {
1247			// The hold moves on as readers take what it answered.
1248			Some(front) => {
1249				self.inner.sync_holds(Some(front), None);
1250				Poll::Pending
1251			}
1252			None => Poll::Ready(()),
1253		}
1254	}
1255
1256	/// What this fill held that a debt evicted with no room to hold it again, answered or
1257	/// still landing: asking for it again would see it evicted the same way.
1258	#[cfg_attr(not(feature = "async"), allow(dead_code, reason = "async-only"))]
1259	pub(crate) fn unfit(&self) -> RangeSet<u64> {
1260		self.inner.result.read().unfit.clone()
1261	}
1262
1263	/// Whether a group this fill answered has yet to reach a reader, so it asks for nothing
1264	/// more for now.
1265	#[cfg_attr(not(feature = "async"), allow(dead_code, reason = "async-only"))]
1266	pub(crate) fn is_paced(&self) -> bool {
1267		self.inner.is_unseen()
1268	}
1269
1270	/// Whether a reader has yet to take a group this fill answered, which the cache holds
1271	/// only while the fill lives.
1272	#[cfg_attr(not(feature = "async"), allow(dead_code, reason = "async-only"))]
1273	pub(crate) fn is_holding(&self) -> bool {
1274		self.inner.untaken_front().is_some()
1275	}
1276
1277	/// Refuse every group still owed with `err`, which says nothing about whether the source
1278	/// has them, so nothing is recorded dropped.
1279	#[cfg_attr(not(feature = "async"), allow(dead_code, reason = "async-only"))]
1280	pub(crate) fn refuse(&self, err: Error) {
1281		let unresolved = self.inner.unresolved(self.inner.start.group..self.inner.end);
1282		self.inner.refuse(&unresolved, err);
1283	}
1284
1285	/// The next run of groups still owed, in the fill's order: [`Self::wanted`]'s group,
1286	/// extended over the owed groups beside it up to the nearest one the cache holds, so a
1287	/// session asks its source for the whole run at once.
1288	#[cfg_attr(not(feature = "async"), allow(dead_code, reason = "async-only"))]
1289	pub(crate) fn next_run(&self) -> Option<ops::Range<u64>> {
1290		let key = self.wanted()?;
1291		Some(self.run_from(key, self.inner.owed_around(key)))
1292	}
1293
1294	/// [`Self::next_run`], passing over `skip`: a group another request is already bringing,
1295	/// so the groups around it are served while it waits. `None` once nothing else is owed.
1296	#[cfg_attr(not(feature = "async"), allow(dead_code, reason = "async-only"))]
1297	pub(crate) fn next_run_except(&self, skip: u64) -> Option<ops::Range<u64>> {
1298		let key = self.wanted_except(Some(skip))?;
1299		let owed = self.inner.owed_around(key);
1300		let owed = match skip < key {
1301			true => owed.start.max(skip + 1)..owed.end,
1302			false => owed.start..owed.end.min(skip),
1303		};
1304		Some(self.run_from(key, owed))
1305	}
1306
1307	/// The run from `key` over the `owed` groups beside it, in the fill's order, up to
1308	/// the nearest one the cache holds.
1309	#[cfg_attr(not(feature = "async"), allow(dead_code, reason = "async-only"))]
1310	fn run_from(&self, key: u64, owed: ops::Range<u64>) -> ops::Range<u64> {
1311		let state = self.inner.state.read();
1312		let held = |(_, slot): &(&u64, &super::Slot)| !slot.is_aborted();
1313		match self.order() {
1314			Order::Ascending => {
1315				let end = state
1316					.lookup
1317					.range(key + 1..owed.end)
1318					.find(held)
1319					.map_or(owed.end, |(held, _)| *held);
1320				key..end
1321			}
1322			Order::Descending => {
1323				let start = state
1324					.lookup
1325					.range(owed.start..key)
1326					.rev()
1327					.find(held)
1328					.map_or(owed.start, |(held, _)| held + 1);
1329				start..key + 1
1330			}
1331		}
1332	}
1333
1334	/// The newest group the track's live feed produced, while a feed still writes the track:
1335	/// its source may still be writing that group, so a fetch including it would cut it short.
1336	#[cfg_attr(not(feature = "async"), allow(dead_code, reason = "async-only"))]
1337	pub(crate) fn live_group(&self) -> Option<u64> {
1338		let state = self.inner.state.read();
1339		match state.feed.is_live() && !state.is_complete() {
1340			true => state.latest_live(),
1341			false => None,
1342		}
1343	}
1344
1345	/// Poll until no reader waits for any group in `groups` from this fill.
1346	#[cfg_attr(not(feature = "async"), allow(dead_code, reason = "async-only"))]
1347	pub(crate) fn poll_unwanted_groups(&self, groups: ops::Range<u64>, waiter: &kio::Waiter) -> Poll<()> {
1348		if self.poll_withdrawn(waiter).is_ready() {
1349			return Poll::Ready(());
1350		}
1351		let id = self.inner.id;
1352		self.inner
1353			.fills
1354			.poll(waiter, |fills| match fills.wants_any(id, &groups) {
1355				true => Poll::Pending,
1356				false => Poll::Ready(()),
1357			})
1358			.map(drop)
1359	}
1360
1361	/// Poll until the track is aborted, with its abort error.
1362	#[cfg_attr(not(feature = "async"), allow(dead_code, reason = "async-only"))]
1363	pub(crate) fn poll_aborted(&self, waiter: &kio::Waiter) -> Poll<Error> {
1364		TrackState::poll_aborted(&self.inner.state, waiter)
1365	}
1366
1367	/// The track the fill serves.
1368	#[cfg_attr(not(feature = "async"), allow(dead_code, reason = "async-only"))]
1369	pub(crate) fn track(&self) -> kio::Producer<TrackState> {
1370		self.inner.state.clone()
1371	}
1372
1373	/// The fill's answers, kept open as long as this handle lives.
1374	#[cfg(all(test, feature = "async"))]
1375	pub(crate) fn joined(&self) -> kio::Producer<Outcome> {
1376		self.inner.result.clone()
1377	}
1378
1379	/// Refuse `groups` with the source's answer to a request for them: only [`Error::Old`]
1380	/// under the publisher's max age (with every older group of the fill) is recorded, as a
1381	/// stale verdict under that age.
1382	#[cfg_attr(not(feature = "async"), allow(dead_code, reason = "async-only"))]
1383	pub(crate) fn reject_groups(&self, groups: ops::Range<u64>, err: Error) {
1384		self.inner.reject(groups, err);
1385	}
1386
1387	/// Declare the track's exclusive final key, as the source answering a request
1388	/// reported it. A no-op once the track declared an end, or holds a later group.
1389	#[cfg_attr(not(feature = "async"), allow(dead_code, reason = "async-only"))]
1390	pub(crate) fn finish_track_at(&self, final_key: u64) {
1391		self.inner.finish_track_at(final_key);
1392	}
1393
1394	/// A handle on group `key` alone, for a session serving the fill one group at a time.
1395	/// It keeps what the readers ask now, which is what its source gets asked.
1396	#[cfg_attr(not(feature = "async"), allow(dead_code, reason = "async-only"))]
1397	pub(crate) fn group(&self, key: u64) -> GroupFill {
1398		GroupFill {
1399			inner: self.inner.clone(),
1400			key,
1401			frame_start: self.inner.frame_start(key),
1402			frame_end: self.inner.bounds(key).end,
1403			priority: self.priority(),
1404		}
1405	}
1406}
1407
1408impl Inner {
1409	fn contains(&self, key: u64) -> bool {
1410		(self.floor.unwrap_or(self.start.group)..self.end).contains(&key)
1411	}
1412
1413	fn is_wanted(&self, key: u64) -> bool {
1414		self.result.wanted() && self.fills.read().wants(self.id, key)
1415	}
1416
1417	/// Whether a group this fill answered has yet to reach a reader.
1418	fn is_unseen(&self) -> bool {
1419		self.fills
1420			.read()
1421			.pending
1422			.get(&self.id)
1423			.is_some_and(|pending| !pending.unseen.is_empty())
1424	}
1425
1426	/// The first group in the fill's order that it answered and no reader took yet, which the
1427	/// fill holds.
1428	fn untaken_front(&self) -> Option<u64> {
1429		let order = self.asks.read().order();
1430		let fills = self.fills.read();
1431		let untaken = &fills.pending.get(&self.id)?.untaken;
1432		match order {
1433			Order::Ascending => untaken.iter().next().map(|run| run.start),
1434			Order::Descending => untaken.iter().next_back().map(|run| run.end - 1),
1435		}
1436	}
1437
1438	/// Hold `front` and await `awaiting` for the fill's readers from now on, or nothing while
1439	/// no reader fronts the fill, unless the track does already: a change takes the track's
1440	/// lock, which wakes everything parked on it. A flight's copy is its readers' own, which no
1441	/// eviction takes from them.
1442	fn sync_holds(&self, front: Option<u64>, awaiting: Option<(ops::Range<u64>, Order)>) {
1443		if self.flight {
1444			return;
1445		}
1446		let (front, awaiting) = match self.fills.read().fronted(self.id) {
1447			true => (front, awaiting),
1448			false => (None, None),
1449		};
1450		if self.state.read().fill_holds_as(self.id, front, &awaiting) {
1451			return;
1452		}
1453		if let Ok(mut state) = TrackState::modify(&self.state) {
1454			state.hold_fill(self.id, front, awaiting);
1455		}
1456	}
1457
1458	/// Answer `key` from the cache, for the readers that still read it to take. Returns
1459	/// whether the answer went out.
1460	fn answer_cached(&self, key: u64) -> bool {
1461		// Recorded before the answer goes out, as `accept_from` does: a reader may pick it up
1462		// and take it the moment it does, which must clear it.
1463		let untaken = {
1464			let mut fills = self.fills.lock();
1465			match fills.pending.get_mut(&self.id) {
1466				Some(pending) if pending.wants.contains_key(&key) => {
1467					pending.unseen.insert(key..key + 1);
1468					pending.untaken.insert(key..key + 1);
1469					true
1470				}
1471				_ => false,
1472			}
1473		};
1474		let Ok(mut outcome) = self.result.write() else {
1475			if untaken && let Some(pending) = self.fills.lock().pending.get_mut(&self.id) {
1476				pending.unseen.remove(key..key + 1);
1477				pending.untaken.remove(key..key + 1);
1478			}
1479			return false;
1480		};
1481		outcome.accept(key..key + 1);
1482		drop(outcome);
1483		uncover(&self.fills, self.id, key..key + 1);
1484		true
1485	}
1486
1487	fn poll_unwanted(&self, key: u64, waiter: &kio::Waiter) -> Poll<()> {
1488		if self.result.poll_wanted_changed(waiter, true).is_ready() {
1489			return Poll::Ready(());
1490		}
1491		self.fills
1492			.poll(waiter, |fills| match fills.wants(self.id, key) {
1493				true => Poll::Pending,
1494				false => Poll::Ready(()),
1495			})
1496			.map(drop)
1497	}
1498
1499	/// The runs of the fill a reader still reads, read before any other lock.
1500	fn wanted(&self) -> RangeSet<u64> {
1501		let span = self.start.group..self.end;
1502		let fills = self.fills.lock();
1503		fills
1504			.pending
1505			.get(&self.id)
1506			.map_or_else(RangeSet::new, |pending| pending.wanted(&span))
1507	}
1508
1509	fn frame_start(&self, key: u64) -> u64 {
1510		match key == self.start.group {
1511			true => self.start.frame,
1512			false => 0,
1513		}
1514	}
1515
1516	fn bounds(&self, key: u64) -> group::Bounds {
1517		group::Bounds {
1518			start: self.frame_start(key),
1519			end: if key.checked_add(1) == Some(self.end) {
1520				self.frame_end
1521			} else {
1522				None
1523			},
1524		}
1525	}
1526
1527	fn accept(&self, key: u64, info: Option<Info>) -> Result<Option<group::Producer>> {
1528		self.accept_from(key, info, self.bounds(key))
1529	}
1530
1531	fn accept_from(&self, key: u64, info: Option<Info>, frames: group::Bounds) -> Result<Option<group::Producer>> {
1532		if !self.contains(key) {
1533			return Err(Error::InvalidRange);
1534		}
1535		let Some(end) = key.checked_add(1) else {
1536			return Err(Error::InvalidRange);
1537		};
1538		// A key below the start answers the start, so no other group starts from it through
1539		// the start.
1540		let answered = match key < self.start.group {
1541			true => key..self.start.group + 1,
1542			false => key..end,
1543		};
1544		if self.result.read().resolved.overlaps(&answered) {
1545			return Ok(None);
1546		}
1547		// Written for a reader that has yet to pick it up, which the next group waits on, and
1548		// to take it, which the cache holds it for.
1549		// Recorded before the group is cached, since a reader may take it from the cache and
1550		// release it before the answer goes out, which must clear it.
1551		let untaken = {
1552			let mut fills = self.fills.lock();
1553			match fills.pending.get_mut(&self.id) {
1554				Some(pending) if pending.wants.contains_key(&key) => {
1555					pending.unseen.insert(key..end);
1556					pending.untaken.insert(key..end);
1557					true
1558				}
1559				_ => false,
1560			}
1561		};
1562		let front = self.untaken_front();
1563		let fronted = self.fills.read().fronted(self.id);
1564		// Cache the group before answering: readers resolve an accept through the cache. Held
1565		// as it is cached, if it is the first a reader has yet to take and this is that
1566		// reader's front fill: the pool may evict anything else before the reader gets to it. A time start answered below its time
1567		// holds the group it names, created or cached, under the same lock, so its End stays
1568		// known once the cache lets it go.
1569		let mut answer = None;
1570		let res = TrackState::modify(&self.state).and_then(|mut state| {
1571			let res = match self.flight {
1572				true => state.insert_flight(key, frames, info).map(Some),
1573				false => state.insert_group_request(key, frames, info),
1574			};
1575			if !self.flight && fronted && matches!(res, Ok(Some(_))) {
1576				state.hold_fill(self.id, front, None);
1577			}
1578			if key < self.start.group {
1579				answer = match &res {
1580					Ok(Some(group)) => Some(group.handle()),
1581					_ => state.cached_handle(key),
1582				};
1583			}
1584			let deferred = state.deferred();
1585			drop(state);
1586			deferred.wake();
1587			res
1588		});
1589		if untaken
1590			&& !matches!(res, Ok(Some(_)))
1591			&& let Some(pending) = self.fills.lock().pending.get_mut(&self.id)
1592		{
1593			pending.unseen.remove(key..end);
1594			pending.untaken.remove(key..end);
1595		}
1596		if let Ok(mut outcome) = self.result.write() {
1597			outcome.accept(key..end);
1598			outcome.resolved.insert(answered);
1599			if let Ok(Some(group)) = &res
1600				&& (self.flight || frames.start > 0 || frames.end.is_some())
1601			{
1602				outcome.partial.insert(key, group.handle());
1603			}
1604			if answer.is_some() {
1605				outcome.answer = answer;
1606			}
1607		}
1608		uncover(&self.fills, self.id, key..end);
1609		res
1610	}
1611
1612	/// Refuse `groups` with `err`, as the source answered, recording them in the track's drops
1613	/// as `hole` says, so the later readers it settles do not ask again. A time-start lookup
1614	/// (`floor.is_some()`) only answers where the time falls and records no drop on the track.
1615	fn drop_groups(&self, groups: &RangeSet<u64>, err: Error, hole: super::Hole) {
1616		if groups.is_empty() {
1617			return;
1618		}
1619		if self.floor.is_none()
1620			&& let Ok(mut state) = TrackState::modify(&self.state)
1621		{
1622			for groups in groups.iter() {
1623				state.drop_unfed(groups.clone(), hole.clone());
1624			}
1625		}
1626		self.answer(groups, err, Some(hole));
1627	}
1628
1629	/// The part of `groups` inside the fill that a reader still reads and nothing answered yet.
1630	fn owed(&self, groups: ops::Range<u64>) -> RangeSet<u64> {
1631		let groups = groups.start.max(self.start.group)..groups.end.min(self.end);
1632		let mut owed = RangeSet::new();
1633		if groups.is_empty() {
1634			return owed;
1635		}
1636		let wanted = self.wanted();
1637		let outcome = self.result.read();
1638		for run in wanted.overlapping(&groups) {
1639			for gap in outcome
1640				.resolved
1641				.gaps(&(run.start.max(groups.start)..run.end.min(groups.end)))
1642			{
1643				owed.insert(gap);
1644			}
1645		}
1646		owed
1647	}
1648
1649	/// The part of `groups` nothing answered yet.
1650	fn unresolved(&self, groups: ops::Range<u64>) -> RangeSet<u64> {
1651		self.result.read().resolved.gaps(&groups).collect()
1652	}
1653
1654	fn refuse(&self, groups: &RangeSet<u64>, err: Error) {
1655		self.answer(groups, err, None);
1656	}
1657
1658	/// Answer `groups` with `err`, and the `hole` the source named when it has none of them.
1659	fn answer(&self, groups: &RangeSet<u64>, err: Error, hole: Option<super::Hole>) {
1660		if groups.is_empty() {
1661			return;
1662		}
1663		if let Ok(mut outcome) = self.result.write() {
1664			for groups in groups.iter() {
1665				outcome.refuse(groups.clone(), err.clone(), hole.clone());
1666			}
1667		}
1668		for groups in groups.iter() {
1669			uncover(&self.fills, self.id, groups.clone());
1670		}
1671	}
1672
1673	/// Refuse `groups` with `err`, as their source answered a request for them.
1674	#[cfg_attr(not(feature = "async"), allow(dead_code, reason = "async-only"))]
1675	fn reject(&self, groups: ops::Range<u64>, err: Error) {
1676		// Hoisted: a guard in the scrutinee would live through the arms, deadlocking against
1677		// the drop's write.
1678		let bound = self.state.read().max_age_bound();
1679		match (err, bound) {
1680			// Past the publisher's max age, and so is every group older than it: a timed track's
1681			// starts never rewind. The bound binds every reader, so the track holds it as a stale
1682			// verdict under that age: retryable, it lasts only until new terms or the drop set's
1683			// expiry window forget it.
1684			(Error::Old, Some(bound)) => {
1685				let older = self.start.group..groups.end;
1686				self.drop_groups(&self.owed(older), Error::Old, super::Hole::stale(bound));
1687			}
1688			// Anything else, a miss or an age not known here included, answers only this request:
1689			// one starting at another frame may still be served, such as the tail of a group whose
1690			// head expired. Refused for now, recorded nowhere.
1691			(err, _) => {
1692				let unresolved = self.unresolved(groups);
1693				self.refuse(&unresolved, err);
1694			}
1695		}
1696	}
1697
1698	/// The run of owed keys around `key`: read by a reader and unanswered.
1699	#[cfg_attr(not(feature = "async"), allow(dead_code, reason = "async-only"))]
1700	fn owed_around(&self, key: u64) -> ops::Range<u64> {
1701		let wanted = self.wanted();
1702		let outcome = self.result.read();
1703		wanted
1704			.overlapping(&(key..key + 1))
1705			.flat_map(|run| outcome.resolved.gaps(run))
1706			.find(|gap| gap.contains(&key))
1707			.unwrap_or(key..key + 1)
1708	}
1709
1710	#[cfg_attr(not(feature = "async"), allow(dead_code, reason = "async-only"))]
1711	fn finish_track_at(&self, final_key: u64) {
1712		if let Ok(mut state) = TrackState::modify(&self.state)
1713			&& state.declared().is_none()
1714		{
1715			let _ = state.set_end(Position::group(final_key), None);
1716		}
1717	}
1718}
1719
1720impl Drop for Inner {
1721	fn drop(&mut self) {
1722		// Whatever the handler left unanswered is named dropped, but only while a reader still
1723		// reads it: once demand left, the fill was withdrawn and records nothing. A group cached
1724		// since (the live feed delivered it) is no drop at all.
1725		let wanted = self.wanted();
1726		let left: RangeSet<u64> = {
1727			let outcome = self.result.read();
1728			wanted.iter().flat_map(|run| outcome.resolved.gaps(run)).collect()
1729		};
1730		if !left.is_empty() && self.result.wanted() {
1731			if self.floor.is_none()
1732				&& let Ok(mut state) = TrackState::modify(&self.state)
1733			{
1734				// Unanswered is a miss downstream, as an explicit `drop_groups` would say.
1735				for groups in left.iter() {
1736					state.drop_unfed(groups.clone(), super::Hole::drop(StreamError::NotFound));
1737				}
1738			}
1739			if let Ok(mut outcome) = self.result.write() {
1740				for groups in left.iter() {
1741					outcome.refuse(
1742						groups.clone(),
1743						Error::Dropped,
1744						Some(super::Hole::drop(StreamError::NotFound)),
1745					);
1746				}
1747			}
1748		}
1749		// What it held is the cache's again: a reader that has yet to take it asks again if
1750		// it is evicted.
1751		if !self.flight
1752			&& !self.state.read().fill_holds_as(self.id, None, &None)
1753			&& let Ok(mut state) = TrackState::modify(&self.state)
1754		{
1755			state.release_fill(self.id);
1756		}
1757		self.fills.lock().end(self.id);
1758	}
1759}
1760
1761impl TrackState {
1762	/// Record `groups` as dropped, as a fill's source answered, except what the cache holds
1763	/// or the live feed may still deliver: a fill refused is no verdict on the feed.
1764	fn drop_unfed(&mut self, groups: ops::Range<u64>, hole: super::Hole) {
1765		// Until the serving session resolves where the feed starts, it may deliver anything.
1766		if matches!(self.start, super::FeedStart::Pending(_)) {
1767			return;
1768		}
1769		let now = self.cache.pool().now_wall();
1770		let mut dropped = RangeSet::new();
1771		for hole in super::miss::holes(self, groups) {
1772			// A group lost to the cache since it arrived is the source's to name too: the live
1773			// feed delivers it no more.
1774			let unfed = self.unfed(hole, now, false);
1775			for groups in unfed.never.iter().chain(unfed.lost.iter()) {
1776				dropped.insert(groups.clone());
1777			}
1778		}
1779		for groups in dropped.iter() {
1780			self.drop_groups(groups.clone(), hole.clone());
1781		}
1782		// The runs are billed, so a source refusing fills in fragments pays for them.
1783		if !dropped.is_empty() {
1784			self.charge_debt();
1785		}
1786	}
1787}
1788
1789/// The readers of one group of a fill, outliving its [`GroupFill`].
1790#[cfg_attr(not(feature = "async"), allow(dead_code, reason = "async-only"))]
1791pub(crate) struct Readers {
1792	fills: kio::Shared<FillState>,
1793	id: u64,
1794	key: u64,
1795	outcome: kio::Producer<Outcome>,
1796}
1797
1798#[cfg_attr(not(feature = "async"), allow(dead_code, reason = "async-only"))]
1799impl Readers {
1800	/// Poll until no reader waits on the group. Once the fill ends its per-group demand goes
1801	/// with it, so then until none of its readers is left.
1802	pub(crate) fn poll_unwanted(&self, waiter: &kio::Waiter) -> Poll<()> {
1803		if self.outcome.poll_wanted_changed(waiter, true).is_ready() {
1804			return Poll::Ready(());
1805		}
1806		self.fills
1807			.poll(waiter, |fills| match fills.pending.get(&self.id) {
1808				Some(pending) if !pending.wants.contains_key(&self.key) => Poll::Ready(()),
1809				_ => Poll::Pending,
1810			})
1811			.map(drop)
1812	}
1813}
1814
1815/// One group of a [`FillGroups`], for a session serving it a group at a time. Answering it answers
1816/// that group of the fill; dropping it unanswered leaves the group to the fill.
1817#[cfg_attr(not(feature = "async"), allow(dead_code, reason = "async-only"))]
1818pub(crate) struct GroupFill {
1819	inner: Arc<SendCell<Inner>>,
1820	key: u64,
1821	frame_start: u64,
1822	frame_end: Option<u64>,
1823	priority: i8,
1824}
1825
1826#[cfg_attr(not(feature = "async"), allow(dead_code, reason = "async-only"))]
1827impl GroupFill {
1828	/// The group key to fetch.
1829	pub(crate) fn key(&self) -> u64 {
1830		self.key
1831	}
1832
1833	/// The delivery priority the readers asked for when the group was taken.
1834	pub(crate) fn priority(&self) -> i8 {
1835		self.priority
1836	}
1837
1838	/// The first frame of the group the readers want; 0 is the whole group.
1839	pub(crate) fn frame_start(&self) -> u64 {
1840		self.frame_start
1841	}
1842
1843	/// The requested exclusive last frame, if this copy is bounded at the back.
1844	pub(crate) fn frame_end(&self) -> Option<u64> {
1845		self.frame_end
1846	}
1847
1848	/// Accept the actual wire range, which an older or compressed upstream may have widened.
1849	pub(crate) fn accept_from(&self, info: Info, frames: group::Bounds) -> Result<Option<group::Producer>> {
1850		self.inner.accept_from(self.key, Some(info), frames)
1851	}
1852
1853	/// Poll until no reader waits on this group, as [`FillGroups::poll_unwanted`].
1854	pub(crate) fn poll_unwanted(&self, waiter: &kio::Waiter) -> Poll<()> {
1855		self.inner.poll_unwanted(self.key, waiter)
1856	}
1857
1858	/// Whether a reader still waits on the fill.
1859	#[cfg(test)]
1860	pub(crate) fn is_wanted(&self) -> bool {
1861		self.inner.result.wanted()
1862	}
1863
1864	/// The group's readers, for a session still writing it once accepted. Holds the fill's
1865	/// answers open, as the group does not answer its readers until they take it.
1866	pub(crate) fn readers(&self) -> Readers {
1867		Readers {
1868			fills: self.inner.fills.clone(),
1869			id: self.inner.id,
1870			key: self.key,
1871			outcome: self.inner.result.clone(),
1872		}
1873	}
1874
1875	/// Insert the group into the cache, as [`FillGroups::accept`].
1876	#[cfg(test)]
1877	pub(crate) fn accept(self, info: impl Into<Option<Info>>) -> Result<Option<group::Producer>> {
1878		self.inner.accept(self.key, info.into())
1879	}
1880
1881	/// Refuse the group with the source's answer, for the readers waiting now. Only
1882	/// [`Error::Old`] under the publisher's max age (with every older group of the fill)
1883	/// is recorded, as a stale verdict under that age.
1884	pub(crate) fn reject(self, err: Error) {
1885		self.inner.reject(self.key..self.key + 1, err);
1886	}
1887
1888	/// Declare the group never produced (SUBSCRIBE_DROP with SKIP), so waiting readers pass
1889	/// over it without recording a loss.
1890	pub(crate) fn skip(self) {
1891		let owed = self.inner.owed(self.key..self.key + 1);
1892		self.inner.drop_groups(&owed, Error::Skipped, super::Hole::Skip);
1893	}
1894}