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}
449
450#[cfg(any(test, feature = "test-hooks"))]
451thread_local! {
452 pub static WORK_LIMIT: std::cell::Cell<Duration> =
455 std::cell::Cell::new(test_work_limit(std::env::var("ALPHA2_TEST_DECODE_WORK_LIMIT_MS").ok().as_deref()));
456 pub static WORK_STEPS: std::cell::Cell<usize> =
458 const { std::cell::Cell::new(DECODE_WORK_STEPS) };
459 pub static FRAME_DELAY: std::cell::Cell<Duration> =
462 const { std::cell::Cell::new(Duration::ZERO) };
463 pub static VIRTUAL_CLOCK: std::cell::Cell<Option<Duration>> =
466 const { std::cell::Cell::new(None) };
467}
468
469#[cfg(any(test, feature = "test-hooks"))]
471fn test_work_limit(setting: Option<&str>) -> Duration {
472 setting
473 .and_then(|value| value.parse::<u64>().ok())
474 .filter(|millis| *millis > 0)
475 .map_or(DECODE_WORK_LIMIT, Duration::from_millis)
476}
477
478#[cfg(any(test, feature = "test-hooks"))]
480pub fn take_frame_delay() {
481 let delay = FRAME_DELAY.with(std::cell::Cell::get);
482 match VIRTUAL_CLOCK.with(std::cell::Cell::get) {
483 Some(now) => VIRTUAL_CLOCK.with(|clock| clock.set(Some(now.saturating_add(delay)))),
484 None => std::thread::sleep(delay),
485 }
486}
487
488#[must_use = "the watch ends when the guard drops"]
493pub fn watch_decode_progress(progressed: impl Fn() + 'static) -> DecodeProgressWatch {
494 let previous = DECODE_PROGRESS_WATCH.with(|watch| watch.replace(Some(Box::new(progressed))));
495 DecodeProgressWatch {
496 previous,
497 thread: std::marker::PhantomData,
498 }
499}
500
501pub fn report_decode_progress() {
504 DECODE_PROGRESS_WATCH.with(|watch| {
505 if let Some(progressed) = watch.borrow().as_ref() {
506 progressed();
507 }
508 });
509}
510
511pub struct DecodeProgressWatch {
513 previous: Option<Box<dyn Fn()>>,
514 thread: std::marker::PhantomData<*const ()>,
515}
516
517impl Drop for DecodeProgressWatch {
518 fn drop(&mut self) {
519 let previous = self.previous.take();
520 DECODE_PROGRESS_WATCH.with(|watch| {
521 watch.replace(previous);
522 });
523 }
524}
525
526pub struct WorkBudget {
529 started: alpha2_os::AwakeInstant,
531 #[cfg(any(test, feature = "test-hooks"))]
533 started_virtual: Option<Duration>,
534 steps: usize,
535}
536impl Default for WorkBudget {
537 fn default() -> Self {
538 Self::new()
539 }
540}
541
542impl WorkBudget {
543 #[must_use]
545 pub fn new() -> Self {
546 Self {
547 started: alpha2_os::AwakeInstant::now(),
548 #[cfg(any(test, feature = "test-hooks"))]
549 started_virtual: VIRTUAL_CLOCK.with(std::cell::Cell::get),
550 steps: 0,
551 }
552 }
553
554 fn elapsed(&self) -> Duration {
555 #[cfg(any(test, feature = "test-hooks"))]
556 if let (Some(now), Some(started)) = (
557 VIRTUAL_CLOCK.with(std::cell::Cell::get),
558 self.started_virtual,
559 ) {
560 return now.saturating_sub(started);
561 }
562 self.started.elapsed()
563 }
564 pub fn step(&mut self, cancel: &CancelToken) -> Result<(), DecodeError> {
569 if cancel.is_cancelled() {
570 return Err(DecodeError::Cancelled);
571 }
572 self.steps += 1;
573 #[cfg(any(test, feature = "test-hooks"))]
574 let (limit, steps) = (
575 WORK_LIMIT.with(std::cell::Cell::get),
576 WORK_STEPS.with(std::cell::Cell::get),
577 );
578 #[cfg(not(any(test, feature = "test-hooks")))]
579 let (limit, steps) = (DECODE_WORK_LIMIT, DECODE_WORK_STEPS);
580 if self.steps > steps || self.elapsed() > limit {
581 return Err(DecodeError::Adapter(
582 "decode progress budget exceeded".into(),
583 ));
584 }
585 Ok(())
586 }
587 pub fn advanced(&mut self) {
590 self.started = alpha2_os::AwakeInstant::now();
591 #[cfg(any(test, feature = "test-hooks"))]
592 {
593 self.started_virtual = VIRTUAL_CLOCK.with(std::cell::Cell::get);
594 }
595 }
596
597 pub fn progressed(&mut self) {
599 self.started = alpha2_os::AwakeInstant::now();
600 #[cfg(any(test, feature = "test-hooks"))]
601 {
602 self.started_virtual = VIRTUAL_CLOCK.with(std::cell::Cell::get);
603 }
604 self.steps = 0;
605 report_decode_progress();
606 }
607}
608
609pub fn submit_packet(
615 mut step: impl FnMut(bool) -> Result<bool, DecodeError>,
616 budget: &mut WorkBudget,
617 cancel: &CancelToken,
618) -> Result<(), DecodeError> {
619 for _ in 0..64 {
620 budget.step(cancel)?;
621 if step(false)? {
622 budget.advanced();
623 return Ok(());
624 }
625 budget.step(cancel)?;
626 if !step(true)? {
627 return Err(DecodeError::Adapter(
628 "decoder send/receive made no progress".into(),
629 ));
630 }
631 }
632 Err(DecodeError::Adapter("packet retry budget exceeded".into()))
633}
634
635#[cfg(test)]
636mod tests {
637 use super::*;
638
639 #[test]
640 fn a_policy_is_named_as_the_host_names_it() {
641 for policy in [DecodePolicy::Strict, DecodePolicy::Tolerant] {
642 assert_eq!(DecodePolicy::parse(policy.as_str()), Some(policy));
643 }
644 assert_eq!(DecodePolicy::Tolerant.as_str(), "tolerant");
645 assert_eq!(DecodePolicy::parse("Tolerant"), None);
646 assert_eq!(DecodePolicy::parse(""), None);
647 }
648
649 #[test]
650 fn an_audio_timestamp_is_in_range_up_to_two_to_the_31_seconds() {
651 let limit = (1_i64 << 31) * 48_000;
652 assert!(audio_timestamp_in_range(limit, 1, 48_000));
653 assert!(audio_timestamp_in_range(-limit, 1, 48_000));
654 assert!(!audio_timestamp_in_range(limit + 1, 1, 48_000));
655 assert!(!audio_timestamp_in_range(i64::MIN, 1, 48_000));
656 assert!(!audio_timestamp_in_range(i64::MAX, 1, 1));
657 assert!(audio_timestamp_in_range(1 << 31, 1, 1));
658 assert!(!audio_timestamp_in_range(0, 0, 1));
659 assert!(!audio_timestamp_in_range(0, 1, 0));
660 }
661
662 #[test]
663 fn counts_tell_concealed_damage_from_a_timestamp_gap() {
664 let mut counts = DecodeDiagnosticCounts::default();
665 assert!(counts.is_empty());
666 let gap = |start_sample, end_sample, reason| {
667 DecodeDiagnostic::AudioGap(ConcealedAudioGap {
668 start_sample,
669 end_sample,
670 sample_rate: 48_000,
671 reason,
672 })
673 };
674 for diagnostic in [
675 DecodeDiagnostic::Corruption(CorruptPacket {
676 stage: "audio send",
677 pts: None,
678 time_base: (1, 48_000),
679 detail: None,
680 }),
681 gap(1024, 2048, "corrupt input"),
682 gap(4096, 4196, "timestamp gap"),
683 DecodeDiagnostic::AudioOverlap(DroppedAudioOverlap {
684 start_sample: 10,
685 end_sample: 15,
686 sample_rate: 48_000,
687 }),
688 DecodeDiagnostic::VideoGap(VideoRecoveryGap {
689 previous_pts: Some(1),
690 recovered_pts: None,
691 time_base: (1, 10),
692 }),
693 ] {
694 counts.record(&diagnostic);
695 }
696 assert_eq!(
697 counts,
698 DecodeDiagnosticCounts {
699 corrupt_packets: 1,
700 video_gaps: 1,
701 concealed_audio_samples: 1024,
702 timestamp_gap_samples: 100,
703 dropped_audio_samples: 5,
704 }
705 );
706 assert!(!counts.is_empty());
707 }
708 #[test]
711 fn a_hardware_sessions_picture_failure_is_damage_only_when_tolerant() {
712 let mut tolerant = Recovery::hardware((1, 30));
713 tolerant.policy = DecodePolicy::Tolerant;
714 assert!(tolerant.counts_as_damage(DecodeFailure::HardwarePicture));
715 assert!(!Recovery::hardware((1, 30)).counts_as_damage(DecodeFailure::HardwarePicture));
716 let mut software = Recovery::new((1, 30));
717 software.policy = DecodePolicy::Tolerant;
718 assert!(!software.counts_as_damage(DecodeFailure::HardwarePicture));
719 assert!(software.counts_as_damage(DecodeFailure::InvalidData));
720 assert!(!software.counts_as_damage(DecodeFailure::Other));
721 }
722
723 #[test]
724 fn strict_tolerant_and_fatal_errors() {
725 let mut state = Recovery::default();
726 assert!(state.corrupt("send", Some(12)).is_err());
727 state.policy = DecodePolicy::Tolerant;
728 state.reset_progress();
729 assert!(state.counts_as_damage(DecodeFailure::InvalidData));
730 assert!(state.corrupt("send", Some(13)).is_ok());
731 assert_eq!(state.diagnostics.corrupt_packets.len(), 2);
732 for _ in 0..31 {
733 state.corrupt("receive", None).unwrap();
734 }
735 assert!(state.corrupt("receive", None).is_err());
736 }
737 #[test]
738 fn progress_and_cancellation_are_bounded() {
739 let mut state = Recovery::default();
740 state.progress(Some(10)).unwrap();
741 for _ in 0..256 {
742 state.progress(Some(10)).unwrap();
743 }
744 assert!(state.progress(Some(10)).is_err());
745 state.reset_progress();
746 state.progress(Some(0)).unwrap();
747 let cancel = CancelToken::default();
748 let mut budget = WorkBudget::new();
749 for _ in 0..65_536 {
750 budget.step(&cancel).unwrap();
751 }
752 assert!(budget.step(&cancel).is_err());
753 WORK_LIMIT.with(|limit| limit.set(DECODE_WORK_LIMIT));
755 let mut budget = WorkBudget::new();
756 budget.started = budget
757 .started
758 .checked_sub(Duration::from_secs(11))
759 .expect("the clock reaches back 11 s");
760 assert!(budget.step(&cancel).is_err());
761 cancel.cancel();
762 assert_eq!(WorkBudget::new().step(&cancel), Err(DecodeError::Cancelled));
763 }
764 #[test]
765 fn eagain_drains_and_retries_the_same_packet_until_accepted() {
766 let mut actions = Vec::new();
767 let mut sends = 0;
768 submit_packet(
769 |drain| {
770 actions.push(drain);
771 if drain {
772 return Ok(true);
773 }
774 sends += 1;
775 Ok(sends == 3)
776 },
777 &mut WorkBudget::new(),
778 &CancelToken::default(),
779 )
780 .unwrap();
781 assert_eq!(actions, [false, true, false, true, false]);
782 assert!(
783 submit_packet(
784 |_| Ok(false),
785 &mut WorkBudget::new(),
786 &CancelToken::default()
787 )
788 .is_err()
789 );
790 assert!(submit_packet(Ok, &mut WorkBudget::new(), &CancelToken::default()).is_err());
791 let cancel = CancelToken::default();
792 let result = submit_packet(
793 |drain| {
794 if drain {
795 cancel.cancel();
796 }
797 Ok(drain)
798 },
799 &mut WorkBudget::new(),
800 &cancel,
801 );
802 assert_eq!(result, Err(DecodeError::Cancelled));
803 }
804
805 #[test]
806 fn the_time_limit_runs_from_the_last_step_forward_and_the_step_limit_from_the_last_frame() {
807 let cancel = CancelToken::default();
808 let limit = Duration::from_secs(10);
809 WORK_LIMIT.with(|cell| cell.set(limit));
810 VIRTUAL_CLOCK.with(|clock| clock.set(Some(Duration::ZERO)));
811 let advance = |by: Duration| {
812 VIRTUAL_CLOCK.with(|clock| clock.set(clock.get().map(|now| now + by)));
813 };
814 let mut budget = WorkBudget::new();
816 budget.step(&cancel).unwrap();
817 advance(Duration::from_secs(11));
818 budget.advanced();
819 budget.step(&cancel).expect("a slow read that returned");
820 advance(Duration::from_secs(11));
822 assert!(budget.step(&cancel).is_err());
823 WORK_STEPS.with(|cell| cell.set(100));
825 let mut budget = WorkBudget::new();
826 for _ in 0..100 {
827 budget.step(&cancel).unwrap();
828 budget.advanced();
829 }
830 assert!(budget.step(&cancel).is_err());
831 WORK_STEPS.with(|cell| cell.set(DECODE_WORK_STEPS));
832 VIRTUAL_CLOCK.with(|clock| clock.set(None));
833 }
834
835 #[test]
836 fn an_accepted_packet_restarts_the_time_limit() {
837 let cancel = CancelToken::default();
838 WORK_LIMIT.with(|cell| cell.set(Duration::from_secs(10)));
839 VIRTUAL_CLOCK.with(|clock| clock.set(Some(Duration::ZERO)));
840 let mut budget = WorkBudget::new();
841 submit_packet(
842 |_| {
843 VIRTUAL_CLOCK.with(|clock| {
845 clock.set(clock.get().map(|now| now + Duration::from_secs(11)));
846 });
847 Ok(true)
848 },
849 &mut budget,
850 &cancel,
851 )
852 .unwrap();
853 budget
854 .step(&cancel)
855 .expect("the accepted packet was a step forward");
856 VIRTUAL_CLOCK.with(|clock| clock.set(None));
857 }
858}