pausable-tokio 1.52.1

A fork of tokio that adds a runtime-controllable pause/resume primitive on its clock. Drop-in replacement for tokio with a few extra methods on the Builder and Runtime types.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
#![cfg_attr(not(feature = "rt"), allow(dead_code))]

//! Source of time abstraction.
//!
//! By default, `std::time::Instant::now()` is used. However, when the
//! `test-util` feature flag is enabled, the values returned for `now()` are
//! configurable.

cfg_not_test_util! {
    use crate::time::Instant;
    use std::sync::Arc;
    use std::sync::atomic::Ordering;
    use std::time::Duration;
    use pausable_clock::PausableClock;

    /// A source of `Instant::now()` that can optionally be paused.
    ///
    /// When constructed via `Clock::new`, the clock is a no-op wrapper around
    /// [`std::time::Instant::now`]. When constructed via
    /// [`Clock::new_pausable`] (indirectly through the
    /// [`Builder::pausable_time`](crate::runtime::Builder::pausable_time)
    /// runtime builder method) the clock is backed by a
    /// [`pausable_clock::PausableClock`] and the runtime's notion of time can
    /// be paused and resumed by calling [`Runtime::pause`](crate::runtime::Runtime::pause)
    /// and [`Runtime::resume`](crate::runtime::Runtime::resume).
    #[derive(Debug, Clone)]
    pub(crate) struct Clock {
        pausable: bool,
        pausing_clock: Arc<PausableClock>,
    }

    pub(crate) fn now() -> Instant {
        Instant::from_std(std::time::Instant::now())
    }

    impl Clock {
        /// Returns `true` when the `test-util` feature is enabled. This is used
        /// by the time driver to know whether it should call `advance` (which
        /// is a test-only concept) or `wait_for_resume`.
        #[allow(dead_code)]
        pub(crate) fn is_test() -> bool {
            false
        }

        pub(crate) fn new(_enable_pausing: bool, _start_paused: bool) -> Clock {
            Clock {
                pausable: false,
                pausing_clock: Arc::new(PausableClock::default()),
            }
        }

        pub(crate) fn new_pausable(start_paused: bool, elapsed_time: Duration) -> Clock {
            Clock {
                pausable: true,
                pausing_clock: Arc::new(PausableClock::new(elapsed_time, start_paused)),
            }
        }

        /// Returns true when this clock can be paused/resumed.
        pub(crate) fn pausable(&self) -> bool {
            self.pausable
        }

        pub(crate) fn now(&self) -> Instant {
            if self.pausable {
                // `PausableInstant` converts into `std::time::Instant` via
                // `From`. The conversion preserves the pausable clock's view
                // of time so that the runtime sees the paused instant.
                Instant::from_std(std::time::Instant::from(self.pausing_clock.now()))
            } else {
                now()
            }
        }

        /// Returns the number of milliseconds elapsed since the pausable clock
        /// was created. Panics if the clock is not pausable.
        pub(crate) fn elapsed_millis(&self) -> u64 {
            if self.pausable {
                self.pausing_clock.now().elapsed_millis()
            } else {
                panic!("elapsed_millis is only supported on pausable clocks")
            }
        }

        pub(crate) fn is_paused(&self) -> bool {
            if self.pausable {
                self.pausing_clock.is_paused()
            } else {
                false
            }
        }

        pub(crate) fn is_paused_ordered(&self, ordering: Ordering) -> bool {
            if self.pausable {
                self.pausing_clock.is_paused_ordered(ordering)
            } else {
                false
            }
        }

        pub(crate) fn pause(&self) -> bool {
            if self.pausable {
                self.pausing_clock.pause()
            } else {
                panic!("this runtime was not configured to be pausable. \
                    Use `Builder::pausable_time` to enable pausable time.");
            }
        }

        pub(crate) fn resume(&self) -> bool {
            if self.pausable {
                self.pausing_clock.resume()
            } else {
                panic!("this runtime was not configured to be pausable. \
                    Use `Builder::pausable_time` to enable pausable time.");
            }
        }

        /// Runs `action` while preventing the clock from being paused. If the
        /// clock is paused when this is called, the call blocks until the
        /// clock is resumed.
        pub(crate) fn run_unpausable<T, F>(&self, action: F) -> T
        where
            F: FnOnce() -> T,
        {
            if self.pausable {
                self.pausing_clock.run_unpausable(action)
            } else {
                action()
            }
        }

        /// Runs `action` while preventing the clock from being resumed. If the
        /// clock is running when this is called, the call blocks until the
        /// clock is paused.
        pub(crate) fn run_unresumable<T, F>(&self, action: F) -> T
        where
            F: FnOnce() -> T,
        {
            if self.pausable {
                self.pausing_clock.run_unresumable(action)
            } else {
                // Running an unresumable action on a non-pausable clock would
                // otherwise block forever since the clock can never be paused.
                unreachable!(
                    "run_unresumable called on non-pausable clock; this would block forever"
                );
            }
        }

        /// Runs `action` atomically if the clock is currently resumed,
        /// returning `None` if the clock is paused.
        pub(crate) fn run_if_resumed<T, F>(&self, action: F) -> Option<T>
        where
            F: FnOnce() -> T,
        {
            if self.pausable {
                self.pausing_clock.run_if_resumed(action)
            } else {
                Some(action())
            }
        }

        /// Runs `action` atomically if the clock is currently paused,
        /// returning `None` if the clock is resumed.
        pub(crate) fn run_if_paused<T, F>(&self, action: F) -> Option<T>
        where
            F: FnOnce() -> T,
        {
            if self.pausable {
                self.pausing_clock.run_if_paused(action)
            } else {
                None
            }
        }

        /// Blocks the current thread until the clock is resumed. If the clock
        /// is not currently paused, or not pausable, this returns immediately.
        pub(crate) fn wait_for_resume(&self) {
            if self.pausable {
                self.pausing_clock.wait_for_resume();
            }
        }

        /// Blocks the current thread until the clock is paused. If the clock is
        /// not pausable, this does nothing.
        pub(crate) fn wait_for_pause(&self) {
            if self.pausable {
                self.pausing_clock.wait_for_pause();
            }
        }
    }
}

cfg_test_util! {
    use crate::time::{Duration, Instant};
    use crate::loom::sync::Mutex;
    use crate::loom::sync::atomic::Ordering;
    use std::sync::atomic::AtomicBool as StdAtomicBool;

    cfg_rt! {
        #[track_caller]
        fn with_clock<R>(f: impl FnOnce(Option<&Clock>) -> Result<R, &'static str>) -> R {
            use crate::runtime::Handle;

            let res = match Handle::try_current() {
                Ok(handle) => f(Some(handle.inner.driver().clock())),
                Err(ref e) if e.is_missing_context() => f(None),
                Err(_) => panic!("{}", crate::util::error::THREAD_LOCAL_DESTROYED_ERROR),
            };

            match res {
                Ok(ret) => ret,
                Err(msg) => panic!("{}", msg),
            }
        }
    }

    cfg_not_rt! {
        #[track_caller]
        fn with_clock<R>(f: impl FnOnce(Option<&Clock>) -> Result<R, &'static str>) -> R {
            match f(None) {
                Ok(ret) => ret,
                Err(msg) => panic!("{}", msg),
            }
        }
    }

    /// A handle to a source of time.
    #[derive(Debug)]
    pub(crate) struct Clock {
        inner: Mutex<Inner>,
    }

    // Used to track if the clock was ever paused. This is an optimization to
    // avoid touching the mutex if `test-util` was accidentally enabled in
    // release mode.
    //
    // A static is used so we can avoid accessing the thread-local as well. The
    // `std` AtomicBool is used directly because loom does not support static
    // atomics.
    static DID_PAUSE_CLOCK: StdAtomicBool = StdAtomicBool::new(false);

    #[derive(Debug)]
    struct Inner {
        /// True if the ability to pause time is enabled.
        enable_pausing: bool,

        /// Instant to use as the clock's base instant.
        base: std::time::Instant,

        /// Instant at which the clock was last unfrozen.
        unfrozen: Option<std::time::Instant>,

        /// Number of `inhibit_auto_advance` calls still in effect.
        auto_advance_inhibit_count: usize,
    }

    /// Pauses time.
    ///
    /// The current value of `Instant::now()` is saved and all subsequent calls
    /// to `Instant::now()` will return the saved value. The saved value can be
    /// changed by [`advance`] or by the time auto-advancing once the runtime
    /// has no work to do. This only affects the `Instant` type in Tokio, and
    /// the `Instant` in std continues to work as normal.
    ///
    /// Pausing time requires the `current_thread` Tokio runtime. This is the
    /// default runtime used by `#[tokio::test]`. The runtime can be initialized
    /// with time in a paused state using the `Builder::start_paused` method.
    ///
    /// For cases where time is immediately paused, it is better to pause
    /// the time using the `main` or `test` macro:
    /// ```
    /// #[tokio::main(flavor = "current_thread", start_paused = true)]
    /// async fn main() {
    ///    println!("Hello world");
    /// }
    /// ```
    ///
    /// # Panics
    ///
    /// Panics if time is already frozen or if called from outside of a
    /// `current_thread` Tokio runtime.
    ///
    /// # Auto-advance
    ///
    /// If time is paused and the runtime has no work to do, the clock is
    /// auto-advanced to the next pending timer. This means that [`Sleep`] or
    /// other timer-backed primitives can cause the runtime to advance the
    /// current time when awaited.
    ///
    /// # Preventing auto-advance
    ///
    /// In some testing scenarios, you may want to keep the clock paused without
    /// auto-advancing, even while waiting for I/O or other asynchronous operations.
    /// This can be achieved by using [`spawn_blocking`] to wrap your I/O operations.
    ///
    /// When a blocking task is running, the clock's auto-advance is temporarily
    /// inhibited. This allows you to wait for I/O to complete while keeping the
    /// paused clock stationary:
    ///
    /// ```ignore
    /// use tokio::time::{Duration, Instant};
    /// use tokio::task;
    ///
    /// #[tokio::test(start_paused = true)]
    /// async fn test_with_io() {
    ///     let start = Instant::now();
    ///
    ///     // The clock will NOT auto-advance while this blocking task runs
    ///     let result = task::spawn_blocking(|| {
    ///         // Perform I/O operations here
    ///         std::thread::sleep(std::time::Duration::from_millis(10));
    ///         42
    ///     }).await.unwrap();
    ///
    ///     // Time has not advanced
    ///     assert_eq!(start.elapsed(), Duration::ZERO);
    /// }
    /// ```
    ///
    /// [`Sleep`]: crate::time::Sleep
    /// [`advance`]: crate::time::advance
    /// [`spawn_blocking`]: crate::task::spawn_blocking
    #[track_caller]
    pub fn pause() {
        with_clock(|maybe_clock| {
            match maybe_clock {
                Some(clock) => clock.pause(),
                None => Err("time cannot be frozen from outside the Tokio runtime"),
            }
        });
    }

    /// Resumes time.
    ///
    /// Clears the saved `Instant::now()` value. Subsequent calls to
    /// `Instant::now()` will return the value returned by the system call.
    ///
    /// # Panics
    ///
    /// Panics if time is not frozen or if called from outside of the Tokio
    /// runtime.
    #[track_caller]
    pub fn resume() {
        with_clock(|maybe_clock| {
            let clock = match maybe_clock {
                Some(clock) => clock,
                None => return Err("time cannot be frozen from outside the Tokio runtime"),
            };

            let mut inner = clock.inner.lock();

            if inner.unfrozen.is_some() {
                return Err("time is not frozen");
            }

            inner.unfrozen = Some(std::time::Instant::now());
            Ok(())
        });
    }

    /// Advances time.
    ///
    /// Increments the saved `Instant::now()` value by `duration`. Subsequent
    /// calls to `Instant::now()` will return the result of the increment.
    ///
    /// This function will make the current time jump forward by the given
    /// duration in one jump. This means that all `sleep` calls with a deadline
    /// before the new time will immediately complete "at the same time", and
    /// the runtime is free to poll them in any order.  Additionally, this
    /// method will not wait for the `sleep` calls it advanced past to complete.
    /// If you want to do that, you should instead call [`sleep`] and rely on
    /// the runtime's auto-advance feature.
    ///
    /// Note that calls to `sleep` are not guaranteed to complete the first time
    /// they are polled after a call to `advance`. For example, this can happen
    /// if the runtime has not yet touched the timer driver after the call to
    /// `advance`. However if they don't, the runtime will poll the task again
    /// shortly.
    ///
    /// # When to use `sleep` instead
    ///
    /// **Important:** `advance` is designed for testing scenarios where you want to
    /// instantly jump forward in time. However, it has limitations that make it
    /// unsuitable for certain use cases:
    ///
    /// - **Forcing timeouts:** If you want to reliably trigger a timeout, prefer
    ///   using [`sleep`] with auto-advance rather than `advance`. The `advance`
    ///   function jumps time forward but doesn't guarantee that all timers will be
    ///   processed before your code continues.
    ///
    /// - **Simulating freezes:** If you're trying to simulate a scenario where the
    ///   program freezes and then resumes, the batch behavior of `advance` may not
    ///   produce the expected results. All timers that expire during the advance
    ///   complete simultaneously.
    ///
    /// For most testing scenarios where you want to wait for a duration to pass
    /// and have all timers fire in order, use [`sleep`] instead:
    ///
    /// ```ignore
    /// use tokio::time::{self, Duration};
    ///
    /// #[tokio::test(start_paused = true)]
    /// async fn test_timeout_reliable() {
    ///     // Use sleep with auto-advance for reliable timeout testing
    ///     time::sleep(Duration::from_secs(5)).await;
    ///     // All timers that were scheduled to fire within 5 seconds
    ///     // have now been processed in order
    /// }
    /// ```
    ///
    /// # Panics
    ///
    /// Panics if any of the following conditions are met:
    ///
    /// - The clock is not frozen, which means that you must
    ///   call [`pause`] before calling this method.
    /// - If called outside of the Tokio runtime.
    /// - If the input `duration` is too large (such as [`Duration::MAX`])
    ///   to be safely added to the current time without causing an overflow.
    ///
    /// # Caveats
    ///
    /// Using a very large `duration` is not recommended,
    /// as it may cause panicking due to overflow.
    ///
    /// # Auto-advance
    ///
    /// If the time is paused and there is no work to do, the runtime advances
    /// time to the next timer. See [`pause`](pause#auto-advance) for more
    /// details.
    ///
    /// [`sleep`]: fn@crate::time::sleep
    pub async fn advance(duration: Duration) {
        with_clock(|maybe_clock| {
            let clock = match maybe_clock {
                Some(clock) => clock,
                None => return Err("time cannot be frozen from outside the Tokio runtime"),
            };

            clock.advance(duration)
        });

        crate::task::yield_now().await;
    }

    /// Returns the current instant, factoring in frozen time.
    pub(crate) fn now() -> Instant {
        if !DID_PAUSE_CLOCK.load(Ordering::Acquire) {
            return Instant::from_std(std::time::Instant::now());
        }

        with_clock(|maybe_clock| {
            Ok(if let Some(clock) = maybe_clock {
                clock.now()
            } else {
                Instant::from_std(std::time::Instant::now())
            })
        })
    }

    impl Clock {
        /// Returns a new `Clock` instance that uses the current execution context's
        /// source of time.
        pub(crate) fn new(enable_pausing: bool, start_paused: bool) -> Clock {
            let now = std::time::Instant::now();

            let clock = Clock {
                inner: Mutex::new(Inner {
                    enable_pausing,
                    base: now,
                    unfrozen: Some(now),
                    auto_advance_inhibit_count: 0,
                }),
            };

            if start_paused {
                if let Err(msg) = clock.pause() {
                    panic!("{}", msg);
                }
            }

            clock
        }

        pub(crate) fn pause(&self) -> Result<(), &'static str> {
            let mut inner = self.inner.lock();

            if !inner.enable_pausing {
                return Err("`time::pause()` requires the `current_thread` Tokio runtime. \
                        This is the default Runtime used by `#[tokio::test].");
            }

            // Track that we paused the clock
            DID_PAUSE_CLOCK.store(true, Ordering::Release);

            let elapsed = match inner.unfrozen.as_ref() {
                Some(v) => v.elapsed(),
                None => return Err("time is already frozen")
            };
            inner.base += elapsed;
            inner.unfrozen = None;

            Ok(())
        }

        /// Temporarily stop auto-advancing the clock (see `tokio::time::pause`).
        pub(crate) fn inhibit_auto_advance(&self) {
            let mut inner = self.inner.lock();
            inner.auto_advance_inhibit_count += 1;
        }

        pub(crate) fn allow_auto_advance(&self) {
            let mut inner = self.inner.lock();
            inner.auto_advance_inhibit_count -= 1;
        }

        pub(crate) fn can_auto_advance(&self) -> bool {
            let inner = self.inner.lock();
            inner.unfrozen.is_none() && inner.auto_advance_inhibit_count == 0
        }

        pub(crate) fn advance(&self, duration: Duration) -> Result<(), &'static str> {
            let mut inner = self.inner.lock();

            if inner.unfrozen.is_some() {
                return Err("time is not frozen");
            }

            inner.base += duration;
            Ok(())
        }

        pub(crate) fn now(&self) -> Instant {
            let inner = self.inner.lock();

            let mut ret = inner.base;

            if let Some(unfrozen) = inner.unfrozen {
                ret += unfrozen.elapsed();
            }

            Instant::from_std(ret)
        }

        // Extra methods that mirror the `cfg_not_test_util` variant so that
        // `Runtime` can expose a uniform pausability API regardless of the
        // `test-util` feature. These generally defer to the existing
        // test-util primitives or are no-ops where no equivalent exists.

        #[allow(dead_code)]
        pub(crate) fn is_test() -> bool {
            true
        }

        #[allow(dead_code)]
        pub(crate) fn new_pausable(start_paused: bool, _elapsed_time: Duration) -> Clock {
            // When `test-util` is enabled we always run the test clock with
            // pausability enabled so that `Runtime::pause` / `Runtime::resume`
            // are available in tests.
            Self::new(true, start_paused)
        }

        #[allow(dead_code)]
        pub(crate) fn pausable(&self) -> bool {
            let inner = self.inner.lock();
            inner.enable_pausing
        }

        #[allow(dead_code)]
        pub(crate) fn elapsed_millis(&self) -> u64 {
            let inner = self.inner.lock();
            let mut ret = inner.base;
            if let Some(unfrozen) = inner.unfrozen {
                ret += unfrozen.elapsed();
            }
            ret.duration_since(inner.base - inner.base.elapsed())
                .as_millis() as u64
        }

        pub(crate) fn is_paused_ordered(&self, _ordering: crate::loom::sync::atomic::Ordering) -> bool {
            self.is_paused()
        }

        // The trait's public `pause()` returns `Result<(), &'static str>` to
        // match historical behavior; the runtime-level `pause` simply returns
        // whether the call succeeded.
        #[allow(dead_code)]
        pub(crate) fn try_pause(&self) -> bool {
            match self.pause() {
                Ok(()) => true,
                Err(_) => false,
            }
        }

        #[allow(dead_code)]
        pub(crate) fn try_resume(&self) -> bool {
            let mut inner = self.inner.lock();
            if inner.unfrozen.is_some() {
                return false;
            }
            inner.unfrozen = Some(std::time::Instant::now());
            true
        }

        pub(crate) fn is_paused(&self) -> bool {
            let inner = self.inner.lock();
            inner.unfrozen.is_none()
        }

        /// No-op stub for compatibility with the pausable_clock-backed
        /// implementation. In test mode, no separate `run_unpausable` mechanism
        /// is needed because `time::pause` is controlled by the user directly.
        pub(crate) fn run_unpausable<T, F>(&self, action: F) -> T
        where
            F: FnOnce() -> T,
        {
            action()
        }

        #[allow(dead_code)]
        pub(crate) fn run_unresumable<T, F>(&self, _action: F) -> T
        where
            F: FnOnce() -> T,
        {
            unreachable!("run_unresumable is not supported when `test-util` is enabled")
        }

        #[allow(dead_code)]
        pub(crate) fn run_if_resumed<T, F>(&self, action: F) -> Option<T>
        where
            F: FnOnce() -> T,
        {
            if self.is_paused() {
                None
            } else {
                Some(action())
            }
        }

        #[allow(dead_code)]
        pub(crate) fn run_if_paused<T, F>(&self, action: F) -> Option<T>
        where
            F: FnOnce() -> T,
        {
            if self.is_paused() {
                Some(action())
            } else {
                None
            }
        }

        #[allow(dead_code)]
        pub(crate) fn wait_for_resume(&self) {
            // The test-util clock has no blocking notification for resume.
            // The time driver uses `can_auto_advance` + `advance` instead of
            // calling `wait_for_resume` when the `test-util` feature is
            // enabled, so this should never be reached.
            unreachable!("wait_for_resume is not supported when `test-util` is enabled")
        }

        #[allow(dead_code)]
        pub(crate) fn wait_for_pause(&self) {
            unreachable!("wait_for_pause is not supported when `test-util` is enabled")
        }
    }
}