expression

gRPC: model an elapsed local handler deadline

Wrap cooperative asynchronous work in a local timeout. On expiry the owned inner future is dropped. Mapping the elapsed error to a gRPC status is an application decision in this example; real transport status behavior must be tested separately. Tokio cannot preempt synchronous work that never yields. Run in the accompanying Cargo project. Expected stdout (not executed): deadline: true Common mistake: Assuming timeouts undo an already committed write or preempt arbitrary CPU work.

Formal Syntax & Structure

rust syntaxrust
timeout(budget, work).await.map_err(|_| Status::deadline_exceeded(...))

Working Example

Example Snippetrust
#[tokio::main(flavor = "current_thread", start_paused = true)]async fn main() {    use tokio::time::{timeout, sleep, Duration};    let result = timeout(Duration::from_millis(5), async {        sleep(Duration::from_millis(50)).await;        7_u64    }).await.map_err(|_| tonic::Status::deadline_exceeded("local budget elapsed"));    println!("deadline: {}", result.unwrap_err().code() == tonic::Code::DeadlineExceeded);}
Rust Reference