context_async/lib.rs
1#![cfg_attr(docsrs, feature(doc_auto_cfg))]
2#![forbid(unsafe_code)]
3
4//! This lib provide an trait [`Context`] and a [`Timer`] to control async function.
5//!
6//! ## Example
7//!
8//! Here is a simple example. We use [`Timer`] to control an async function
9//! to finish in 5 seconds.
10//!
11//! ```rust
12//! use std::time;
13//! use context_async::{Context, Timer};
14//!
15//! async fn a_heavy_async_function(a: u8) -> bool {
16//! return true;
17//! }
18//!
19//! # tokio_test::block_on(async {
20//! let timer = Timer::with_timeout(time::Duration::from_secs(5));
21//!
22//! let _ = timer.handle(a_heavy_async_function(0)).await;
23//!
24//! // or:
25//!
26//! use context_async::With;
27//! let _ = a_heavy_async_function(0).with(&timer).await;
28//! # });
29//! ```
30//!
31//! [`Timer`] implements [`Context`], you can pass a [`Context`] to your async function:
32//!
33//! ```rust
34//!
35//! use std::time;
36//! use context_async::{Context, Error, Timer, With};
37//!
38//! async fn a_heavy_async_function(a: u8) -> bool {
39//! return true;
40//! }
41//!
42//! async fn my_function<Ctx: Context>(ctx: Ctx) -> Result<bool, Error> {
43//! a_heavy_async_function(0)
44//! .with(ctx)
45//! .await
46//! }
47//!
48//! # tokio_test::block_on(async {
49//! let timer = Timer::with_timeout(time::Duration::from_secs(5));
50//! let _ = my_function(&timer).await;
51//! # })
52//!
53//! ```
54//!
55//! ## Error
56//!
57//! [`Context`] returns [`Error`], one of [`Error::ContextCancelled`] or [`Error::ContextTimeout`].
58//!
59//! ## Features
60//! - `actix-web-from-request`: implement actix-web::FromRequest for [`Timer`].
61//! - `name`: create a name for each [`Context`].
62//! - `tracing`: enable `tracing` and do `tracing::trace!(...)` logging.
63
64mod timer;
65mod context;
66mod error;
67mod with;
68#[cfg(feature = "name")]
69mod name;
70
71pub use timer::*;
72pub use context::*;
73pub use error::*;
74pub use with::*;
75#[cfg(feature = "name")]
76pub use name::*;
77
78/// Re-export [`async_trait`] crate.
79pub use async_trait::async_trait;
80
81#[doc(hidden)]
82pub struct TimeChecker(tokio::time::Instant);
83
84impl Default for TimeChecker {
85 fn default() -> Self {
86 Self::new()
87 }
88}
89
90impl TimeChecker {
91 pub fn new() -> Self {
92 Self(tokio::time::Instant::now())
93 }
94
95 pub fn not_exceed(&self, duration: tokio::time::Duration) -> bool {
96 let diff = tokio::time::Instant::now() - self.0;
97
98 diff < duration
99 }
100}