use std::{
future::Future,
pin::Pin,
time::{Duration, Instant},
};
use anyhow::Result;
use async_trait::async_trait;
use eventsource_stream::{Event, EventStreamError, Eventsource};
use futures_util::{Stream, StreamExt as _};
use reqwest::{
StatusCode,
header::{ACCEPT, CONTENT_ENCODING, CONTENT_TYPE, HeaderMap, HeaderName, HeaderValue},
};
use serde::{Serialize, de::DeserializeOwned};
use tokio_util::bytes::Bytes;
use tracing::{debug, info};
use crate::auth::{AuthedClient, Token};
use crate::compress::{compress, encoding_for};
use crate::error::{LlmError, LlmErrorKind};
pub use crate::retry_policy::RetryPolicy;
use crate::stream_driver::{StreamMapper, drive_stream};
use crate::streaming::collect;
use crate::{
retry_policy::retry_after_header,
types::{
ChatRequest, ChatResponse, ChatResponseStream, DEFAULT_STREAM_IDLE_TIMEOUT_SECS, ModelSpec,
},
};
#[async_trait]
pub trait ChatClient: Send + Sync {
async fn stream_chat(&self, request: ChatRequest) -> Result<ChatResponseStream, LlmError>;
async fn chat(&self, request: ChatRequest) -> Result<ChatResponse, LlmError> {
collect(self.stream_chat(request).await?, |_| {}).await.into_result()
}
async fn list_models(&self) -> Result<Vec<ModelSpec>, LlmError> {
Err(LlmError::message(
LlmErrorKind::InvalidRequest,
"model listing is not supported by this provider",
))
}
}
pub async fn chat_with_tool_choice_fallback(
client: &dyn ChatClient,
request: ChatRequest,
) -> Result<ChatResponse, LlmError> {
let retry =
request.tool_choice.is_some().then(|| ChatRequest { tool_choice: None, ..request.clone() });
match (client.chat(request).await, retry) {
(Err(err), Some(retry)) if err.is_tool_choice_rejection() => {
info!("provider rejected tool_choice, retrying once without it: {err}");
client.chat(retry).await
}
(result, _) => result,
}
}
#[derive(Debug, Clone)]
pub struct Client {
base_url: String,
auth: AuthedClient,
headers: HeaderMap,
retry_policy: RetryPolicy,
stream_idle_timeout: Duration,
}
#[derive(Debug)]
pub struct ClientResponse {
pub status: StatusCode,
pub headers: HeaderMap,
pub body: String,
}
pub(crate) type RawSseStream = Pin<Box<dyn Stream<Item = Result<Event, LlmError>> + Send>>;
pub(crate) enum ClientSseResponse {
Stream(RawSseStream),
Error(ClientResponse),
}
#[derive(Clone)]
pub(crate) struct ProviderClient {
transport: Client,
classify: fn(ClientResponse) -> LlmError,
}
impl ProviderClient {
pub(crate) fn new(transport: Client, classify: fn(ClientResponse) -> LlmError) -> Self {
Self { transport, classify }
}
pub(crate) fn raw(&self) -> &Client {
&self.transport
}
pub(crate) fn base_url(&self) -> &str {
self.transport.base_url()
}
pub(crate) fn stream_idle_timeout(&self) -> Duration {
self.transport.stream_idle_timeout()
}
pub(crate) async fn post_json<Resp, Req>(
&self,
path: &str,
body: &Req,
) -> Result<Resp, LlmError>
where
Resp: DeserializeOwned,
Req: Serialize + ?Sized,
{
let resp = self.transport.post(path, body).await?;
self.decode_json(resp)
}
pub(crate) async fn get_json<Resp, Q>(&self, path: &str, query: &Q) -> Result<Resp, LlmError>
where
Resp: DeserializeOwned,
Q: Serialize + ?Sized,
{
let resp = self.transport.get(path, query).await?;
self.decode_json(resp)
}
pub(crate) async fn post_chunks<T, Req>(
&self,
path: &str,
body: &Req,
) -> Result<impl Stream<Item = Result<T, LlmError>> + Send + Unpin + 'static, LlmError>
where
T: DeserializeOwned + Send + 'static,
Req: Serialize + ?Sized,
{
let response = self.transport.post_sse(path, body).await?;
match response {
ClientSseResponse::Stream(stream) => Ok(decode_chunks(stream)),
ClientSseResponse::Error(resp) => Err(self.classify_error(resp)),
}
}
pub(crate) async fn post_stream<Req, M>(
&self,
path: &str,
body: &Req,
mapper: M,
) -> Result<ChatResponseStream, LlmError>
where
Req: Serialize + ?Sized,
M: StreamMapper,
M::Raw: DeserializeOwned,
{
let chunks = self.post_chunks(path, body).await?;
Ok(drive_stream(chunks, mapper))
}
fn decode_json<Resp: DeserializeOwned>(&self, resp: ClientResponse) -> Result<Resp, LlmError> {
if !resp.status.is_success() {
return Err(self.classify_error(resp));
}
Ok(serde_json::from_str(&resp.body)?)
}
fn classify_error(&self, resp: ClientResponse) -> LlmError {
let retry_after = retry_after_header(&resp.headers);
let mut err = (self.classify)(resp);
err.detail.retry_after = err.detail.retry_after.or(retry_after);
err
}
}
fn decode_chunks<T>(
events: RawSseStream,
) -> impl Stream<Item = Result<T, LlmError>> + Send + Unpin + 'static
where
T: DeserializeOwned + Send + 'static,
{
events
.take_while(|raw| std::future::ready(!matches!(raw, Ok(event) if event.data == "[DONE]")))
.filter_map(|raw| {
std::future::ready(match raw {
Ok(raw) => decode_json_event(&raw),
Err(err) => Some(Err(err)),
})
})
}
fn decode_json_event<T: DeserializeOwned>(raw: &Event) -> Option<Result<T, LlmError>> {
if raw.event == "keepalive" || raw.data.is_empty() {
return None;
}
Some(serde_json::from_str(&raw.data).map_err(|err| {
LlmError::malformed_response(format!(
"failed to parse SSE data as JSON for event {}: {err}",
raw.event
))
}))
}
pub fn with_idle_timeout<S, T>(raw: S, timeout: Duration) -> impl Stream<Item = Result<T, LlmError>>
where
S: Stream<Item = Result<T, LlmError>> + Unpin,
{
futures_util::stream::unfold(Some(raw), move |raw| async move {
let mut raw = raw?;
match tokio::time::timeout(timeout, raw.next()).await {
Err(_elapsed) => Some((
Err(LlmError::unexpected_eof(format!(
"stream idle for {}s with no data",
timeout.as_secs()
))),
None,
)),
Ok(Some(item)) => Some((item, Some(raw))),
Ok(None) => None,
}
})
}
fn sse_events<S, B>(bytes: S, idle_timeout: Duration) -> RawSseStream
where
S: Stream<Item = Result<B, LlmError>> + Send + Unpin + 'static,
B: AsRef<[u8]> + Send + 'static,
{
let stream = with_idle_timeout(bytes, idle_timeout).eventsource().map(|sse| match sse {
Ok(raw) => Ok(raw),
Err(EventStreamError::Transport(err)) => Err(err),
Err(err) => Err(LlmError::malformed_response(format!("SSE decode error: {err}"))),
});
Box::pin(stream)
}
impl Client {
pub fn new(base_url: impl Into<String>, auth: AuthedClient) -> Self {
Self {
base_url: base_url.into(),
auth,
headers: HeaderMap::new(),
retry_policy: RetryPolicy::default(),
stream_idle_timeout: Duration::from_secs(DEFAULT_STREAM_IDLE_TIMEOUT_SECS),
}
}
pub fn with_headers(mut self, headers: HeaderMap) -> Self {
self.headers = headers;
self
}
pub(crate) fn with_default_header(mut self, name: HeaderName, value: HeaderValue) -> Self {
self.headers.entry(name).or_insert(value);
self
}
pub fn with_retry_policy(mut self, retry_policy: RetryPolicy) -> Self {
self.retry_policy = retry_policy;
self
}
pub fn with_stream_idle_timeout(mut self, timeout: Duration) -> Self {
self.stream_idle_timeout = timeout;
self
}
pub fn stream_idle_timeout(&self) -> Duration {
self.stream_idle_timeout
}
pub(crate) fn base_url(&self) -> &str {
&self.base_url
}
pub(crate) fn auth(&self) -> &AuthedClient {
&self.auth
}
pub(crate) fn transport_headers(&self, token: Option<&Token>) -> Result<HeaderMap, LlmError> {
let mut headers = self.headers.clone();
if let Some(token) = token {
headers.extend(self.auth.headers(token)?);
}
Ok(headers)
}
pub async fn post<Req>(&self, path: &str, body: &Req) -> Result<ClientResponse, LlmError>
where
Req: Serialize + ?Sized,
{
self.send_json(path, body, None, read_response).await
}
pub async fn get<Q>(&self, path: &str, query: &Q) -> Result<ClientResponse, LlmError>
where
Q: Serialize + ?Sized,
{
let url = self.url(path);
self.send_with_retry(|http| http.get(url.clone()).query(query), &url, read_response).await
}
pub(crate) async fn post_sse<Req>(
&self,
path: &str,
body: &Req,
) -> Result<ClientSseResponse, LlmError>
where
Req: Serialize + ?Sized,
{
self.send_json(path, body, Some("text/event-stream"), |resp| async move {
if resp.status().is_success() {
let stream = sse_events(
resp.bytes_stream().map(|result| result.map_err(LlmError::sse_transport)),
self.stream_idle_timeout,
);
Ok(ClientSseResponse::Stream(stream))
} else {
read_response(resp).await.map(ClientSseResponse::Error)
}
})
.await
}
async fn send_json<Req, H, Fut, T>(
&self,
path: &str,
body: &Req,
accept: Option<&str>,
mut read: H,
) -> Result<T, LlmError>
where
Req: Serialize + ?Sized,
H: FnMut(reqwest::Response) -> Fut,
Fut: Future<Output = std::result::Result<T, reqwest::Error>>,
{
let started = Instant::now();
let url = self.url(path);
let json =
serde_json::to_vec(body).map_err(|err| LlmError::request_conversion(err.into()))?;
let json_bytes = json.len();
let compressed = encoding_for(&url)
.and_then(|encoding| Some((compress(&json, encoding)?, encoding.name())));
let (upload, encoding) =
compressed.map_or((json, None), |(bytes, encoding)| (bytes, Some(encoding)));
let upload = Bytes::from(upload);
self.send_with_retry(
|http| {
let mut request = http.post(url.clone()).header(CONTENT_TYPE, "application/json");
if let Some(encoding) = encoding {
request = request.header(CONTENT_ENCODING, encoding);
}
if let Some(accept) = accept {
request = request.header(ACCEPT, accept);
}
request.body(upload.clone())
},
&url,
|resp| {
debug!(
encoding = encoding.unwrap_or("identity"),
json_bytes,
upload_bytes = upload.len(),
http_status = resp.status().as_u16(),
elapsed_ms = started.elapsed().as_millis() as u64,
"llm request answered"
);
read(resp)
},
)
.await
}
async fn send_with_retry<F, H, Fut, T>(
&self,
mut make_req: F,
url: &str,
mut handle_success: H,
) -> Result<T, LlmError>
where
F: FnMut(&reqwest::Client) -> reqwest::RequestBuilder,
H: FnMut(reqwest::Response) -> Fut,
Fut: Future<Output = std::result::Result<T, reqwest::Error>>,
{
within(self.stream_idle_timeout, async {
let mut attempt: u32 = 0;
loop {
let send_result =
self.auth.send(|http| make_req(http).headers(self.headers.clone())).await?;
let retry = match send_result {
Ok(resp)
if self.retry_policy.should_retry_status(resp.status())
&& attempt < self.retry_policy.max_count
&& retry_after_header(resp.headers())
.is_none_or(|wait| wait <= self.retry_policy.max_delay) =>
{
let status = resp.status();
Retry {
delay: retry_after_header(resp.headers())
.unwrap_or_else(|| self.retry_policy.next_delay(attempt)),
reason: format!("HTTP {status}"),
}
}
Ok(resp) => match handle_success(resp).await {
Ok(value) => {
if attempt > 0 {
info!(url = %url, retries = attempt, "request succeeded after retries");
}
return Ok(value);
}
Err(err)
if self.retry_policy.should_retry_error(&err)
&& attempt < self.retry_policy.max_count =>
{
Retry {
delay: self.retry_policy.next_delay(attempt),
reason: format!("response read error ({err:?})"),
}
}
Err(err) => return Err(classify_send_failure(&self.retry_policy, &err)),
},
Err(err)
if self.retry_policy.should_retry_error(&err)
&& attempt < self.retry_policy.max_count =>
{
Retry {
delay: self.retry_policy.next_delay(attempt),
reason: format!("request error ({err:?})"),
}
}
Err(err) => return Err(classify_send_failure(&self.retry_policy, &err)),
};
info!(
url = %url,
attempt,
delay_ms = retry.delay.as_millis() as u64,
reason = %retry.reason,
"retrying request"
);
tokio::time::sleep(retry.delay).await;
attempt = attempt.saturating_add(1);
}
})
.await?
}
fn url(&self, path: &str) -> String {
format!("{}/{}", self.base_url.trim_end_matches('/'), path.trim_start_matches('/'))
}
}
struct Retry {
delay: Duration,
reason: String,
}
pub(crate) async fn within<T>(
bound: Duration,
fut: impl Future<Output = T>,
) -> Result<T, LlmError> {
tokio::time::timeout(bound, fut).await.map_err(|_| {
LlmError::message(LlmErrorKind::Timeout, format!("no response within {}s", bound.as_secs()))
})
}
async fn read_response(
resp: reqwest::Response,
) -> std::result::Result<ClientResponse, reqwest::Error> {
let status = resp.status();
let headers = resp.headers().clone();
let body = resp.text().await?;
Ok(ClientResponse { status, headers, body })
}
fn classify_send_failure(policy: &RetryPolicy, err: &reqwest::Error) -> LlmError {
if policy.should_retry_error(err) {
LlmError::transport(err.to_string())
} else {
LlmError::message(LlmErrorKind::Unknown, err.to_string())
}
}
#[cfg(test)]
mod retry_tests;
#[cfg(test)]
mod tests {
use super::*;
use crate::auth::test_support::StubSource;
use crate::compress::Encoding;
use crate::test_support::unauthenticated;
use crate::types::{Message, ToolChoice, Usage};
use async_trait::async_trait;
use reqwest::header::HeaderValue;
#[tokio::test(start_paused = true)]
async fn idle_timeout_yields_unexpected_eof() {
let raw = futures_util::stream::pending::<Result<(), LlmError>>();
let mut stream = Box::pin(with_idle_timeout(raw, Duration::from_secs(17)));
let err = stream.next().await.expect("timeout should yield an item").unwrap_err();
assert_eq!(err.kind, LlmErrorKind::UnexpectedEof);
assert!(err.to_string().contains("17s"), "configured timeout should be reported: {err}");
}
#[tokio::test(start_paused = true)]
async fn sse_keepalives_reset_idle_timeout_before_filtering() {
let bytes = futures_util::stream::iter([
": heartbeat\n\n",
"event: keepalive\n\n",
"event: keepalive\ndata: still working\n\n",
"data:\n\n",
"data: {\"text\":\"pong\"}\n\n",
])
.then(|chunk| async move {
tokio::time::sleep(Duration::from_secs(10)).await;
Ok(chunk)
})
.chain(futures_util::stream::pending());
let stream = sse_events(Box::pin(bytes), Duration::from_secs(17));
let mut decoded = decode_chunks::<serde_json::Value>(stream);
let start = tokio::time::Instant::now();
assert_eq!(decoded.next().await.unwrap().unwrap(), serde_json::json!({"text": "pong"}));
assert_eq!(start.elapsed(), Duration::from_secs(50));
let err = decoded.next().await.unwrap().unwrap_err();
assert_eq!(err.kind, LlmErrorKind::UnexpectedEof);
assert_eq!(start.elapsed(), Duration::from_secs(67));
}
#[tokio::test(start_paused = true)]
async fn done_sentinel_ends_the_stream_on_a_held_connection() {
let bytes = futures_util::stream::iter([
Ok::<_, LlmError>("data: {\"text\":\"pong\"}\n\n"),
Ok("data: [DONE]\n\n"),
])
.chain(futures_util::stream::pending());
let stream = sse_events(Box::pin(bytes), Duration::from_secs(17));
let mut decoded = decode_chunks::<serde_json::Value>(stream);
let start = tokio::time::Instant::now();
assert_eq!(decoded.next().await.unwrap().unwrap(), serde_json::json!({"text": "pong"}));
assert!(decoded.next().await.is_none(), "`[DONE]` ends the stream");
assert_eq!(start.elapsed(), Duration::ZERO, "no wait for the idle timeout");
}
#[tokio::test]
async fn sse_payloads_are_not_logged_even_when_decoding_fails() {
use tracing::instrument::WithSubscriber;
let log = tempfile::NamedTempFile::new().unwrap();
let subscriber = tracing_subscriber::fmt()
.with_max_level(tracing::Level::TRACE)
.with_ansi(false)
.without_time()
.with_writer(log.reopen().unwrap())
.finish();
async {
let bytes = futures_util::stream::iter([
Ok("data: {\"text\":\"private-model-output\"}\n\n"),
Ok("data: {\"argument\":\"private-tool-argument\"\n\n"),
Ok("data: [DONE]\n\n"),
]);
let stream = sse_events(bytes, Duration::from_secs(17));
let mut decoded = decode_chunks::<serde_json::Value>(stream);
assert_eq!(
decoded.next().await.unwrap().unwrap(),
serde_json::json!({"text": "private-model-output"})
);
let err = decoded.next().await.unwrap().unwrap_err();
assert_eq!(err.kind, LlmErrorKind::MalformedResponse);
assert!(err.to_string().contains("EOF while parsing an object"));
assert!(decoded.next().await.is_none());
}
.with_subscriber(subscriber)
.await;
let output = std::fs::read_to_string(log.path()).unwrap();
assert!(!output.contains("private-model-output"), "model output leaked: {output}");
assert!(!output.contains("private-tool-argument"), "tool argument leaked: {output}");
assert!(!output.contains("sse ["), "per-event logging returned: {output}");
}
#[tokio::test]
async fn invalid_sse_utf8_is_malformed_response() {
let bytes = futures_util::stream::iter([Ok(vec![0, 159])]);
let err = sse_events(bytes, Duration::from_secs(17)).next().await.unwrap().unwrap_err();
assert_eq!(err.kind, LlmErrorKind::MalformedResponse);
assert!(err.retry_delay(1).is_none());
}
#[derive(Default)]
struct ToolChoicePickyClient {
seen: std::sync::Mutex<Vec<Option<ToolChoice>>>,
}
#[async_trait]
impl ChatClient for ToolChoicePickyClient {
async fn chat(&self, request: ChatRequest) -> Result<ChatResponse, LlmError> {
self.seen.lock().unwrap().push(request.tool_choice.clone());
if request.tool_choice.is_some() {
return Err(LlmError::http(
LlmErrorKind::InvalidRequest,
StatusCode::BAD_REQUEST,
Some("invalid_request_error".to_string()),
"Upstream request failed: [invalid_request_error] only `\"auto\"` is \
supported for `tool_choice`. `\"none\"`, `\"required\"`, and named \
function choices are not currently supported"
.to_string(),
));
}
Ok(ChatResponse {
message: Message::model("ok".to_string()),
stop_reason: None,
usage: Usage::default(),
})
}
async fn stream_chat(&self, _request: ChatRequest) -> Result<ChatResponseStream, LlmError> {
panic!("stream_chat should not be called");
}
}
#[tokio::test]
async fn tool_choice_rejection_retries_once_without_the_parameter() {
let client = ToolChoicePickyClient::default();
let request = ChatRequest { tool_choice: Some(ToolChoice::Forbid), ..Default::default() };
let response = chat_with_tool_choice_fallback(&client, request).await.expect("fallback");
assert_eq!(response.message.content.as_text(), "ok");
let seen = client.seen.lock().unwrap();
assert_eq!(seen.as_slice(), [Some(ToolChoice::Forbid), None]);
}
#[tokio::test]
async fn unrelated_invalid_request_is_not_retried() {
struct InvalidParamClient {
calls: std::sync::Mutex<u32>,
}
#[async_trait]
impl ChatClient for InvalidParamClient {
async fn chat(&self, _request: ChatRequest) -> Result<ChatResponse, LlmError> {
*self.calls.lock().unwrap() += 1;
Err(LlmError::http(
LlmErrorKind::InvalidRequest,
StatusCode::BAD_REQUEST,
None,
"Invalid assistant message: content or tool_calls must be set".to_string(),
))
}
async fn stream_chat(
&self,
_request: ChatRequest,
) -> Result<ChatResponseStream, LlmError> {
panic!("stream_chat should not be called");
}
}
let client = InvalidParamClient { calls: std::sync::Mutex::new(0) };
let request = ChatRequest { tool_choice: Some(ToolChoice::Forbid), ..Default::default() };
let err = chat_with_tool_choice_fallback(&client, request).await.unwrap_err();
assert_eq!(err.kind, LlmErrorKind::InvalidRequest);
assert_eq!(*client.calls.lock().unwrap(), 1, "only a tool_choice rejection may retry");
}
#[tokio::test]
async fn local_tool_choice_validation_error_is_not_retried() {
struct ConversionFailingClient {
calls: std::sync::Mutex<u32>,
}
#[async_trait]
impl ChatClient for ConversionFailingClient {
async fn chat(&self, _request: ChatRequest) -> Result<ChatResponse, LlmError> {
*self.calls.lock().unwrap() += 1;
Err(LlmError::request_conversion(anyhow::anyhow!(
"tool_choice requires a tool call but the request has no tools"
)))
}
async fn stream_chat(
&self,
_request: ChatRequest,
) -> Result<ChatResponseStream, LlmError> {
panic!("stream_chat should not be called");
}
}
let client = ConversionFailingClient { calls: std::sync::Mutex::new(0) };
let request = ChatRequest { tool_choice: Some(ToolChoice::Required), ..Default::default() };
let err = chat_with_tool_choice_fallback(&client, request).await.unwrap_err();
assert_eq!(err.kind, LlmErrorKind::InvalidRequest);
assert_eq!(
*client.calls.lock().unwrap(),
1,
"local validation errors have no provider origin and must not retry"
);
}
#[tokio::test]
async fn a_rejected_credential_is_recovered_within_the_attempt() {
let server = wiremock::MockServer::start().await;
wiremock::Mock::given(wiremock::matchers::method("POST"))
.and(wiremock::matchers::header("authorization", "Bearer old"))
.respond_with(wiremock::ResponseTemplate::new(401))
.mount(&server)
.await;
wiremock::Mock::given(wiremock::matchers::method("POST"))
.respond_with(wiremock::ResponseTemplate::new(200).set_body_string("ok"))
.mount(&server)
.await;
let base_url = format!("http://api.anthropic.com:{}", server.address().port());
let http = reqwest::Client::builder()
.no_proxy()
.resolve("api.anthropic.com", *server.address())
.build()
.unwrap();
let client = Client::new(
base_url,
AuthedClient::new(
http,
crate::auth::Placement::Bearer,
std::sync::Arc::new(StubSource::new(["old", "new"])),
),
);
let body = serde_json::json!({"content": "hello".repeat(4000)});
let expected = compress(&serde_json::to_vec(&body).unwrap(), Encoding::Gzip).unwrap();
let response = client.post("/v1/messages", &body).await.expect("recovered");
assert_eq!(response.status, StatusCode::OK);
let requests = server.received_requests().await.unwrap();
assert_eq!(requests.len(), 2);
for request in requests {
assert_eq!(request.headers[CONTENT_ENCODING], "gzip");
assert_eq!(request.body, expected);
}
}
#[test]
fn classify_error_stamps_retry_after_from_headers() {
fn classify(resp: ClientResponse) -> LlmError {
LlmError::http(LlmErrorKind::RateLimited, resp.status, None, "slow down".to_string())
}
let transport = unauthenticated("https://api.example.test/v1");
let provider = ProviderClient::new(transport, classify);
let mut headers = HeaderMap::new();
headers.insert("retry-after", HeaderValue::from_static("30"));
let err = provider.classify_error(ClientResponse {
status: StatusCode::TOO_MANY_REQUESTS,
headers,
body: String::new(),
});
assert_eq!(err.detail.retry_after, Some(std::time::Duration::from_secs(30)));
let err = provider.classify_error(ClientResponse {
status: StatusCode::TOO_MANY_REQUESTS,
headers: HeaderMap::new(),
body: String::new(),
});
assert_eq!(err.detail.retry_after, None, "no header means no server-mandated wait");
}
async fn never_answering_client() -> (wiremock::MockServer, Client) {
let server = wiremock::MockServer::start().await;
wiremock::Mock::given(wiremock::matchers::method("POST"))
.respond_with(wiremock::ResponseTemplate::new(200).set_delay(Duration::from_secs(30)))
.mount(&server)
.await;
let client =
unauthenticated(server.uri()).with_stream_idle_timeout(Duration::from_millis(100));
(server, client)
}
#[tokio::test]
async fn buffered_request_times_out_at_the_idle_bound() {
let (server, client) = never_answering_client().await;
let started = std::time::Instant::now();
let err = client
.post("/chat", &serde_json::json!({}))
.await
.expect_err("a response that never comes must time out");
assert!(started.elapsed() < Duration::from_secs(5), "bounded by the idle timeout");
assert_eq!(err.kind, LlmErrorKind::Timeout, "{err}");
assert_eq!(server.received_requests().await.unwrap().len(), 1, "no second attempt");
}
#[tokio::test]
async fn stream_open_times_out_at_the_idle_bound() {
let (server, client) = never_answering_client().await;
let started = std::time::Instant::now();
let err = client
.post_sse("/chat", &serde_json::json!({}))
.await
.err()
.expect("a stream that never opens must time out");
assert!(started.elapsed() < Duration::from_secs(5), "bounded by the idle timeout");
assert_eq!(err.kind, LlmErrorKind::Timeout, "{err}");
assert_eq!(server.received_requests().await.unwrap().len(), 1, "no second attempt");
}
#[tokio::test]
async fn inline_retries_run_under_the_call_deadline() {
let server = wiremock::MockServer::start().await;
wiremock::Mock::given(wiremock::matchers::method("POST"))
.respond_with(wiremock::ResponseTemplate::new(503).set_delay(Duration::from_secs(1)))
.up_to_n_times(2)
.mount(&server)
.await;
wiremock::Mock::given(wiremock::matchers::method("POST"))
.respond_with(wiremock::ResponseTemplate::new(200).set_delay(Duration::from_secs(30)))
.mount(&server)
.await;
let client = unauthenticated(server.uri())
.with_retry_policy(RetryPolicy {
base_delay: Duration::from_millis(10),
max_delay: Duration::from_millis(10),
..RetryPolicy::default()
})
.with_stream_idle_timeout(Duration::from_millis(1500));
let started = std::time::Instant::now();
let err = client
.post("/chat", &serde_json::json!({}))
.await
.expect_err("the retry must be cut at the call's bound");
assert!(started.elapsed() < Duration::from_secs(3), "one bound for the whole call");
assert_eq!(err.kind, LlmErrorKind::Timeout, "{err}");
assert_eq!(server.received_requests().await.unwrap().len(), 2, "one retry, no third");
}
#[tokio::test]
async fn stream_open_error_body_times_out_at_the_idle_bound() {
use tokio::io::{AsyncReadExt as _, AsyncWriteExt as _};
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
let base_url = format!("http://{}", listener.local_addr().unwrap());
tokio::spawn(async move {
let (mut socket, _) = listener.accept().await.unwrap();
let _ = socket.read(&mut [0_u8; 4096]).await;
let headers = b"HTTP/1.1 500 Internal Server Error\r\n\
Content-Type: application/json\r\nContent-Length: 100\r\n\r\n";
socket.write_all(headers).await.unwrap();
tokio::time::sleep(Duration::from_secs(30)).await;
});
let client = unauthenticated(base_url).with_stream_idle_timeout(Duration::from_millis(100));
let err = tokio::time::timeout(
Duration::from_secs(5),
client.post_sse("/chat", &serde_json::json!({})),
)
.await
.expect("bounded by the idle timeout")
.err()
.expect("an error body that never comes must time out");
assert_eq!(err.kind, LlmErrorKind::Timeout, "{err}");
}
}