moq_json/snapshot/producer.rs
1//! Publishing a JSON value over a track: an [`Encoder`] plus the track it writes to.
2
3use moq_net::frame::Frame;
4use std::marker::PhantomData;
5use std::ops::{Deref, DerefMut};
6use std::sync::{Arc, Mutex, MutexGuard};
7
8use serde::Serialize;
9use serde::de::DeserializeOwned;
10
11use super::{Encoded, Encoder};
12use crate::refresh::Refresh;
13
14use crate::{Error, Result};
15
16pub use super::Config;
17
18/// Take the shared publishing state, recovering if a prior guard panicked while holding it.
19///
20/// A panic under this lock is an in-flight edit being unwound. That edit is discarded (see
21/// [`Guard`]'s `Drop`) and the last value that reached the wire is still consistent, so poisoning
22/// would only turn the next `modify`/`update` into a panic during cleanup.
23fn take<T>(inner: &Mutex<Inner<T>>) -> MutexGuard<'_, Inner<T>> {
24 inner.lock().unwrap_or_else(|poisoned| poisoned.into_inner())
25}
26
27/// Publishes a JSON value over a track, choosing snapshots and deltas automatically.
28///
29/// An [`Encoder`] that owns its track: it writes each encoded frame and rolls a group whenever the
30/// encoder emits a snapshot. When something else already owns the track, use the [`Encoder`]
31/// directly.
32///
33/// A group runs until a joiner wants a fresh one, which [`poll_refresh`](Self::poll_refresh) answers, or until
34/// it reaches the encoder's caps. Set the track's [`refresh`](moq_net::track::Info::refresh) ratio
35/// when creating it, or joins never ask.
36///
37/// Set [`compression`](moq_net::track::Info::compression) on that track's info too: JSON is small and
38/// repetitive, and moq-net compresses each delta against the snapshot earlier in its group.
39///
40/// Cheaply clonable: clones share one underlying track and publishing state, like other MoQ
41/// producers.
42pub struct Producer<T> {
43 inner: Arc<Mutex<Inner<T>>>,
44 _marker: PhantomData<fn(T)>,
45}
46
47impl<T> Clone for Producer<T> {
48 fn clone(&self) -> Self {
49 Self {
50 inner: self.inner.clone(),
51 _marker: PhantomData,
52 }
53 }
54}
55
56impl<T> Producer<T> {
57 /// Create a subscriber for the underlying track.
58 pub fn consume(&self) -> moq_net::track::Subscriber {
59 take(&self.inner).track.inner.subscribe(None)
60 }
61
62 /// A watch-only handle to the underlying track's subscriber demand.
63 ///
64 /// Weak, so holding it neither keeps the track open nor contends with publishing.
65 pub fn demand(&self) -> moq_net::track::Demand {
66 take(&self.inner).track.inner.demand()
67 }
68}
69
70impl<T: Serialize> Producer<T> {
71 /// Create a producer that publishes to the given track.
72 pub fn new(track: moq_net::track::Producer, config: Config) -> Self {
73 Self {
74 inner: Arc::new(Mutex::new(Inner {
75 refresh: Refresh::new(&track),
76 track: Track {
77 inner: track,
78 group: None,
79 largest: None,
80 deltas: config.deltas,
81 },
82 encoder: Encoder::new(config),
83 at: None,
84 state: crate::state::State::Open,
85 })),
86 _marker: PhantomData,
87 }
88 }
89
90 /// Wait for a joiner to want a fresh group, then restate the current value as a snapshot in one.
91 ///
92 /// A join wants one once the open group's deltas outweigh the track's
93 /// [`refresh`](moq_net::track::Info::refresh) ratio times its snapshot (see
94 /// [`Demand::wanted`](moq_net::track::Demand::wanted)). It is a soft trigger: that joiner still
95 /// reads the cached group, then the new one. The snapshot carries the newest timestamp written,
96 /// where its group starts; while that is the newest group's own start, the refresh waits for a
97 /// later update, since two groups never share a start. Nothing happens before the first update,
98 /// or on a track without a ratio.
99 ///
100 /// The producer has no runtime of its own, so the owner drives this: loop on it, or select on it
101 /// beside the updates. Errors once the track is closed.
102 #[cfg_attr(feature = "async", kio::wrapper)]
103 pub fn poll_refresh(&self, waiter: &kio::Waiter) -> std::task::Poll<Result<()>> {
104 take(&self.inner).poll_refresh(waiter)
105 }
106
107 /// Publish a new value at `at` (see [`Timed::at`](crate::Timed::at)), emitting a snapshot or a delta automatically.
108 ///
109 /// Returns the encoded size of the frame written, or `None` if the value is unchanged from the
110 /// previous publish and nothing was written.
111 pub fn update(&mut self, value: &T, at: moq_net::Timestamp) -> Result<Option<usize>> {
112 take(&self.inner).update(value, at)
113 }
114
115 /// Edit the current value in place and publish it at `at` (see [`Timed::at`](crate::Timed::at)).
116 ///
117 /// The closure receives the current value: everything published through this producer so far,
118 /// composed, or `T::default()` if nothing has been. Edit it in place; on return the result is
119 /// published, a no-op if unchanged.
120 ///
121 /// ```no_run
122 /// # fn example(producer: &mut moq_json::snapshot::Producer<serde_json::Value>) -> moq_json::Result<()> {
123 /// producer.mutate(|catalog| {
124 /// catalog["scte35"] = serde_json::json!({ "id": 1 });
125 /// }, moq_net::Timestamp::from_millis(100).unwrap())
126 /// # }
127 /// ```
128 ///
129 /// Independent owners can share one producer and each edit only their own keys: every call starts
130 /// from the latest value, so their sections compose instead of clobbering one another. This is
131 /// [`modify`](Self::modify) opened and committed for you; take the guard to hold the lock across
132 /// several edits, and [`update`](Self::update) to replace the whole value.
133 pub fn mutate(&mut self, f: impl FnOnce(&mut T), at: moq_net::Timestamp) -> Result<()>
134 where
135 T: Default + DeserializeOwned,
136 {
137 let mut guard = self.modify(at)?;
138 f(&mut guard);
139 guard.commit()
140 }
141
142 /// Edit the current value, publishing on drop at `at` (see [`Timed::at`](crate::Timed::at)).
143 ///
144 /// The returned [`Guard`] derefs to the current value: everything published through this producer
145 /// so far, composed, or `T::default()` if nothing has been. Editing it through [`DerefMut`] marks
146 /// the guard dirty; when a dirty guard drops it publishes the result, a no-op if unchanged.
147 ///
148 /// A rejected edit never reached the wire, so the current value stays the last one that did. The
149 /// owner whose write failed sees the error and can retry; carrying the rejected edit forward would
150 /// instead fail every later owner's publish the same way, or publish a value its owner was told
151 /// failed.
152 ///
153 /// Reach for this over [`mutate`](Self::mutate) when several edits belong to one publish. The
154 /// guard holds the producer's lock for its lifetime, so independent owners are serialized: each
155 /// one starts from the latest value and their changes compose instead of clobbering. Don't hold a
156 /// guard across an `.await`, since that keeps the lock held while suspended.
157 ///
158 /// Fails if the track is closed. That is the one publication failure that happens in normal
159 /// operation, and the guard holds the lock that [`finish`](Self::finish) needs, so nothing is
160 /// left to check after the guard drops. Anything else that stops the drop from publishing (a
161 /// value that won't serialize, or one too large for a frame) aborts the track with that error:
162 /// consumers see it instead of a stale value, and the next `modify` returns it here. Call
163 /// [`Guard::commit`] to get the error back immediately instead. A panic while the guard is held
164 /// discards the in-flight edit rather than publishing a torn value.
165 pub fn modify(&mut self, at: moq_net::Timestamp) -> Result<Guard<'_, T>>
166 where
167 T: Default + DeserializeOwned,
168 {
169 let inner = take(&self.inner);
170 inner.open()?;
171
172 // A published value that does not deserialize as `T` is a bug in the caller, not a reason
173 // to start over: seeding `T::default()` here would publish a value with every other field
174 // dropped, the clobber this guard exists to prevent.
175 let value = match inner.encoder.value() {
176 Some(last) => serde_json::from_value(last.clone())?,
177 None => T::default(),
178 };
179
180 Ok(Guard {
181 inner,
182 value,
183 dirty: false,
184 at,
185 })
186 }
187
188 /// Close the open group, so the deltas already written stop being provisional.
189 ///
190 /// No replacement group opens until the next [`update`](Self::update) or [`poll_refresh`](Self::poll_refresh), which emits a full
191 /// snapshot as its first frame even when the value is unchanged. A consumer joining at that group
192 /// therefore reads the whole value without the deltas that preceded it.
193 ///
194 /// Idempotent: cutting when no group is open does nothing, so a caller can cut on its own
195 /// schedule without tracking what has been published since the last one. Inert when deltas are
196 /// disabled, where every frame already gets its own group.
197 pub fn cut(&mut self) -> Result<()> {
198 take(&self.inner).cut()
199 }
200
201 /// Finish the track, closing any open group, and return the [`Finished`] value.
202 ///
203 /// Clones sharing the track see it ended: their next [`modify`](Self::modify) or
204 /// [`update`](Self::update) fails. A finish that fails aborts the track with the cause, which
205 /// those clones then report.
206 pub fn finish(self) -> Result<Finished<T>> {
207 take(&self.inner).finish()?;
208 Ok(Finished {
209 inner: self.inner,
210 _marker: PhantomData,
211 })
212 }
213
214 /// Abort the track with the given error, which consumers see in place of any further value.
215 ///
216 /// Consumes the handle, since nothing can be published afterwards. Clones sharing the track see
217 /// it closed: their next [`modify`](Self::modify) or [`update`](Self::update) fails.
218 pub fn abort(self, err: moq_net::Error) -> Result<()> {
219 let mut inner = take(&self.inner);
220 inner.abort(err.into());
221 Ok(())
222 }
223}
224
225/// A value whose producer [finished](Producer::finish) it: it can still be read or aborted, but
226/// not published to.
227///
228/// Dropping the last handle sharing the track releases it, so new readers can no longer find it.
229///
230/// ```compile_fail,E0599
231/// # fn cannot_update(value: moq_json::snapshot::Finished<u32>) {
232/// value.update(&1, moq_net::Timestamp::unscaled(0)).unwrap();
233/// # }
234/// ```
235#[must_use = "dropping the last handle releases the track, which new readers can then no longer find"]
236pub struct Finished<T> {
237 inner: Arc<Mutex<Inner<T>>>,
238 _marker: PhantomData<fn(T)>,
239}
240
241impl<T> Finished<T> {
242 /// Create a subscriber for the underlying track.
243 pub fn consume(&self) -> moq_net::track::Subscriber {
244 take(&self.inner).track.inner.subscribe(None)
245 }
246
247 /// A watch-only handle to the underlying track's subscriber demand.
248 pub fn demand(&self) -> moq_net::track::Demand {
249 take(&self.inner).track.inner.demand()
250 }
251
252 /// Abort the track with `err`; see [`moq_net::track::Finished::abort`]. Readers still draining
253 /// get the clean end instead once every group below the end finished.
254 pub fn abort(self, err: moq_net::Error) -> Result<()> {
255 take(&self.inner).abort(err.into());
256 Ok(())
257 }
258}
259
260/// An RAII editing guard returned by [`Producer::modify`].
261///
262/// Holds the producer's lock for its lifetime and derefs to the current value. Mutating it through
263/// [`DerefMut`] marks it dirty, and dropping a dirty guard publishes the edited value.
264///
265/// Publishing on drop cannot return an error, so a failure aborts the track instead: consumers see
266/// the error and the next [`Producer::modify`] returns it. Call [`commit`](Self::commit) when the
267/// caller can act on the failure itself. A panic while the guard is held skips publication, so a
268/// torn edit is discarded instead of reaching the wire.
269pub struct Guard<'a, T: Serialize> {
270 inner: MutexGuard<'a, Inner<T>>,
271 value: T,
272 dirty: bool,
273 at: moq_net::Timestamp,
274}
275
276impl<T: Serialize> Guard<'_, T> {
277 /// Publish the edited value, returning any error.
278 ///
279 /// Consumes the guard, so the subsequent drop publishes nothing. A no-op if the value was never
280 /// mutated. Unlike a drop, a failure here leaves the track open: the caller has the error and
281 /// decides what to do with it.
282 pub fn commit(mut self) -> Result<()> {
283 self.publish()
284 }
285
286 /// Publish a dirty value once, clearing the dirty flag so it isn't published again.
287 fn publish(&mut self) -> Result<()> {
288 if !self.dirty {
289 return Ok(());
290 }
291 self.dirty = false;
292
293 // We already hold the lock, so publish through the held guard rather than re-locking.
294 self.inner.update(&self.value, self.at)?;
295 Ok(())
296 }
297}
298
299impl<T: Serialize> Deref for Guard<'_, T> {
300 type Target = T;
301
302 fn deref(&self) -> &T {
303 &self.value
304 }
305}
306
307impl<T: Serialize> DerefMut for Guard<'_, T> {
308 fn deref_mut(&mut self) -> &mut T {
309 self.dirty = true;
310 &mut self.value
311 }
312}
313
314impl<T: Serialize> Drop for Guard<'_, T> {
315 fn drop(&mut self) {
316 if std::thread::panicking() {
317 // The in-flight copy may be torn; keep the last value that reached the wire.
318 return;
319 }
320 if let Err(err) = self.publish() {
321 tracing::error!(%err, "failed to publish JSON value on guard drop, aborting the track");
322 self.inner.abort(err);
323 }
324 }
325}
326
327/// Shared publishing state behind [`Producer`]'s `Arc<Mutex>`.
328///
329/// The track and the encoder are separate fields so a [`Pending`](super::Pending) frame (which
330/// borrows the encoder) and the write that consumes it (which borrows the track) don't contend for
331/// one `&mut self`.
332struct Inner<T> {
333 track: Track,
334 encoder: Encoder<T>,
335
336 /// Watches for a joiner wanting a group past the largest written.
337 refresh: Refresh,
338
339 /// The newest timestamp written, which a refresh restates the value at. A group's timestamps
340 /// never decrease, so a later write may not go below it, nor a new group start before it.
341 /// `None` before the first write.
342 at: Option<moq_net::Timestamp>,
343
344 /// Whether this producer still publishes, or how it ended the track.
345 state: crate::state::State,
346}
347
348impl<T> Inner<T> {
349 /// Refuse further edits once the track can't take another group.
350 fn open(&self) -> Result<()> {
351 self.state.check()?;
352
353 // The same test `append_group` applies: a boundary declared ahead of the live edge still
354 // admits the groups below it. The largest counts every group, even an empty one, so the
355 // next group is the one after it.
356 let track = &self.track.inner;
357 let next = track.largest().map_or(0, |largest| largest.group.saturating_add(1));
358 if track.is_closed()
359 || track
360 .finished()
361 .is_some_and(|end| moq_net::track::Position::group(next) >= end)
362 {
363 return Err(moq_net::Error::Closed.into());
364 }
365 Ok(())
366 }
367
368 /// Abort the track with a publication failure nobody could return.
369 fn abort(&mut self, err: Error) {
370 // The track carries a moq-net error; anything else (a value that won't serialize) has no
371 // wire code, so consumers get a generic failure while the exact cause stays here.
372 let reason = match &err {
373 Error::Net(err) => err.clone(),
374 _ => moq_net::StreamError::Internal.into(),
375 };
376 self.encoder.reset();
377 self.track.group = None;
378 // Idempotent: a track that is already closed keeps its first reason.
379 let _ = self.track.inner.clone().abort(reason);
380 self.state.abort(err);
381 self.refresh.ended();
382 }
383
384 /// Close the open group, leaving the next update to open a replacement with a full snapshot.
385 fn cut(&mut self) -> Result<()> {
386 if self.track.group.is_none() {
387 return Ok(());
388 }
389
390 // The group closes either way below, so reset first: a `close` error must not leave the
391 // encoder emitting deltas against a snapshot whose group is gone.
392 self.encoder.reset();
393 self.track.cut()
394 }
395}
396
397impl<T: Serialize> Inner<T> {
398 fn update(&mut self, value: &T, at: moq_net::Timestamp) -> Result<Option<usize>> {
399 self.open()?;
400 let timestamp = self.track.rescale(at)?;
401 // Split the borrow so `frame` can hold the encoder while `track` is written through.
402 let Inner { track, encoder, .. } = self;
403
404 let Some(frame) = encoder.update(value)? else {
405 return Ok(None);
406 };
407
408 // A failed write drops `frame` uncommitted, which resets the encoder so the next update
409 // resynchronizes with a fresh snapshot. Most failures kill the track outright, but a rejected
410 // frame (too large) doesn't, and a delta against a snapshot no consumer ever saw is unreadable.
411 // The value stays the last one written, so a refresh restates that rather than the rejection.
412 track.write(timestamp, &frame)?;
413 let size = frame.payload.len();
414 frame.commit();
415 if self.at.is_none_or(|newest| timestamp > newest) {
416 self.at = Some(timestamp);
417 self.refresh.advanced();
418 }
419
420 Ok(Some(size))
421 }
422
423 fn poll_refresh(&mut self, waiter: &kio::Waiter) -> std::task::Poll<Result<()>> {
424 // A finished track still has subscribers draining it, so its demand alone never says stop.
425 self.open()?;
426 std::task::ready!(self.refresh.poll(self.track.largest, waiter))?;
427
428 let Inner {
429 track,
430 encoder,
431 at,
432 refresh,
433 ..
434 } = self;
435 // Two groups never share a start, so a refresh at the newest group's own start waits for a
436 // later write. Checked before encoding, since a snapshot dropped unwritten resets the encoder.
437 let Some(at) = *at else {
438 return refresh.park(waiter);
439 };
440 if !crate::starts_past(&track.inner, at) {
441 return refresh.park(waiter);
442 }
443 // A group was written, so a value was encoded and there is one to restate.
444 let Some(frame) = encoder.snapshot()? else {
445 return std::task::Poll::Pending;
446 };
447 track.write(at, &frame)?;
448 frame.commit();
449 std::task::Poll::Ready(Ok(()))
450 }
451
452 fn finish(&mut self) -> Result<()> {
453 match &self.state {
454 crate::state::State::Open => {}
455 crate::state::State::Finished => return Ok(()),
456 crate::state::State::Aborted(err) => return Err(err.clone()),
457 }
458 // The open group goes with the track, so the encoder must not keep emitting deltas into it.
459 // Any further update fails on the closed track, but it has to fail as an error rather than by
460 // writing a delta with no group to hold it.
461 self.encoder.reset();
462 if let Err(err) = self.track.finish() {
463 // Half-finished, the track could still take groups, so it ends with the cause instead.
464 self.abort(err.clone());
465 return Err(err);
466 }
467 self.state = crate::state::State::Finished;
468 self.refresh.ended();
469 Ok(())
470 }
471}
472
473/// The track half of [`Inner`]: where an encoded frame goes and how groups are rolled.
474struct Track {
475 inner: moq_net::track::Producer,
476
477 /// The group a delta would be appended to, open only while deltas are enabled.
478 group: Option<moq_net::group::Producer>,
479
480 /// The start of the newest group written, which a refresh has to pass.
481 largest: Option<u64>,
482
483 /// Whether the encoder can emit deltas at all. With them off every frame is a snapshot, so a
484 /// group is closed the moment it's written and never held open.
485 deltas: bool,
486}
487
488impl Track {
489 /// Close the open group without opening a replacement.
490 fn cut(&mut self) -> Result<()> {
491 if let Some(group) = self.group.take() {
492 group.finish()?;
493 }
494 Ok(())
495 }
496
497 /// `timestamp` at the track's timescale, or [`moq_net::Error::TimestampMismatch`] when it is
498 /// unscaled on a timed track, scaled on a scale-less one, or beyond what the scale can hold.
499 ///
500 /// An update checks this before encoding. Found by `write_frame` instead, the mismatch would
501 /// come after a snapshot published its group, leaving an empty newest group in place of the
502 /// last value, and the dropped frame would reset the encoder, rolling a group for nothing.
503 fn rescale(&self, timestamp: moq_net::Timestamp) -> Result<moq_net::Timestamp> {
504 Ok(self.inner.info().rescale(timestamp)?)
505 }
506
507 /// Write one encoded frame at a timestamp already [rescaled](Self::rescale) to the track, rolling a
508 /// group when it's a snapshot.
509 fn write(&mut self, timestamp: moq_net::Timestamp, encoded: &Encoded) -> Result<()> {
510 // Check before touching a group. `write_snapshot` closes the previous group and publishes a
511 // new one before the frame is written, so discovering the limit inside `write_frame` would
512 // leave an empty newest group behind: a snapshot consumer jumps to the newest, so the previous
513 // value would be lost even though this update reported an error.
514 if encoded.payload.len() as u64 > crate::MAX_GROUP_BYTES {
515 return Err(moq_net::Error::FrameTooLarge.into());
516 }
517
518 match encoded.keyframe {
519 true => self.write_snapshot(timestamp, encoded.payload.clone()),
520 false => self.write_delta(timestamp, encoded.payload.clone()),
521 }
522 }
523
524 /// Write a snapshot as the first frame of a new group starting at `timestamp`, then close the
525 /// previous group.
526 ///
527 /// A start at or before the newest group's is [`moq_net::Error::TimestampMismatch`], and a
528 /// frame too large [`moq_net::Error::FrameTooLarge`]: both are refused before the previous
529 /// group closes, leaving no group behind.
530 fn write_snapshot(&mut self, timestamp: moq_net::Timestamp, payload: bytes::Bytes) -> Result<()> {
531 let group = self.inner.append_group(Frame::new(timestamp, payload))?;
532 self.largest = Some(group.start);
533
534 // The previous group is complete; no more frames will be appended to it. One that can't
535 // close (already aborted) fails the write, taking the group just published with it rather
536 // than leaving it to drop as `Dropped`.
537 if let Some(previous) = self.group.take()
538 && let Err(err) = previous.finish()
539 {
540 let _ = group.abort(err.clone());
541 return Err(err.into());
542 }
543
544 match self.deltas {
545 // Keep the group open so future deltas can be appended to it.
546 true => self.group = Some(group),
547 // One frame per group, identical to a plain JSON track.
548 false => drop(group.finish()?),
549 }
550
551 Ok(())
552 }
553
554 /// Append a delta to the group the last snapshot opened.
555 fn write_delta(&mut self, timestamp: moq_net::Timestamp, payload: bytes::Bytes) -> Result<()> {
556 let group = self
557 .group
558 .as_mut()
559 .expect("the encoder only emits a delta after a snapshot opened a group");
560 group.write_frame(Frame::new(crate::frame_time(group, timestamp), payload))?;
561 Ok(())
562 }
563
564 fn finish(&mut self) -> Result<()> {
565 if let Some(group) = self.group.take() {
566 group.finish()?;
567 }
568 // Another handle may have declared the end already, which stands. This shared state
569 // keeps its own clone, whose appends the end refuses.
570 if self.inner.finished().is_none() {
571 drop(self.inner.clone().finish()?);
572 }
573 Ok(())
574 }
575}
576
577#[cfg(test)]
578mod tests {
579 use std::task::Poll;
580
581 use serde_json::{Value, json};
582
583 use super::*;
584
585 /// A previous group already aborted fails the next snapshot, which aborts the group it just
586 /// published with the same error rather than dropping it as `Dropped`.
587 #[test]
588 fn a_previous_group_that_cannot_close_aborts_the_next() {
589 let track = moq_net::broadcast::Info::new()
590 .produce()
591 .create_track("test", moq_net::track::Info::default())
592 .unwrap();
593 // Oldest first, as published.
594 let mut groups = track.subscribe(
595 moq_net::track::Subscription::default()
596 .with_ranges([moq_net::track::Range::default().with_order(moq_net::track::Order::Ascending)]),
597 );
598 let mut producer = Producer::<Value>::new(track, Config::default().with_deltas(true));
599 producer
600 .update(&json!({ "n": 1 }), moq_net::Timestamp::unscaled(1))
601 .unwrap();
602
603 let mut inner = producer.inner.lock().unwrap();
604 // Swap in a group its own track's abort already failed, keeping the handle.
605 let other = moq_net::broadcast::Info::new()
606 .produce()
607 .create_track("other", moq_net::track::Info::default())
608 .unwrap();
609 let aborted = other
610 .append_group(Frame::new(moq_net::Timestamp::unscaled(1), b"{}".as_slice()))
611 .unwrap();
612 other.abort(moq_net::Error::GroupTooLarge).unwrap();
613 let open = inner.track.group.replace(aborted).expect("an open group");
614 let _finished = open.finish().unwrap();
615 let err = inner
616 .track
617 .write_snapshot(moq_net::Timestamp::unscaled(2), bytes::Bytes::from_static(b"{}"))
618 .unwrap_err();
619 assert!(matches!(err, crate::Error::Net(moq_net::Error::GroupTooLarge)), "{err}");
620 assert!(inner.track.group.is_none());
621 drop(inner);
622
623 let waiter = kio::Waiter::noop();
624 let mut read = 0;
625 while let Poll::Ready(Ok(Some(mut group))) = groups.poll_recv_group(&waiter) {
626 let ended = loop {
627 match group.poll_read_frame(&waiter) {
628 Poll::Ready(Ok(Some(_))) => continue,
629 other => break other,
630 }
631 };
632 read += 1;
633 // The first group finished; the one the failed write published carries the abort.
634 match read {
635 1 => assert!(matches!(ended, Poll::Ready(Ok(None))), "{ended:?}"),
636 _ => assert!(
637 matches!(ended, Poll::Ready(Err(moq_net::Error::GroupTooLarge))),
638 "{ended:?}"
639 ),
640 }
641 }
642 assert_eq!(read, 2);
643 }
644}