1use std::{
37 collections::VecDeque,
38 sync::Arc,
39 task::{Poll, ready},
40};
41
42use bytes::Bytes;
43
44use crate::{Error, Result, Timescale, Timestamp, broadcast, stats};
45
46pub(crate) const MAX_PAYLOAD: usize = u16::MAX as usize;
53
54const MAX_BUFFERED: usize = 64;
59
60const MAX_BUFFERED_BYTES: usize = 64 * 1024;
64
65const DEFAULT_PRIORITY: i8 = 0;
67
68#[derive(Clone, Debug, PartialEq, Eq)]
70pub struct Datagram {
71 pub sequence: u64,
73 pub timestamp: Timestamp,
76 pub payload: Bytes,
78}
79
80#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
82#[non_exhaustive]
83pub struct Info {
84 pub timescale: Option<Timescale>,
89 pub priority: i8,
92}
93
94impl Info {
95 pub fn with_timescale(mut self, timescale: impl Into<Option<Timescale>>) -> Self {
97 self.timescale = timescale.into();
98 self
99 }
100
101 pub fn with_priority(mut self, priority: i8) -> Self {
103 self.priority = priority;
104 self
105 }
106
107 pub fn rescale(&self, timestamp: Timestamp) -> Result<Timestamp> {
114 match (timestamp.scale(), self.timescale) {
115 (Some(_), Some(timescale)) => timestamp.convert(timescale).map_err(|_| Error::TimestampMismatch),
116 (None, None) => Ok(timestamp),
117 _ => Err(Error::TimestampMismatch),
118 }
119 }
120
121 #[cfg(test)]
123 pub(crate) fn produce(self, name: impl Into<Arc<str>>) -> Producer {
124 Producer::new(name.into(), Some(self))
125 }
126}
127
128#[derive(Default)]
129struct State {
130 info: Option<Info>,
132 buffer: VecDeque<Datagram>,
133 bytes: usize,
135 offset: u64,
137 next: Option<u64>,
140 end: Option<Result<()>>,
142 producers: usize,
144 priorities: slab::Slab<Option<i8>>,
146 listed: Option<broadcast::Unlist>,
148}
149
150impl State {
151 fn closed(&self) -> Result<()> {
152 match &self.end {
153 None => Ok(()),
154 Some(Ok(())) => Err(Error::Closed),
155 Some(Err(err)) => Err(err.clone()),
156 }
157 }
158
159 fn push(&mut self, datagram: Datagram) {
160 self.bytes += datagram.payload.len();
161 while self.buffer.len() >= MAX_BUFFERED || (!self.buffer.is_empty() && self.bytes > MAX_BUFFERED_BYTES) {
162 let dropped = self.buffer.pop_front().expect("not empty");
163 self.bytes -= dropped.payload.len();
164 self.offset += 1;
165 }
166 self.next = match (self.next, datagram.sequence.checked_add(1)) {
167 (Some(next), Some(after)) => Some(next.max(after)),
168 _ => None,
169 };
170 self.buffer.push_back(datagram);
171 }
172
173 #[must_use = "drop the listing after releasing the lock"]
176 fn end(&mut self, end: Result<()>) -> Option<broadcast::Unlist> {
177 if self.end.is_some() {
178 return None;
179 }
180 let finished = end.is_ok();
181 let unread = end.is_err() || self.priorities.is_empty();
184 self.end = Some(end);
185 if unread {
186 self.release();
187 }
188 self.listed.take().map(|listed| listed.finished(finished))
189 }
190
191 fn release(&mut self) {
194 self.offset += self.buffer.len() as u64;
195 self.buffer.clear();
196 self.bytes = 0;
197 }
198
199 fn has_next(&self, cursor: u64) -> bool {
202 !self.buffer.is_empty() && self.offset + (self.buffer.len() as u64) > cursor
203 }
204
205 fn priority(&self) -> Option<i8> {
206 self.priorities.iter().filter_map(|(_, priority)| *priority).max()
207 }
208}
209
210#[derive(Clone)]
212pub(super) struct Weak {
213 name: Arc<str>,
214 state: kio::Shared<State>,
215}
216
217impl Weak {
218 pub(super) fn try_consume(&self, stats: stats::Scope) -> Option<Consumer> {
220 Consumer::join(self.name.clone(), &self.state, stats, Some(DEFAULT_PRIORITY))
221 }
222
223 pub(super) fn observe(&self, stats: stats::Scope) -> Option<Consumer> {
225 Consumer::join(self.name.clone(), &self.state, stats, None)
226 }
227}
228
229impl super::WeakEntry for Weak {
230 fn is_closed(&self) -> bool {
231 self.state.read().end.is_some()
232 }
233
234 fn same_channel(&self, other: &Self) -> bool {
235 self.state.is_clone(&other.state)
236 }
237}
238
239pub struct Producer {
245 name: Arc<str>,
246 info: Info,
247 state: kio::Shared<State>,
248 stats: stats::Scope,
249 prev: Option<Option<i8>>,
251}
252
253impl Producer {
254 pub(super) fn new(name: Arc<str>, info: Option<Info>) -> Self {
255 let state = State {
256 info,
257 next: Some(0),
258 producers: 1,
259 ..Default::default()
260 };
261 Self {
262 name,
263 info: info.unwrap_or_default(),
264 state: kio::Shared::new(state),
265 stats: stats::Scope::default(),
266 prev: None,
267 }
268 }
269
270 pub(super) fn with_stats(mut self, scope: stats::Scope) -> Self {
271 self.stats = scope;
272 self
273 }
274
275 pub(super) fn listed(self, unlist: broadcast::Unlist) -> Self {
277 self.state.lock().listed = Some(unlist);
278 self
279 }
280
281 pub(super) fn weak(&self) -> Weak {
282 Weak {
283 name: self.name.clone(),
284 state: self.state.clone(),
285 }
286 }
287
288 pub fn name(&self) -> &str {
290 &self.name
291 }
292
293 pub fn info(&self) -> &Info {
295 &self.info
296 }
297
298 pub fn append<B: crate::IntoBytes>(&mut self, timestamp: Timestamp, payload: B) -> Result<u64> {
305 let mut state = self.state.lock();
306 let sequence = match timestamp.scale() {
307 Some(_) => state.next.ok_or(crate::coding::BoundsExceeded)?,
308 None => timestamp.value(),
309 };
310 self.push(
311 &mut state,
312 Datagram {
313 sequence,
314 timestamp,
315 payload: payload.into_bytes(),
316 },
317 )?;
318 Ok(sequence)
319 }
320
321 pub fn insert(&mut self, datagram: Datagram) -> Result<()> {
326 let mut state = self.state.lock();
327 self.push(&mut state, datagram)
328 }
329
330 fn push(&self, state: &mut State, mut datagram: Datagram) -> Result<()> {
331 if datagram.payload.len() > MAX_PAYLOAD {
332 return Err(Error::FrameTooLarge);
333 }
334 state.closed()?;
335 datagram.timestamp = self.info.rescale(datagram.timestamp)?;
336 if datagram.timestamp.scale().is_none() && datagram.timestamp.value() != datagram.sequence {
338 return Err(Error::TimestampMismatch);
339 }
340 self.stats.meter().datagram(datagram.payload.len() as u64);
341 state.push(datagram);
342 Ok(())
343 }
344
345 pub fn consume(&self) -> Consumer {
347 Consumer::join(
348 self.name.clone(),
349 &self.state,
350 stats::Scope::default(),
351 Some(DEFAULT_PRIORITY),
352 )
353 .unwrap_or_else(|| Consumer::ended(self.name.clone(), &self.state))
354 }
355
356 pub fn finish(self) {
358 let unlist = self.state.lock().end(Ok(()));
359 drop(unlist);
360 }
361
362 pub fn abort(self, err: Error) {
364 let unlist = self.state.lock().end(Err(err));
365 drop(unlist);
366 }
367
368 pub fn priority(&self) -> Option<i8> {
370 self.state.read().priority()
371 }
372
373 #[cfg_attr(feature = "async", kio::wrapper)]
376 pub fn poll_priority_changed(&mut self, waiter: &kio::Waiter) -> Poll<Option<i8>> {
377 let priority = match self.prev {
378 None => self.priority(),
379 Some(last) => ready!(self.poll_priority(waiter, last)),
380 };
381 self.prev = Some(priority);
382 Poll::Ready(priority)
383 }
384
385 #[cfg_attr(not(feature = "async"), allow(dead_code, reason = "async-only"))]
387 pub(crate) fn poll_priority(&self, waiter: &kio::Waiter, last: Option<i8>) -> Poll<Option<i8>> {
388 let state = ready!(self.state.poll(waiter, |state| match state.priority() == last {
389 true => Poll::Pending,
390 false => Poll::Ready(()),
391 }));
392 Poll::Ready(state.priority())
393 }
394
395 #[cfg_attr(not(feature = "async"), allow(dead_code, reason = "async-only"))]
397 pub(crate) fn poll_unused(&self, waiter: &kio::Waiter) -> Poll<()> {
398 let _state = ready!(self.state.poll(waiter, |state| match state.priorities.is_empty() {
399 true => Poll::Ready(()),
400 false => Poll::Pending,
401 }));
402 Poll::Ready(())
403 }
404
405 #[cfg_attr(not(feature = "async"), allow(dead_code, reason = "async-only"))]
411 pub(crate) fn close_unused(&self) -> bool {
412 let mut state = self.state.lock();
413 if !state.priorities.is_empty() {
414 return false;
415 }
416 let unlist = state.end(Err(Error::Cancel));
417 drop(state);
418 drop(unlist);
419 true
420 }
421
422 #[cfg_attr(not(feature = "async"), allow(dead_code, reason = "async-only"))]
424 pub(crate) fn is_clone(&self, other: &Self) -> bool {
425 self.state.is_clone(&other.state)
426 }
427}
428
429impl Clone for Producer {
430 fn clone(&self) -> Self {
431 self.state.lock().producers += 1;
432 Self {
433 name: self.name.clone(),
434 info: self.info,
435 state: self.state.clone(),
436 stats: self.stats.clone(),
437 prev: None,
438 }
439 }
440}
441
442impl Drop for Producer {
443 fn drop(&mut self) {
444 let mut state = self.state.lock();
445 state.producers -= 1;
446 if state.producers == 0 {
447 let unlist = state.end(Err(Error::Dropped));
448 drop(state);
449 drop(unlist);
450 }
451 }
452}
453
454pub struct Request {
460 producer: Producer,
461}
462
463impl Request {
464 pub(super) fn new(name: Arc<str>) -> Self {
465 Self {
466 producer: Producer::new(name, None),
467 }
468 }
469
470 pub(super) fn with_stats(mut self, scope: stats::Scope) -> Self {
471 self.producer = self.producer.with_stats(scope);
472 self
473 }
474
475 pub(super) fn weak(&self) -> Weak {
476 self.producer.weak()
477 }
478
479 pub fn name(&self) -> &str {
481 self.producer.name()
482 }
483
484 pub(super) fn is_closed(&self) -> bool {
486 self.producer.state.read().end.is_some()
487 }
488
489 pub fn priority(&self) -> Option<i8> {
491 self.producer.priority()
492 }
493
494 #[cfg_attr(not(feature = "async"), allow(dead_code, reason = "async-only"))]
496 pub(crate) fn poll_unused(&self, waiter: &kio::Waiter) -> Poll<()> {
497 self.producer.poll_unused(waiter)
498 }
499
500 #[cfg_attr(not(feature = "async"), allow(dead_code, reason = "async-only"))]
502 pub(crate) fn close_unused(&self) -> bool {
503 self.producer.close_unused()
504 }
505
506 pub fn accept(self, info: Info) -> Producer {
508 let mut producer = self.producer;
509 producer.state.lock().info = Some(info);
510 producer.info = info;
511 producer
512 }
513
514 pub fn reject(self, err: Error) {
516 self.producer.abort(err);
517 }
518}
519
520pub struct Consumer {
525 name: Arc<str>,
526 state: kio::Shared<State>,
527 slot: Option<usize>,
529 cursor: u64,
531 stats: stats::Scope,
532 delegated: bool,
534}
535
536impl Consumer {
537 fn join(name: Arc<str>, state: &kio::Shared<State>, stats: stats::Scope, priority: Option<i8>) -> Option<Self> {
539 let mut guard = state.lock();
540 if guard.end.is_some() {
541 return None;
542 }
543 let slot = guard.priorities.insert(priority);
544 let cursor = guard.offset + guard.buffer.len() as u64;
545 drop(guard);
546 Some(Self {
547 name,
548 state: state.clone(),
549 slot: Some(slot),
550 cursor,
551 stats,
552 delegated: false,
553 })
554 }
555
556 fn ended(name: Arc<str>, state: &kio::Shared<State>) -> Self {
557 let cursor = {
559 let state = state.read();
560 state.offset + state.buffer.len() as u64
561 };
562 Self {
563 name,
564 state: state.clone(),
565 slot: None,
566 cursor,
567 stats: stats::Scope::default(),
568 delegated: false,
569 }
570 }
571
572 #[cfg_attr(not(feature = "async"), allow(dead_code, reason = "async-only"))]
575 pub(crate) fn delegate(&mut self) -> stats::Scope {
576 self.delegated = true;
577 self.stats.clone()
578 }
579
580 pub(super) fn with_stats(mut self, scope: stats::Scope) -> Self {
581 self.stats = scope;
582 self
583 }
584
585 pub fn name(&self) -> &str {
587 &self.name
588 }
589
590 #[cfg_attr(feature = "async", kio::wrapper)]
592 pub fn poll_info(&self, waiter: &kio::Waiter) -> Poll<Result<Info>> {
593 let state = ready!(
594 self.state
595 .poll(waiter, |state| match state.info.is_some() || state.end.is_some() {
596 true => Poll::Ready(()),
597 false => Poll::Pending,
598 })
599 );
600 match (state.info, &state.end) {
601 (Some(info), _) => Poll::Ready(Ok(info)),
602 (None, Some(Err(err))) => Poll::Ready(Err(err.clone())),
603 (None, _) => Poll::Ready(Err(Error::Closed)),
604 }
605 }
606
607 #[cfg_attr(feature = "async", kio::wrapper)]
612 pub fn poll_recv(&mut self, waiter: &kio::Waiter) -> Poll<Result<Option<Datagram>>> {
613 let cursor = self.cursor;
614 let state = ready!(self.state.poll(waiter, |state| {
615 match state.end.is_some() || state.has_next(cursor) {
616 true => Poll::Ready(()),
617 false => Poll::Pending,
618 }
619 }));
620 if !state.has_next(cursor) {
622 let end = state.end.clone().expect("ready only once ended or buffered");
623 return Poll::Ready(end.map(|()| None));
624 }
625 let index = self.cursor.max(state.offset);
626 let datagram = state.buffer[(index - state.offset) as usize].clone();
627 drop(state);
628 self.cursor = index + 1;
629 if !self.delegated {
630 self.stats.meter().datagram(datagram.payload.len() as u64);
631 }
632 Poll::Ready(Ok(Some(datagram)))
633 }
634
635 pub fn priority(&self) -> i8 {
637 self.slot
638 .and_then(|slot| self.state.read().priorities.get(slot).copied().flatten())
639 .unwrap_or(DEFAULT_PRIORITY)
640 }
641
642 pub fn set_priority(&mut self, priority: i8) {
644 if let Some(slot) = self.slot {
645 self.state.lock().priorities[slot] = Some(priority);
646 }
647 }
648
649 #[cfg_attr(not(feature = "async"), allow(dead_code, reason = "async-only"))]
651 pub(crate) fn observe(&self) -> Self {
652 let slot = self.slot.map(|_| self.state.lock().priorities.insert(None));
653 Self {
654 name: self.name.clone(),
655 state: self.state.clone(),
656 slot,
657 cursor: self.cursor,
658 stats: self.stats.clone(),
659 delegated: false,
660 }
661 }
662
663 #[cfg_attr(not(feature = "async"), allow(dead_code, reason = "async-only"))]
665 pub(crate) fn is_clone(&self, other: &Self) -> bool {
666 self.state.is_clone(&other.state)
667 }
668}
669
670impl Clone for Consumer {
671 fn clone(&self) -> Self {
672 let slot = self.slot.map(|slot| {
673 let mut state = self.state.lock();
674 let priority = state.priorities[slot];
675 state.priorities.insert(priority)
676 });
677 Self {
678 name: self.name.clone(),
679 state: self.state.clone(),
680 slot,
681 cursor: self.cursor,
682 stats: self.stats.clone(),
683 delegated: self.delegated,
684 }
685 }
686}
687
688impl Drop for Consumer {
689 fn drop(&mut self) {
690 if let Some(slot) = self.slot {
691 let mut state = self.state.lock();
692 state.priorities.remove(slot);
693 if state.priorities.is_empty() && state.info.is_none() {
696 let unlisted = state.end(Err(Error::Cancel));
697 debug_assert!(
698 unlisted.is_none(),
699 "only a created track is listed, and it has its info"
700 );
701 }
702 if state.priorities.is_empty() && state.end.is_some() {
704 state.release();
705 }
706 }
707 }
708}
709
710#[cfg(test)]
711mod tests {
712 use super::*;
713
714 fn recv(consumer: &mut Consumer) -> Poll<Result<Option<Datagram>>> {
715 consumer.poll_recv(&kio::Waiter::noop())
716 }
717
718 fn seq(sequence: u64) -> Timestamp {
720 Timestamp::unscaled(sequence)
721 }
722
723 fn ms(millis: u64) -> Timestamp {
724 Timestamp::from_millis(millis).unwrap()
725 }
726
727 fn sequence(consumer: &mut Consumer) -> u64 {
728 match recv(consumer) {
729 Poll::Ready(Ok(Some(datagram))) => datagram.sequence,
730 other => panic!("expected a datagram, got {other:?}"),
731 }
732 }
733
734 #[test]
735 fn passive_forwarding_keeps_the_tail_without_adding_demand() {
736 let mut producer = Info::default().produce("audio");
737 let mut observer = producer.weak().observe(stats::Scope::default()).unwrap();
738 let mut copy = observer.clone();
739 assert_eq!(producer.priority(), None);
740 let mut reader = producer.consume();
741 reader.set_priority(-7);
742 assert_eq!(producer.priority(), Some(-7));
743 drop(reader);
744 assert_eq!(producer.priority(), None);
745 producer.append(seq(0), &b"tail"[..]).unwrap();
746 producer.finish();
747 for consumer in [&mut observer, &mut copy] {
748 let Poll::Ready(Ok(Some(datagram))) = consumer.poll_recv(&kio::Waiter::noop()) else {
749 panic!("tail lost");
750 };
751 assert_eq!(datagram.payload.as_ref(), b"tail");
752 assert!(matches!(
753 consumer.poll_recv(&kio::Waiter::noop()),
754 Poll::Ready(Ok(None))
755 ));
756 }
757 }
758
759 #[test]
760 fn append_counts_its_own_sequence_past_inserts() {
761 let mut producer = Info::default().with_timescale(Timescale::MILLI).produce("dg");
762 let mut consumer = producer.consume();
763 assert_eq!(producer.append(ms(0), "a").unwrap(), 0);
764 producer
765 .insert(Datagram {
766 sequence: 10,
767 timestamp: ms(10),
768 payload: Bytes::from_static(b"b"),
769 })
770 .unwrap();
771 producer
773 .insert(Datagram {
774 sequence: 3,
775 timestamp: ms(3),
776 payload: Bytes::from_static(b"c"),
777 })
778 .unwrap();
779 assert_eq!(producer.append(ms(11), "d").unwrap(), 11);
780 let got: Vec<u64> = (0..4).map(|_| sequence(&mut consumer)).collect();
781 assert_eq!(got, [0, 10, 3, 11]);
782 assert!(recv(&mut consumer).is_pending());
783 }
784
785 #[test]
787 fn append_refuses_once_the_sequence_is_spent() {
788 let mut producer = Info::default().with_timescale(Timescale::MILLI).produce("dg");
789 producer
790 .insert(Datagram {
791 sequence: u64::MAX,
792 timestamp: ms(0),
793 payload: Bytes::from_static(b"last"),
794 })
795 .unwrap();
796 assert!(matches!(producer.append(ms(1), "x"), Err(Error::BoundsExceeded(_))));
797 }
798
799 #[test]
800 fn a_consumer_starts_live() {
801 let mut producer = Info::default().produce("dg");
802 producer.append(seq(0), "old").unwrap();
803 let mut consumer = producer.consume();
804 assert!(recv(&mut consumer).is_pending());
805 producer.append(seq(1), "new").unwrap();
806 assert_eq!(sequence(&mut consumer), 1);
807 }
808
809 #[test]
810 fn a_slow_consumer_skips_to_the_oldest_held() {
811 let mut producer = Info::default().produce("dg");
812 let mut consumer = producer.consume();
813 for sequence in 0..MAX_BUFFERED as u64 + 5 {
814 producer.append(seq(sequence), "x").unwrap();
815 }
816 assert_eq!(sequence(&mut consumer), 5);
817 }
818
819 #[test]
820 fn a_slow_consumer_holds_a_bounded_number_of_bytes() {
821 let mut producer = Info::default().produce("dg");
822 let mut consumer = producer.consume();
823 let payload = Bytes::from(vec![0; MAX_BUFFERED_BYTES / 4]);
824 for sequence in 0..8 {
825 producer.append(seq(sequence), payload.clone()).unwrap();
826 }
827 assert_eq!(sequence(&mut consumer), 4);
829 let mut producer = Info::default().produce("dg");
831 let mut consumer = producer.consume();
832 for sequence in 0..2 {
833 producer.append(seq(sequence), vec![0; MAX_PAYLOAD]).unwrap();
834 }
835 assert_eq!(sequence(&mut consumer), 1);
836 }
837
838 #[test]
839 fn timestamps_must_match_the_track() {
840 let mut timed = Info::default().with_timescale(Timescale::MILLI).produce("dg");
841 let mut consumer = timed.consume();
842 assert!(matches!(timed.append(seq(0), "x"), Err(Error::TimestampMismatch)));
843 timed.append(Timestamp::from_secs(1).unwrap(), "x").unwrap();
844 let Poll::Ready(Ok(Some(datagram))) = recv(&mut consumer) else {
845 panic!("expected a datagram");
846 };
847 assert_eq!(datagram.timestamp, Timestamp::from_millis(1000).unwrap());
849 let mut untimed = Info::default().produce("dg");
850 assert!(matches!(
851 untimed.append(Timestamp::from_secs(1).unwrap(), "x"),
852 Err(Error::TimestampMismatch)
853 ));
854 let wrong = Datagram {
856 sequence: 4,
857 timestamp: seq(5),
858 payload: Bytes::from_static(b"x"),
859 };
860 assert!(matches!(untimed.insert(wrong), Err(Error::TimestampMismatch)));
861 assert_eq!(untimed.append(seq(4), "x").unwrap(), 4);
862 }
863
864 #[test]
865 fn the_end_reaches_consumers() {
866 let mut producer = Info::default().produce("dg");
867 let mut finished = producer.consume();
868 producer.clone().finish();
869 assert!(matches!(recv(&mut finished), Poll::Ready(Ok(None))));
870 assert!(matches!(producer.append(seq(0), "x"), Err(Error::Closed)));
871
872 let producer = Info::default().produce("dg");
873 let mut dropped = producer.consume();
874 drop(producer);
875 assert!(matches!(recv(&mut dropped), Poll::Ready(Err(Error::Dropped))));
876 }
877
878 #[test]
879 fn a_finish_delivers_what_is_buffered() {
880 let mut producer = Info::default().produce("dg");
881 let mut consumer = producer.consume();
882 producer.append(seq(0), "a").unwrap();
883 producer.append(seq(1), "b").unwrap();
884 producer.finish();
885 assert_eq!(sequence(&mut consumer), 0);
886 assert_eq!(sequence(&mut consumer), 1);
887 assert!(matches!(recv(&mut consumer), Poll::Ready(Ok(None))));
888
889 let mut producer = Info::default().produce("dg");
891 let _reading = producer.consume();
892 producer.append(seq(0), "a").unwrap();
893 producer.clone().finish();
894 let mut late = producer.consume();
895 assert!(matches!(recv(&mut late), Poll::Ready(Ok(None))));
896
897 let mut producer = Info::default().produce("dg");
900 producer.append(seq(0), "a").unwrap();
901 producer.clone().finish();
902 assert!(producer.state.read().buffer.is_empty());
903 let mut producer = Info::default().produce("dg");
904 let reading = producer.consume();
905 producer.append(seq(0), "a").unwrap();
906 producer.clone().finish();
907 assert_eq!(producer.state.read().buffer.len(), 1);
908 drop(reading);
909 assert!(producer.state.read().buffer.is_empty());
910 assert_eq!(producer.state.read().bytes, 0);
911
912 let mut producer = Info::default().produce("dg");
914 let mut consumer = producer.consume();
915 producer.append(seq(0), "a").unwrap();
916 producer.abort(Error::Cancel);
917 assert!(matches!(recv(&mut consumer), Poll::Ready(Err(Error::Cancel))));
918 }
919
920 #[test]
921 fn the_publisher_sees_the_highest_priority() {
922 let producer = Info::default().produce("dg");
923 assert_eq!(producer.priority(), None);
924 let mut low = producer.consume();
925 let mut high = low.clone();
926 high.set_priority(5);
927 low.set_priority(-3);
928 assert_eq!(producer.priority(), Some(5));
929 assert!(producer.poll_priority(&kio::Waiter::noop(), Some(5)).is_pending());
930 drop(high);
931 assert_eq!(
932 producer.poll_priority(&kio::Waiter::noop(), Some(5)),
933 Poll::Ready(Some(-3))
934 );
935 assert!(!producer.close_unused());
936 drop(low);
937 assert!(producer.close_unused());
938 }
939
940 #[test]
941 fn priority_changed_reports_the_current_value_then_each_change() {
942 let waiter = kio::Waiter::noop();
943 let mut producer = Info::default().produce("dg");
944 assert_eq!(producer.poll_priority_changed(&waiter), Poll::Ready(None));
945 assert!(producer.poll_priority_changed(&waiter).is_pending());
946 let mut consumer = producer.consume();
947 consumer.set_priority(4);
948 assert_eq!(producer.poll_priority_changed(&waiter), Poll::Ready(Some(4)));
949 assert!(producer.poll_priority_changed(&waiter).is_pending());
950 let mut clone = producer.clone();
952 assert_eq!(clone.poll_priority_changed(&waiter), Poll::Ready(Some(4)));
953 drop(consumer);
954 assert_eq!(producer.poll_priority_changed(&waiter), Poll::Ready(None));
955 }
956
957 #[test]
958 fn a_request_resolves_its_consumers() {
959 let request = Request::new("dg".into());
960 let consumer = request.weak().try_consume(stats::Scope::default()).unwrap();
961 assert!(consumer.poll_info(&kio::Waiter::noop()).is_pending());
962 let info = Info::default().with_priority(3);
963 let _producer = request.accept(info);
964 assert!(matches!(consumer.poll_info(&kio::Waiter::noop()), Poll::Ready(Ok(got)) if got == info));
965
966 let request = Request::new("dg".into());
967 let mut consumer = request.weak().try_consume(stats::Scope::default()).unwrap();
968 request.reject(Error::NotFound);
969 assert!(matches!(recv(&mut consumer), Poll::Ready(Err(Error::NotFound))));
970 assert!(matches!(
971 consumer.poll_info(&kio::Waiter::noop()),
972 Poll::Ready(Err(Error::NotFound))
973 ));
974 }
975}