1use alpha2_media::{CancelToken, DecodeError};
3use std::time::Duration;
4
5#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
7pub enum DecodePolicy {
8 #[default]
10 Strict,
11 Tolerant,
13}
14
15impl DecodePolicy {
16 #[must_use]
18 pub const fn as_str(self) -> &'static str {
19 match self {
20 Self::Strict => "strict",
21 Self::Tolerant => "tolerant",
22 }
23 }
24
25 #[must_use]
27 pub fn parse(value: &str) -> Option<Self> {
28 [Self::Strict, Self::Tolerant]
29 .into_iter()
30 .find(|policy| policy.as_str() == value)
31 }
32
33 pub fn from_env() -> Result<Self, String> {
38 match std::env::var("ALPHA2_DECODE_POLICY") {
39 Err(std::env::VarError::NotPresent) => Some(Self::Strict),
40 Ok(value) => Self::parse(&value),
41 Err(std::env::VarError::NotUnicode(_)) => None,
42 }
43 .ok_or_else(|| "ALPHA2_DECODE_POLICY must be strict or tolerant".to_owned())
44 }
45}
46
47#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
50pub struct DecodeDiagnosticCounts {
51 pub corrupt_packets: u64,
53 pub video_gaps: u64,
55 pub concealed_audio_samples: u64,
57 pub timestamp_gap_samples: u64,
59 pub dropped_audio_samples: u64,
61}
62
63impl DecodeDiagnosticCounts {
64 pub fn record(&mut self, diagnostic: &DecodeDiagnostic) {
66 let samples = |start: i64, end: i64| u64::try_from(end.saturating_sub(start)).unwrap_or(0);
67 match diagnostic {
68 DecodeDiagnostic::Corruption(_) => {
69 self.corrupt_packets = self.corrupt_packets.saturating_add(1);
70 }
71 DecodeDiagnostic::VideoGap(_) => self.video_gaps = self.video_gaps.saturating_add(1),
72 DecodeDiagnostic::AudioGap(gap) => {
73 let count = samples(gap.start_sample, gap.end_sample);
74 let total = if gap.reason == "timestamp gap" {
75 &mut self.timestamp_gap_samples
76 } else {
77 &mut self.concealed_audio_samples
78 };
79 *total = total.saturating_add(count);
80 }
81 DecodeDiagnostic::AudioOverlap(overlap) => {
82 self.dropped_audio_samples = self
83 .dropped_audio_samples
84 .saturating_add(samples(overlap.start_sample, overlap.end_sample));
85 }
86 }
87 }
88
89 #[must_use]
91 pub fn is_empty(&self) -> bool {
92 *self == Self::default()
93 }
94}
95
96#[derive(Clone, Debug, PartialEq, Eq)]
98pub struct CorruptPacket {
99 pub stage: &'static str,
101 pub pts: Option<i64>,
103 pub time_base: (i32, i32),
105 pub detail: Option<String>,
107}
108
109const MAX_AUDIO_RECORDS: usize = 1024;
110
111#[derive(Clone, Debug, PartialEq, Eq)]
114pub struct ConcealedAudioGap {
115 pub start_sample: i64,
117 pub end_sample: i64,
119 pub sample_rate: u32,
121 pub reason: &'static str,
123}
124
125#[derive(Clone, Debug, PartialEq, Eq)]
128pub struct DroppedAudioOverlap {
129 pub start_sample: i64,
131 pub end_sample: i64,
133 pub sample_rate: u32,
135}
136
137#[derive(Clone, Debug, PartialEq, Eq)]
139pub struct VideoRecoveryGap {
140 pub previous_pts: Option<i64>,
142 pub recovered_pts: Option<i64>,
144 pub time_base: (i32, i32),
146}
147
148#[derive(Clone, Debug, Default, PartialEq, Eq)]
150pub struct DecodeDiagnostics {
151 pub corrupt_packets: Vec<CorruptPacket>,
153 pub audio_gaps: Vec<ConcealedAudioGap>,
155 pub audio_overlaps: Vec<DroppedAudioOverlap>,
157 pub video_gaps: Vec<VideoRecoveryGap>,
159}
160
161#[derive(Clone, Debug, PartialEq, Eq)]
163pub enum DecodeDiagnostic {
164 Corruption(CorruptPacket),
166 AudioGap(ConcealedAudioGap),
168 AudioOverlap(DroppedAudioOverlap),
170 VideoGap(VideoRecoveryGap),
172}
173
174#[derive(Clone, Copy, Debug, PartialEq, Eq)]
176pub enum DecodeFailure {
177 InvalidData,
179 HardwarePicture,
182 Other,
184}
185
186const AUDIO_TIMESTAMP_LIMIT_SECONDS: i128 = 1 << 31;
189
190#[must_use]
193pub fn audio_timestamp_in_range(pts: i64, num: i64, den: i64) -> bool {
194 let (num, den) = (i128::from(num), i128::from(den));
195 num > 0 && den > 0 && (i128::from(pts) * num).abs() <= AUDIO_TIMESTAMP_LIMIT_SECONDS * den
196}
197
198#[derive(Default)]
200pub struct Recovery {
201 pub policy: DecodePolicy,
203 pub reporter: Option<Box<dyn Fn(DecodeDiagnostic) + Send + Sync>>,
205 pub diagnostics: DecodeDiagnostics,
207 consecutive: usize,
208 last_pts: Option<i64>,
209 stalled: usize,
210 video_damage: bool,
211 time_base: (i32, i32),
212 healthy_frames: usize,
213 hardware: bool,
215}
216impl Recovery {
217 #[must_use]
219 pub fn new(time_base: (i32, i32)) -> Self {
220 Self {
221 time_base,
222 ..Self::default()
223 }
224 }
225 #[must_use]
227 pub fn hardware(time_base: (i32, i32)) -> Self {
228 Self {
229 hardware: true,
230 ..Self::new(time_base)
231 }
232 }
233 pub fn set_hardware(&mut self, hardware: bool) {
235 self.hardware = hardware;
236 }
237 pub fn finish_video_gap(&mut self, recovered_pts: Option<i64>) {
239 if !self.video_damage {
240 return;
241 }
242 self.video_damage = false;
243 let gap = VideoRecoveryGap {
244 previous_pts: self.last_pts,
245 recovered_pts,
246 time_base: self.time_base,
247 };
248 self.diagnostics.video_gaps.push(gap.clone());
249 if let Some(report) = &self.reporter {
250 report(DecodeDiagnostic::VideoGap(gap));
251 }
252 }
253
254 #[must_use]
258 pub fn counts_as_damage(&self, failure: DecodeFailure) -> bool {
259 match failure {
260 DecodeFailure::InvalidData => true,
261 DecodeFailure::HardwarePicture => {
262 self.hardware && self.policy == DecodePolicy::Tolerant
263 }
264 DecodeFailure::Other => false,
265 }
266 }
267 pub fn corrupt(&mut self, stage: &'static str, pts: Option<i64>) -> Result<(), DecodeError> {
272 self.corrupt_with_detail(stage, pts, None)
273 }
274
275 pub fn corrupt_with_detail(
283 &mut self,
284 stage: &'static str,
285 pts: Option<i64>,
286 detail: Option<String>,
287 ) -> Result<(), DecodeError> {
288 if self.diagnostics.corrupt_packets.len() >= 1024 {
289 return Err(DecodeError::Adapter(
290 "corruption diagnostic budget exceeded".into(),
291 ));
292 }
293 self.diagnostics.corrupt_packets.push(CorruptPacket {
294 stage,
295 pts,
296 time_base: self.time_base,
297 detail,
298 });
299 if let Some(report) = &self.reporter {
300 report(DecodeDiagnostic::Corruption(
301 self.diagnostics.corrupt_packets.last().unwrap().clone(),
302 ));
303 }
304 self.video_damage |= stage.starts_with("video");
305 self.consecutive += 1;
306 if self.policy == DecodePolicy::Strict {
307 return Err(DecodeError::Adapter(format!(
308 "corrupt input at {stage} (strict decode policy)"
309 )));
310 }
311 if self.consecutive > 32 {
312 return Err(DecodeError::Adapter(
313 "consecutive corruption budget exceeded".into(),
314 ));
315 }
316 Ok(())
317 }
318 pub fn video_eof(&mut self) -> Result<(), DecodeError> {
323 self.finish_video_gap(None);
324 if self.consecutive != 0 {
325 self.damaged_tail("video")?;
326 }
327 Ok(())
328 }
329 pub fn damaged_tail(&self, kind: &str) -> Result<(), DecodeError> {
335 if self.healthy_frames == 0 {
336 return Err(DecodeError::Adapter(format!(
337 "damaged {kind} has no recoverable frames"
338 )));
339 }
340 Ok(())
341 }
342 pub fn progress(&mut self, pts: Option<i64>) -> Result<(), DecodeError> {
347 self.healthy_frames = self.healthy_frames.saturating_add(1);
348 self.finish_video_gap(pts);
349 self.consecutive = 0;
350 if let Some(pts) = pts
351 && self.last_pts.is_none_or(|previous| pts > previous)
352 {
353 self.last_pts = Some(pts);
354 self.stalled = 0;
355 } else {
356 self.stalled += 1;
357 }
358 if self.stalled > 256 {
359 return Err(DecodeError::Adapter(
360 "decoder PTS progress budget exceeded".into(),
361 ));
362 }
363 Ok(())
364 }
365 pub fn reset_progress(&mut self) {
367 self.finish_video_gap(None);
368 self.last_pts = None;
369 self.healthy_frames = 0;
370 self.stalled = 0;
371 self.consecutive = 0;
372 }
373 pub fn audio_gap(
378 &mut self,
379 start_sample: i64,
380 end_sample: i64,
381 sample_rate: u32,
382 reason: &'static str,
383 ) -> Result<(), DecodeError> {
384 if self.diagnostics.audio_gaps.len() >= MAX_AUDIO_RECORDS {
385 return Err(DecodeError::Adapter(
386 "audio gap diagnostic budget exceeded".into(),
387 ));
388 }
389 self.timestamp_audio_gap(start_sample, end_sample, sample_rate, reason);
390 Ok(())
391 }
392 pub fn timestamp_gap(&mut self, start_sample: i64, end_sample: i64, sample_rate: u32) {
395 self.timestamp_audio_gap(start_sample, end_sample, sample_rate, "timestamp gap");
396 }
397 fn timestamp_audio_gap(
398 &mut self,
399 start_sample: i64,
400 end_sample: i64,
401 sample_rate: u32,
402 reason: &'static str,
403 ) {
404 let gap = ConcealedAudioGap {
405 start_sample,
406 end_sample,
407 sample_rate,
408 reason,
409 };
410 if let Some(report) = &self.reporter {
411 report(DecodeDiagnostic::AudioGap(gap.clone()));
412 }
413 if self.diagnostics.audio_gaps.len() < MAX_AUDIO_RECORDS {
414 self.diagnostics.audio_gaps.push(gap);
415 }
416 }
417 pub fn timestamp_overlap(&mut self, start_sample: i64, end_sample: i64, sample_rate: u32) {
419 let overlap = DroppedAudioOverlap {
420 start_sample,
421 end_sample,
422 sample_rate,
423 };
424 if let Some(report) = &self.reporter {
425 report(DecodeDiagnostic::AudioOverlap(overlap.clone()));
426 }
427 if self.diagnostics.audio_overlaps.len() < MAX_AUDIO_RECORDS {
428 self.diagnostics.audio_overlaps.push(overlap);
429 }
430 }
431}
432
433pub const DECODE_WORK_LIMIT: Duration = Duration::from_secs(10);
441
442const DECODE_WORK_STEPS: usize = 65_536;
444
445thread_local! {
446 static DECODE_PROGRESS_WATCH: std::cell::RefCell<Option<Box<dyn Fn()>>> =
447 const { std::cell::RefCell::new(None) };
448 static INPUT_WAIT: std::cell::Cell<Duration> = const { std::cell::Cell::new(Duration::ZERO) };
449}
450
451pub fn report_input_wait(waited: Duration) {
454 INPUT_WAIT.with(|total| total.set(total.get().saturating_add(waited)));
455}
456
457fn input_wait() -> Duration {
458 INPUT_WAIT.with(std::cell::Cell::get)
459}
460
461#[cfg(any(test, feature = "test-hooks"))]
462thread_local! {
463 pub static WORK_LIMIT: std::cell::Cell<Duration> =
466 std::cell::Cell::new(test_work_limit(std::env::var("ALPHA2_TEST_DECODE_WORK_LIMIT_MS").ok().as_deref()));
467 pub static WORK_STEPS: std::cell::Cell<usize> =
469 const { std::cell::Cell::new(DECODE_WORK_STEPS) };
470 pub static FRAME_DELAY: std::cell::Cell<Duration> =
473 const { std::cell::Cell::new(Duration::ZERO) };
474 pub static VIRTUAL_CLOCK: std::cell::Cell<Option<Duration>> =
477 const { std::cell::Cell::new(None) };
478}
479
480#[cfg(any(test, feature = "test-hooks"))]
482fn test_work_limit(setting: Option<&str>) -> Duration {
483 setting
484 .and_then(|value| value.parse::<u64>().ok())
485 .filter(|millis| *millis > 0)
486 .map_or(DECODE_WORK_LIMIT, Duration::from_millis)
487}
488
489#[cfg(any(test, feature = "test-hooks"))]
491pub fn take_frame_delay() {
492 let delay = FRAME_DELAY.with(std::cell::Cell::get);
493 match VIRTUAL_CLOCK.with(std::cell::Cell::get) {
494 Some(now) => VIRTUAL_CLOCK.with(|clock| clock.set(Some(now.saturating_add(delay)))),
495 None => std::thread::sleep(delay),
496 }
497}
498
499#[must_use = "the watch ends when the guard drops"]
504pub fn watch_decode_progress(progressed: impl Fn() + 'static) -> DecodeProgressWatch {
505 let previous = DECODE_PROGRESS_WATCH.with(|watch| watch.replace(Some(Box::new(progressed))));
506 DecodeProgressWatch {
507 previous,
508 thread: std::marker::PhantomData,
509 }
510}
511
512pub fn report_decode_progress() {
515 DECODE_PROGRESS_WATCH.with(|watch| {
516 if let Some(progressed) = watch.borrow().as_ref() {
517 progressed();
518 }
519 });
520}
521
522pub struct DecodeProgressWatch {
524 previous: Option<Box<dyn Fn()>>,
525 thread: std::marker::PhantomData<*const ()>,
526}
527
528impl Drop for DecodeProgressWatch {
529 fn drop(&mut self) {
530 let previous = self.previous.take();
531 DECODE_PROGRESS_WATCH.with(|watch| {
532 watch.replace(previous);
533 });
534 }
535}
536
537pub struct WorkBudget {
540 started: alpha2_os::AwakeInstant,
542 input_wait_at_start: Duration,
543 #[cfg(any(test, feature = "test-hooks"))]
545 started_virtual: Option<Duration>,
546 steps: usize,
547}
548impl Default for WorkBudget {
549 fn default() -> Self {
550 Self::new()
551 }
552}
553
554impl WorkBudget {
555 #[must_use]
557 pub fn new() -> Self {
558 Self {
559 started: alpha2_os::AwakeInstant::now(),
560 input_wait_at_start: input_wait(),
561 #[cfg(any(test, feature = "test-hooks"))]
562 started_virtual: VIRTUAL_CLOCK.with(std::cell::Cell::get),
563 steps: 0,
564 }
565 }
566
567 fn elapsed(&self) -> Duration {
568 #[cfg(any(test, feature = "test-hooks"))]
569 if let (Some(now), Some(started)) = (
570 VIRTUAL_CLOCK.with(std::cell::Cell::get),
571 self.started_virtual,
572 ) {
573 return now.saturating_sub(started);
574 }
575 self.started
576 .elapsed()
577 .saturating_sub(input_wait().saturating_sub(self.input_wait_at_start))
578 }
579 pub fn step(&mut self, cancel: &CancelToken) -> Result<(), DecodeError> {
584 if cancel.is_cancelled() {
585 return Err(DecodeError::Cancelled);
586 }
587 self.steps += 1;
588 #[cfg(any(test, feature = "test-hooks"))]
589 let (limit, steps) = (
590 WORK_LIMIT.with(std::cell::Cell::get),
591 WORK_STEPS.with(std::cell::Cell::get),
592 );
593 #[cfg(not(any(test, feature = "test-hooks")))]
594 let (limit, steps) = (DECODE_WORK_LIMIT, DECODE_WORK_STEPS);
595 if self.steps > steps || self.elapsed() > limit {
596 return Err(DecodeError::Adapter(
597 "decode progress budget exceeded".into(),
598 ));
599 }
600 Ok(())
601 }
602 pub fn advanced(&mut self) {
605 self.started = alpha2_os::AwakeInstant::now();
606 self.input_wait_at_start = input_wait();
607 #[cfg(any(test, feature = "test-hooks"))]
608 {
609 self.started_virtual = VIRTUAL_CLOCK.with(std::cell::Cell::get);
610 }
611 }
612
613 pub fn progressed(&mut self) {
615 self.started = alpha2_os::AwakeInstant::now();
616 self.input_wait_at_start = input_wait();
617 #[cfg(any(test, feature = "test-hooks"))]
618 {
619 self.started_virtual = VIRTUAL_CLOCK.with(std::cell::Cell::get);
620 }
621 self.steps = 0;
622 report_decode_progress();
623 }
624}
625
626pub fn submit_packet(
632 mut step: impl FnMut(bool) -> Result<bool, DecodeError>,
633 budget: &mut WorkBudget,
634 cancel: &CancelToken,
635) -> Result<(), DecodeError> {
636 for _ in 0..64 {
637 budget.step(cancel)?;
638 if step(false)? {
639 budget.advanced();
640 return Ok(());
641 }
642 budget.step(cancel)?;
643 if !step(true)? {
644 return Err(DecodeError::Adapter(
645 "decoder send/receive made no progress".into(),
646 ));
647 }
648 }
649 Err(DecodeError::Adapter("packet retry budget exceeded".into()))
650}
651
652#[cfg(test)]
653mod tests {
654 use super::*;
655
656 #[test]
657 fn a_reported_input_wait_is_not_counted_against_a_work_budget() {
658 const LIMIT: Duration = Duration::from_millis(50);
659 WORK_LIMIT.with(|limit| limit.set(LIMIT));
660 let cancel = CancelToken::default();
661 let mut budget = WorkBudget::new();
662 std::thread::sleep(LIMIT * 2);
663 report_input_wait(LIMIT * 2);
664 assert!(budget.step(&cancel).is_ok(), "a wait for input is not work");
665 std::thread::sleep(LIMIT * 2);
666 assert!(
667 budget.step(&cancel).is_err(),
668 "time past the wait still counts"
669 );
670 WORK_LIMIT.with(|limit| limit.set(DECODE_WORK_LIMIT));
671 }
672
673 #[test]
674 fn a_policy_is_named_as_the_host_names_it() {
675 for policy in [DecodePolicy::Strict, DecodePolicy::Tolerant] {
676 assert_eq!(DecodePolicy::parse(policy.as_str()), Some(policy));
677 }
678 assert_eq!(DecodePolicy::Tolerant.as_str(), "tolerant");
679 assert_eq!(DecodePolicy::parse("Tolerant"), None);
680 assert_eq!(DecodePolicy::parse(""), None);
681 }
682
683 #[test]
684 fn an_audio_timestamp_is_in_range_up_to_two_to_the_31_seconds() {
685 let limit = (1_i64 << 31) * 48_000;
686 assert!(audio_timestamp_in_range(limit, 1, 48_000));
687 assert!(audio_timestamp_in_range(-limit, 1, 48_000));
688 assert!(!audio_timestamp_in_range(limit + 1, 1, 48_000));
689 assert!(!audio_timestamp_in_range(i64::MIN, 1, 48_000));
690 assert!(!audio_timestamp_in_range(i64::MAX, 1, 1));
691 assert!(audio_timestamp_in_range(1 << 31, 1, 1));
692 assert!(!audio_timestamp_in_range(0, 0, 1));
693 assert!(!audio_timestamp_in_range(0, 1, 0));
694 }
695
696 #[test]
697 fn counts_tell_concealed_damage_from_a_timestamp_gap() {
698 let mut counts = DecodeDiagnosticCounts::default();
699 assert!(counts.is_empty());
700 let gap = |start_sample, end_sample, reason| {
701 DecodeDiagnostic::AudioGap(ConcealedAudioGap {
702 start_sample,
703 end_sample,
704 sample_rate: 48_000,
705 reason,
706 })
707 };
708 for diagnostic in [
709 DecodeDiagnostic::Corruption(CorruptPacket {
710 stage: "audio send",
711 pts: None,
712 time_base: (1, 48_000),
713 detail: None,
714 }),
715 gap(1024, 2048, "corrupt input"),
716 gap(4096, 4196, "timestamp gap"),
717 DecodeDiagnostic::AudioOverlap(DroppedAudioOverlap {
718 start_sample: 10,
719 end_sample: 15,
720 sample_rate: 48_000,
721 }),
722 DecodeDiagnostic::VideoGap(VideoRecoveryGap {
723 previous_pts: Some(1),
724 recovered_pts: None,
725 time_base: (1, 10),
726 }),
727 ] {
728 counts.record(&diagnostic);
729 }
730 assert_eq!(
731 counts,
732 DecodeDiagnosticCounts {
733 corrupt_packets: 1,
734 video_gaps: 1,
735 concealed_audio_samples: 1024,
736 timestamp_gap_samples: 100,
737 dropped_audio_samples: 5,
738 }
739 );
740 assert!(!counts.is_empty());
741 }
742 #[test]
745 fn a_hardware_sessions_picture_failure_is_damage_only_when_tolerant() {
746 let mut tolerant = Recovery::hardware((1, 30));
747 tolerant.policy = DecodePolicy::Tolerant;
748 assert!(tolerant.counts_as_damage(DecodeFailure::HardwarePicture));
749 assert!(!Recovery::hardware((1, 30)).counts_as_damage(DecodeFailure::HardwarePicture));
750 let mut software = Recovery::new((1, 30));
751 software.policy = DecodePolicy::Tolerant;
752 assert!(!software.counts_as_damage(DecodeFailure::HardwarePicture));
753 assert!(software.counts_as_damage(DecodeFailure::InvalidData));
754 assert!(!software.counts_as_damage(DecodeFailure::Other));
755 }
756
757 #[test]
758 fn strict_tolerant_and_fatal_errors() {
759 let mut state = Recovery::default();
760 assert!(state.corrupt("send", Some(12)).is_err());
761 state.policy = DecodePolicy::Tolerant;
762 state.reset_progress();
763 assert!(state.counts_as_damage(DecodeFailure::InvalidData));
764 assert!(state.corrupt("send", Some(13)).is_ok());
765 assert_eq!(state.diagnostics.corrupt_packets.len(), 2);
766 for _ in 0..31 {
767 state.corrupt("receive", None).unwrap();
768 }
769 assert!(state.corrupt("receive", None).is_err());
770 }
771 #[test]
772 fn progress_and_cancellation_are_bounded() {
773 let mut state = Recovery::default();
774 state.progress(Some(10)).unwrap();
775 for _ in 0..256 {
776 state.progress(Some(10)).unwrap();
777 }
778 assert!(state.progress(Some(10)).is_err());
779 state.reset_progress();
780 state.progress(Some(0)).unwrap();
781 let cancel = CancelToken::default();
782 let mut budget = WorkBudget::new();
783 for _ in 0..65_536 {
784 budget.step(&cancel).unwrap();
785 }
786 assert!(budget.step(&cancel).is_err());
787 WORK_LIMIT.with(|limit| limit.set(DECODE_WORK_LIMIT));
789 let mut budget = WorkBudget::new();
790 budget.started = budget
791 .started
792 .checked_sub(Duration::from_secs(11))
793 .expect("the clock reaches back 11 s");
794 assert!(budget.step(&cancel).is_err());
795 cancel.cancel();
796 assert_eq!(WorkBudget::new().step(&cancel), Err(DecodeError::Cancelled));
797 }
798 #[test]
799 fn eagain_drains_and_retries_the_same_packet_until_accepted() {
800 let mut actions = Vec::new();
801 let mut sends = 0;
802 submit_packet(
803 |drain| {
804 actions.push(drain);
805 if drain {
806 return Ok(true);
807 }
808 sends += 1;
809 Ok(sends == 3)
810 },
811 &mut WorkBudget::new(),
812 &CancelToken::default(),
813 )
814 .unwrap();
815 assert_eq!(actions, [false, true, false, true, false]);
816 assert!(
817 submit_packet(
818 |_| Ok(false),
819 &mut WorkBudget::new(),
820 &CancelToken::default()
821 )
822 .is_err()
823 );
824 assert!(submit_packet(Ok, &mut WorkBudget::new(), &CancelToken::default()).is_err());
825 let cancel = CancelToken::default();
826 let result = submit_packet(
827 |drain| {
828 if drain {
829 cancel.cancel();
830 }
831 Ok(drain)
832 },
833 &mut WorkBudget::new(),
834 &cancel,
835 );
836 assert_eq!(result, Err(DecodeError::Cancelled));
837 }
838
839 #[test]
840 fn the_time_limit_runs_from_the_last_step_forward_and_the_step_limit_from_the_last_frame() {
841 let cancel = CancelToken::default();
842 let limit = Duration::from_secs(10);
843 WORK_LIMIT.with(|cell| cell.set(limit));
844 VIRTUAL_CLOCK.with(|clock| clock.set(Some(Duration::ZERO)));
845 let advance = |by: Duration| {
846 VIRTUAL_CLOCK.with(|clock| clock.set(clock.get().map(|now| now + by)));
847 };
848 let mut budget = WorkBudget::new();
850 budget.step(&cancel).unwrap();
851 advance(Duration::from_secs(11));
852 budget.advanced();
853 budget.step(&cancel).expect("a slow read that returned");
854 advance(Duration::from_secs(11));
856 assert!(budget.step(&cancel).is_err());
857 WORK_STEPS.with(|cell| cell.set(100));
859 let mut budget = WorkBudget::new();
860 for _ in 0..100 {
861 budget.step(&cancel).unwrap();
862 budget.advanced();
863 }
864 assert!(budget.step(&cancel).is_err());
865 WORK_STEPS.with(|cell| cell.set(DECODE_WORK_STEPS));
866 VIRTUAL_CLOCK.with(|clock| clock.set(None));
867 }
868
869 #[test]
870 fn an_accepted_packet_restarts_the_time_limit() {
871 let cancel = CancelToken::default();
872 WORK_LIMIT.with(|cell| cell.set(Duration::from_secs(10)));
873 VIRTUAL_CLOCK.with(|clock| clock.set(Some(Duration::ZERO)));
874 let mut budget = WorkBudget::new();
875 submit_packet(
876 |_| {
877 VIRTUAL_CLOCK.with(|clock| {
879 clock.set(clock.get().map(|now| now + Duration::from_secs(11)));
880 });
881 Ok(true)
882 },
883 &mut budget,
884 &cancel,
885 )
886 .unwrap();
887 budget
888 .step(&cancel)
889 .expect("the accepted packet was a step forward");
890 VIRTUAL_CLOCK.with(|clock| clock.set(None));
891 }
892}