vtcode_commons/
async_utils.rs1use 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
18pub 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
29pub 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
37pub 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
45pub 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#[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
89pub async fn sleep_with_context(duration: Duration, _context: &str) {
91 tokio::time::sleep(duration).await;
92}
93
94pub 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
102pub 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 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 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}