LCOV - code coverage report
Current view: top level - libs/utils/src - timeout.rs (source / functions) Coverage Total Hit
Test: c639aa5f7ab62b43d647b10f40d15a15686ce8a9.info Lines: 84.6 % 13 11
Test Date: 2024-02-12 20:26:03 Functions: 57.1 % 42 24

            Line data    Source code
       1              : use std::time::Duration;
       2              : 
       3              : use tokio_util::sync::CancellationToken;
       4              : 
       5            0 : #[derive(thiserror::Error, Debug)]
       6              : pub enum TimeoutCancellableError {
       7              :     #[error("Timed out")]
       8              :     Timeout,
       9              :     #[error("Cancelled")]
      10              :     Cancelled,
      11              : }
      12              : 
      13              : /// Wrap [`tokio::time::timeout`] with a CancellationToken.
      14              : ///
      15              : /// This wrapper is appropriate for any long running operation in a task
      16              : /// that ought to respect a CancellationToken (which means most tasks).
      17              : ///
      18              : /// The only time you should use a bare tokio::timeout is when the future `F`
      19              : /// itself respects a CancellationToken: otherwise, always use this wrapper
      20              : /// with your CancellationToken to ensure that your task does not hold up
      21              : /// graceful shutdown.
      22        55675 : pub async fn timeout_cancellable<F>(
      23        55675 :     duration: Duration,
      24        55675 :     cancel: &CancellationToken,
      25        55675 :     future: F,
      26        55675 : ) -> Result<F::Output, TimeoutCancellableError>
      27        55675 : where
      28        55675 :     F: std::future::Future,
      29        55675 : {
      30      1593879 :     tokio::select!(
      31        55657 :         r = tokio::time::timeout(duration, future) => {
      32            0 :             r.map_err(|_| TimeoutCancellableError::Timeout)
      33              : 
      34              :         },
      35              :         _ = cancel.cancelled() => {
      36              :             Err(TimeoutCancellableError::Cancelled)
      37              : 
      38              :         }
      39              :     )
      40        55665 : }
        

Generated by: LCOV version 2.1-beta