Skip to main content

vtcode_commons/
async_utils.rs

1//! Async utility functions.
2//!
3//! Retry/backoff belongs to [`crate::retry::RetryPolicy`] (with the HTTP
4//! wrappers in [`crate::http`]); do not add a local retry loop here.
5//! `retry_with_backoff` is kept only as a deprecated compatibility shim for
6//! downstream users of the published crate.
7
8use anyhow::{Context, Result};
9use std::future::Future;
10use std::time::Duration;
11use tokio::io::AsyncReadExt;
12use tokio::time::timeout;
13
14pub const DEFAULT_ASYNC_TIMEOUT: Duration = Duration::from_secs(30);
15pub const SHORT_ASYNC_TIMEOUT: Duration = Duration::from_secs(5);
16pub const LONG_ASYNC_TIMEOUT: Duration = Duration::from_secs(300);
17
18/// Execute a future with a timeout and context
19pub async fn with_timeout<F, T>(fut: F, duration: Duration, context: &str) -> Result<T>
20where
21    F: Future<Output = T>,
22{
23    match timeout(duration, fut).await {
24        Ok(result) => Ok(result),
25        Err(_) => anyhow::bail!("Operation timed out after {duration:?}: {context}"),
26    }
27}
28
29/// Execute a future with the default timeout
30pub async fn with_default_timeout<F, T>(fut: F, context: &str) -> Result<T>
31where
32    F: Future<Output = T>,
33{
34    with_timeout(fut, DEFAULT_ASYNC_TIMEOUT, context).await
35}
36
37/// Execute a future with a short timeout
38pub async fn with_short_timeout<F, T>(fut: F, context: &str) -> Result<T>
39where
40    F: Future<Output = T>,
41{
42    with_timeout(fut, SHORT_ASYNC_TIMEOUT, context).await
43}
44
45/// Execute a future with a long timeout
46pub async fn with_long_timeout<F, T>(fut: F, context: &str) -> Result<T>
47where
48    F: Future<Output = T>,
49{
50    with_timeout(fut, LONG_ASYNC_TIMEOUT, context).await
51}
52
53/// Retry an operation with exponential backoff.
54///
55/// Kept for source compatibility with the published crate. New code should use
56/// [`crate::retry::RetryPolicy`], which classifies errors and applies bounded,
57/// jittered delays; this helper retries every error unconditionally.
58#[deprecated(note = "use vtcode_commons::retry::RetryPolicy (or http::send_with_retry for HTTP)")]
59pub async fn retry_with_backoff<F, Fut, T>(
60    mut op: F,
61    max_retries: usize,
62    initial_delay: Duration,
63    context: &str,
64) -> Result<T>
65where
66    F: FnMut() -> Fut,
67    Fut: Future<Output = Result<T>>,
68{
69    let mut delay = initial_delay;
70    let mut last_error = None;
71
72    for i in 0..=max_retries {
73        match op().await {
74            Ok(result) => return Ok(result),
75            Err(e) => {
76                last_error = Some(e);
77                if i < max_retries {
78                    tokio::time::sleep(delay).await;
79                    delay *= 2;
80                }
81            }
82        }
83    }
84
85    let err = last_error.unwrap_or_else(|| anyhow::anyhow!("Retry failed without error"));
86    Err(err).with_context(|| format!("Operation failed after {max_retries} retries: {context}"))
87}
88
89/// Sleep with context
90pub async fn sleep_with_context(duration: Duration, _context: &str) {
91    tokio::time::sleep(duration).await;
92}
93
94/// Run multiple futures and wait for all with a timeout
95pub async fn join_all_with_timeout<F, T>(futs: Vec<F>, duration: Duration, context: &str) -> Result<Vec<T>>
96where
97    F: Future<Output = T>,
98{
99    with_timeout(futures::future::join_all(futs), duration, context).await
100}
101
102/// Read exactly `len` bytes from an async reader without zero-initializing
103/// the buffer first.
104///
105/// This avoids the double-write overhead of `vec![0u8; len]` followed by
106/// `read_exact` — `read_buf` appends directly into the `Vec`'s spare capacity,
107/// so the zeroing pass is skipped. For large payloads this can yield
108/// measurable performance gains.
109///
110/// The returned `Vec` has exactly `len` initialized bytes.
111///
112/// This used to be an `unsafe` function that handed `read_exact` a
113/// `&mut [u8]` over uninitialized memory via `from_raw_parts_mut`. That was
114/// unsound: `tokio::io::ReadBuf::new(&mut [u8])` asserts the whole buffer is
115/// initialized, so a reader conforming to the `ReadBuf` contract would be
116/// entitled to read the (uninitialized) `[filled, initialized)` region. The
117/// `read_buf`-based implementation below is fully safe and keeps the same
118/// zero-overhead property, miri-clean by construction.
119///
120/// # Errors
121///
122/// Returns `io::ErrorKind::UnexpectedEof` if the reader reaches EOF before
123/// `len` bytes have been read.
124pub async fn read_exact_uninit<R>(reader: &mut R, len: usize) -> std::io::Result<Vec<u8>>
125where
126    R: tokio::io::AsyncRead + Unpin,
127{
128    let mut buf = Vec::with_capacity(len);
129    // `read_buf` fills the Vec's spare capacity without zero-initializing it,
130    // and is sound with respect to uninitialized memory by construction.
131    while buf.len() < len {
132        let n = reader.read_buf(&mut buf).await?;
133        if n == 0 {
134            return Err(std::io::Error::new(
135                std::io::ErrorKind::UnexpectedEof,
136                format!("unexpected EOF before reading {len} bytes (got {})", buf.len()),
137            ));
138        }
139    }
140    Ok(buf)
141}
142
143#[cfg(test)]
144mod tests {
145    use super::*;
146
147    #[tokio::test]
148    async fn read_exact_uninit_round_trips_known_payload() {
149        let payload: Vec<u8> = (0..64u8).collect();
150        let mut reader = std::io::Cursor::new(payload.clone());
151        let got = read_exact_uninit(&mut reader, payload.len()).await.expect("read full payload");
152        assert_eq!(got, payload);
153    }
154
155    #[tokio::test]
156    async fn read_exact_uninit_reads_across_multiple_poll_reads() {
157        // A payload larger than a single `read_buf` is likely to require
158        // several poll_read calls; the loop must still accumulate correctly.
159        let payload: Vec<u8> = (0..2000u32).map(|i| u8::try_from(i % 256).unwrap_or_default()).collect();
160        let mut reader = std::io::Cursor::new(payload.clone());
161        let got = read_exact_uninit(&mut reader, payload.len()).await.expect("read full payload");
162        assert_eq!(got, payload);
163    }
164
165    #[tokio::test]
166    async fn read_exact_uninit_returns_unexpected_eof_on_short_read() {
167        let payload = b"only ten!".to_vec();
168        let mut reader = std::io::Cursor::new(payload);
169        let err = read_exact_uninit(&mut reader, 64).await.expect_err("short read must error");
170        assert_eq!(err.kind(), std::io::ErrorKind::UnexpectedEof);
171    }
172
173    #[tokio::test]
174    async fn read_exact_uninit_returns_unexpected_eof_on_empty_reader() {
175        let mut reader = std::io::Cursor::new(Vec::<u8>::new());
176        let err = read_exact_uninit(&mut reader, 1).await.expect_err("empty reader must error");
177        assert_eq!(err.kind(), std::io::ErrorKind::UnexpectedEof);
178    }
179
180    #[tokio::test]
181    async fn read_exact_uninit_zero_len_returns_empty_vec() {
182        let mut reader = std::io::Cursor::new(Vec::<u8>::new());
183        let got = read_exact_uninit(&mut reader, 0).await.expect("zero-length read must succeed");
184        assert!(got.is_empty());
185    }
186}