1use std::sync::Arc;
21use std::task::Poll;
22use std::time::Duration;
23
24use bytes::Bytes;
25use futures::{FutureExt, StreamExt};
26use http::{HeaderMap, Method, Uri};
27use tokio::time::Instant;
28
29use super::error::RestError;
30use super::policy::{RetryAfter, RetryPolicy, should_retry, should_retry_dropped_body};
31use crate::error::ModelError;
32use crate::http::{BodyStream, HttpClient, collect_body};
33
34pub const DEFAULT_RESPONSE_HEADER_TIMEOUT: Duration = Duration::from_secs(600);
36
37#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
39pub enum CallTimeout {
40 #[default]
42 None,
43 PerAttempt(Duration),
49 Call(Instant),
54}
55
56#[async_trait::async_trait]
58pub trait RequestHeaders: Send + Sync {
59 async fn headers(&self) -> Result<HeaderMap, RestError>;
63}
64
65#[async_trait::async_trait]
67impl RequestHeaders for HeaderMap {
68 async fn headers(&self) -> Result<HeaderMap, RestError> {
69 Ok(self.clone())
70 }
71}
72
73pub enum RestReply {
75 Read(http::response::Parts, Bytes),
79 Streaming(http::Response<BodyStream>),
84}
85
86impl std::fmt::Debug for RestReply {
87 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
88 match self {
89 Self::Read(parts, body) => f.debug_tuple("Read").field(parts).field(body).finish(),
90 Self::Streaming(res) => f
91 .debug_struct("Streaming")
92 .field("status", &res.status())
93 .field("headers", res.headers())
94 .finish_non_exhaustive(),
95 }
96 }
97}
98
99#[derive(Clone)]
102pub struct RestTransport {
103 pub http: Arc<dyn HttpClient>,
105 pub policy: RetryPolicy,
107 pub response_header_timeout: Option<Duration>,
112}
113
114impl std::fmt::Debug for RestTransport {
115 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
116 f.debug_struct("RestTransport")
117 .field("policy", &self.policy)
118 .field("response_header_timeout", &self.response_header_timeout)
119 .finish_non_exhaustive()
120 }
121}
122
123enum Attempt {
125 NoResponse(RestError),
127 TimedOut,
129 Retry(Duration),
131 Read(http::response::Parts, Bytes),
133 DroppedBody(http::response::Parts, ModelError),
135 Streaming(http::Response<BodyStream>),
137}
138
139fn body_with_deadline(body: BodyStream, deadline: Instant) -> BodyStream {
143 let mut body = Some(body);
144 let mut sleep = Box::pin(tokio::time::sleep_until(deadline));
145 futures::stream::poll_fn(move |cx| {
146 let Some(inner) = body.as_mut() else {
147 return Poll::Ready(None);
148 };
149 if let Poll::Ready(item) = inner.poll_next_unpin(cx) {
150 if item.is_none() {
151 body = None;
152 }
153 return Poll::Ready(item);
154 }
155 if sleep.poll_unpin(cx).is_ready() {
156 body = None;
157 return Poll::Ready(Some(Err(ModelError::Other(Box::new(
158 RestError::DeadlineExceeded,
159 )))));
160 }
161 Poll::Pending
162 })
163 .boxed()
164}
165
166impl RestTransport {
167 async fn attempt(
171 &self,
172 method: &Method,
173 uri: &Uri,
174 body: &Bytes,
175 stream: bool,
176 headers: &dyn RequestHeaders,
177 retry_count: u32,
178 ) -> Attempt {
179 let headers = match headers.headers().await {
180 Ok(h) => h,
181 Err(e) => return Attempt::NoResponse(e),
182 };
183 let mut req = http::Request::new(body.clone());
184 *req.method_mut() = method.clone();
185 *req.uri_mut() = uri.clone();
186 *req.headers_mut() = headers;
187 let sent = match self.response_header_timeout {
188 Some(limit) => match tokio::time::timeout(limit, self.http.send(req)).await {
189 Ok(sent) => sent,
190 Err(_) => return Attempt::NoResponse(RestError::ResponseHeaderTimeout),
191 },
192 None => self.http.send(req).await,
193 };
194 let res = match sent {
195 Ok(res) => res,
196 Err(e) => return Attempt::NoResponse(RestError::Transport(e)),
197 };
198 if retry_count < self.policy.max_retries
199 && should_retry(res.status(), res.headers())
200 && let RetryAfter::Wait(delay) =
201 self.policy.retry_delay(Some(res.headers()), retry_count)
202 {
203 return Attempt::Retry(delay);
205 }
206 if stream && res.status().as_u16() < 400 {
207 return Attempt::Streaming(res);
208 }
209 let (parts, body) = res.into_parts();
210 match collect_body(body).await {
211 Ok(bytes) => Attempt::Read(parts, bytes),
212 Err(e) => Attempt::DroppedBody(parts, e),
213 }
214 }
215
216 fn backoff(&self, retry_count: u32) -> Duration {
219 match self.policy.retry_delay(None, retry_count) {
220 RetryAfter::Wait(d) => d,
221 RetryAfter::Stop => Duration::ZERO,
222 }
223 }
224
225 pub async fn send(
228 &self,
229 uri: &Uri,
230 body: Bytes,
231 stream: bool,
232 headers: &dyn RequestHeaders,
233 timeout: CallTimeout,
234 ) -> Result<RestReply, RestError> {
235 self.send_method(Method::POST, uri, body, stream, headers, timeout)
236 .await
237 }
238
239 pub async fn send_method(
258 &self,
259 method: Method,
260 uri: &Uri,
261 body: Bytes,
262 stream: bool,
263 headers: &dyn RequestHeaders,
264 timeout: CallTimeout,
265 ) -> Result<RestReply, RestError> {
266 let (per_attempt, call_deadline) = match timeout {
267 CallTimeout::None => (None, None),
268 CallTimeout::PerAttempt(d) => ((!d.is_zero()).then_some(d), None),
269 CallTimeout::Call(at) => (None, Some(at)),
270 };
271 let mut retry_count: u32 = 0;
272 loop {
273 if call_deadline.is_some_and(|at| Instant::now() >= at) {
274 return Err(RestError::DeadlineExceeded);
275 }
276 let last_attempt = retry_count >= self.policy.max_retries;
277 let deadline = per_attempt
279 .and_then(|t| Instant::now().checked_add(t))
280 .or(call_deadline);
281 let attempt = self.attempt(&method, uri, &body, stream, headers, retry_count);
282 let outcome = match deadline {
283 Some(deadline) => tokio::time::timeout_at(deadline, attempt)
284 .await
285 .unwrap_or(Attempt::TimedOut),
286 None => attempt.await,
287 };
288 let delay = match outcome {
289 Attempt::NoResponse(err) => {
290 if last_attempt {
291 return Err(err);
292 }
293 self.backoff(retry_count)
294 }
295 Attempt::TimedOut => {
296 if last_attempt || call_deadline.is_some() {
297 return Err(RestError::DeadlineExceeded);
298 }
299 self.backoff(retry_count)
300 }
301 Attempt::Retry(delay) => delay,
302 Attempt::DroppedBody(parts, source) => {
303 let retry = !last_attempt
304 && self.policy.retry_dropped_body
305 && should_retry_dropped_body(&parts.headers);
306 match retry.then(|| self.policy.retry_delay(Some(&parts.headers), retry_count))
307 {
308 Some(RetryAfter::Wait(delay)) => delay,
309 _ => {
310 return Err(RestError::DroppedBody {
311 parts: Box::new(parts),
312 source,
313 });
314 }
315 }
316 }
317 Attempt::Read(parts, bytes) => return Ok(RestReply::Read(parts, bytes)),
318 Attempt::Streaming(res) => {
319 return Ok(RestReply::Streaming(match deadline {
320 Some(deadline) => res.map(|b| body_with_deadline(b, deadline)),
321 None => res,
322 }));
323 }
324 };
325 let sleep = tokio::time::sleep(delay);
326 match call_deadline {
327 Some(at) => {
328 if tokio::time::timeout_at(at, sleep).await.is_err() {
329 return Err(RestError::DeadlineExceeded);
330 }
331 }
332 None => sleep.await,
333 }
334 retry_count += 1;
335 }
336 }
337}
338
339#[cfg(test)]
340mod tests {
341 use std::sync::atomic::{AtomicUsize, Ordering};
342
343 use http::{HeaderValue, StatusCode};
344 use pretty_assertions::assert_eq;
345
346 use super::*;
347 use crate::rest::test_util::{FakeResponse, ScriptedClient};
348
349 const URI: &str = "https://api.example.test/v1/endpoint";
352 const BODY: &[u8] = br#"{"max_tokens":16,"model":"m"}"#;
353 const OK: &str = r#"{"id":"msg_1"}"#;
354 const BOOM: &str = r#"{"error":"boom"}"#;
355
356 fn reply(status: u16, body: &'static str) -> FakeResponse {
357 FakeResponse::json_status(status, body)
358 }
359
360 fn transport(http: Arc<ScriptedClient>, policy: RetryPolicy) -> RestTransport {
361 RestTransport {
362 http,
363 policy,
364 response_header_timeout: None,
365 }
366 }
367
368 fn anthropic(http: Arc<ScriptedClient>, max_retries: u32) -> RestTransport {
369 transport(
370 http,
371 RetryPolicy {
372 max_retries,
373 ..RetryPolicy::ANTHROPIC
374 },
375 )
376 }
377
378 fn openai(http: Arc<ScriptedClient>, max_retries: u32) -> RestTransport {
379 transport(
380 http,
381 RetryPolicy {
382 max_retries,
383 ..RetryPolicy::OPENAI
384 },
385 )
386 }
387
388 fn fixed_headers() -> HeaderMap {
389 HeaderMap::from_iter([
390 (
391 http::header::CONTENT_TYPE,
392 HeaderValue::from_static("application/json"),
393 ),
394 (
395 http::HeaderName::from_static("x-api-key"),
396 HeaderValue::from_static("sk-test"),
397 ),
398 ])
399 }
400
401 async fn send_with(
402 t: &RestTransport,
403 stream: bool,
404 timeout: CallTimeout,
405 ) -> Result<RestReply, RestError> {
406 t.send(
407 &Uri::from_static(URI),
408 Bytes::from_static(BODY),
409 stream,
410 &fixed_headers(),
411 timeout,
412 )
413 .await
414 }
415
416 async fn send(t: &RestTransport, stream: bool) -> Result<(u16, Bytes), RestError> {
419 send_timeout(t, stream, CallTimeout::None).await
420 }
421
422 async fn send_timeout(
423 t: &RestTransport,
424 stream: bool,
425 timeout: CallTimeout,
426 ) -> Result<(u16, Bytes), RestError> {
427 Ok(match send_with(t, stream, timeout).await? {
428 RestReply::Read(parts, body) => (parts.status.as_u16(), body),
429 RestReply::Streaming(res) => (
430 res.status().as_u16(),
431 collect_body(res.into_body()).await.unwrap(),
432 ),
433 })
434 }
435
436 fn streaming(reply: RestReply) -> http::Response<BodyStream> {
437 match reply {
438 RestReply::Streaming(res) => res,
439 other => panic!("want a streaming reply, got {other:?}"),
440 }
441 }
442
443 fn assert_backoff(d: Duration, n: u32, extra: Duration) {
445 let base = Duration::from_millis(500) * 2u32.pow(n);
446 let (lo, hi) = (extra + base - base / 4, extra + base);
447 assert!(d > lo && d <= hi, "gap {d:?} not in ({lo:?}, {hi:?}]");
448 }
449
450 fn assert_deadline_body_error(err: ModelError) {
451 let ModelError::Other(boxed) = err else {
452 panic!("want ModelError::Other, got {err:?}");
453 };
454 let err = boxed.downcast::<RestError>().unwrap();
455 assert!(matches!(*err, RestError::DeadlineExceeded), "{err:?}");
456 }
457
458 struct CountingHeaders {
460 calls: AtomicUsize,
461 fail: usize,
462 }
463
464 #[async_trait::async_trait]
465 impl RequestHeaders for CountingHeaders {
466 async fn headers(&self) -> Result<HeaderMap, RestError> {
467 let n = self.calls.fetch_add(1, Ordering::SeqCst);
468 if n < self.fail {
469 return Err(RestError::Headers("credentials: boom".into()));
470 }
471 let mut h = fixed_headers();
472 h.insert("x-attempt", HeaderValue::from_str(&n.to_string()).unwrap());
473 Ok(h)
474 }
475 }
476
477 #[tokio::test(start_paused = true)]
480 async fn send_first_attempt_success_wire() {
481 let fake = ScriptedClient::always(reply(200, OK));
482 let t = anthropic(fake.clone(), 2);
483 let RestReply::Read(parts, body) = send_with(&t, false, CallTimeout::None).await.unwrap()
484 else {
485 panic!("want a read reply");
486 };
487 assert_eq!(parts.status, StatusCode::OK);
488 assert_eq!(
489 parts.headers.get(http::header::CONTENT_TYPE).unwrap(),
490 "application/json"
491 );
492 assert_eq!(body, OK.as_bytes());
493 let seen = fake.requests();
494 assert_eq!(seen.len(), 1);
495 assert_eq!(seen[0].method, "POST");
496 assert_eq!(seen[0].url, URI);
497 assert_eq!(seen[0].body, BODY);
498 assert_eq!(seen[0].headers, fixed_headers());
499 }
500
501 #[tokio::test(start_paused = true)]
502 async fn send_method_sends_get_and_delete_through_the_retry_loop() {
503 for method in [Method::GET, Method::DELETE] {
504 let fake = ScriptedClient::sequence(vec![reply(503, BOOM), reply(200, OK)]);
505 let RestReply::Read(parts, body) = anthropic(fake.clone(), 2)
506 .send_method(
507 method.clone(),
508 &Uri::from_static(URI),
509 Bytes::new(),
510 false,
511 &fixed_headers(),
512 CallTimeout::None,
513 )
514 .await
515 .unwrap()
516 else {
517 panic!("want a read reply");
518 };
519 assert_eq!(parts.status, StatusCode::OK);
520 assert_eq!(body, OK.as_bytes());
521 let seen = fake.requests();
522 assert_eq!(seen.len(), 2, "{method}");
523 for s in &seen {
524 assert_eq!(s.method, method.as_str());
525 assert_eq!(s.url, URI);
526 assert!(s.body.is_empty());
527 }
528 }
529 }
530
531 #[tokio::test(start_paused = true)]
532 async fn send_is_send_method_post() {
533 let fake = ScriptedClient::always(reply(200, OK));
534 send(&anthropic(fake.clone(), 0), false).await.unwrap();
535 anthropic(fake.clone(), 0)
536 .send_method(
537 Method::POST,
538 &Uri::from_static(URI),
539 Bytes::from_static(BODY),
540 false,
541 &fixed_headers(),
542 CallTimeout::None,
543 )
544 .await
545 .unwrap();
546 let seen = fake.requests();
547 assert_eq!(seen.len(), 2);
548 for s in &seen {
549 assert_eq!(s.method, "POST");
550 assert_eq!(s.body, BODY);
551 assert_eq!(s.headers, fixed_headers());
552 }
553 }
554
555 #[tokio::test(start_paused = true)]
556 async fn send_resends_the_same_body_and_headers() {
557 let fake =
558 ScriptedClient::sequence(vec![reply(503, BOOM), reply(503, BOOM), reply(200, OK)]);
559 send(&anthropic(fake.clone(), 2), false).await.unwrap();
560 let seen = fake.requests();
561 assert_eq!(seen.len(), 3);
562 for s in &seen {
563 assert_eq!(s.body, BODY);
564 assert_eq!(s.headers, seen[0].headers);
565 }
566 }
567
568 #[tokio::test(start_paused = true)]
569 async fn send_fetches_headers_for_every_attempt() {
570 let fake =
571 ScriptedClient::sequence(vec![reply(500, BOOM), reply(500, BOOM), reply(200, OK)]);
572 let headers = CountingHeaders {
573 calls: AtomicUsize::new(0),
574 fail: 0,
575 };
576 anthropic(fake.clone(), 2)
577 .send(
578 &Uri::from_static(URI),
579 Bytes::from_static(BODY),
580 false,
581 &headers,
582 CallTimeout::None,
583 )
584 .await
585 .unwrap();
586 assert_eq!(headers.calls.load(Ordering::SeqCst), 3);
587 let attempts: Vec<String> = fake
588 .requests()
589 .iter()
590 .map(|r| r.header("x-attempt"))
591 .collect();
592 assert_eq!(attempts, ["0", "1", "2"]);
593 }
594
595 #[tokio::test(start_paused = true)]
598 async fn send_retries_retryable_statuses() {
599 for policy in [RetryPolicy::ANTHROPIC, RetryPolicy::OPENAI] {
600 for status in [408u16, 409, 429, 500, 502, 503, 529] {
601 let fake = ScriptedClient::sequence(vec![reply(status, BOOM), reply(200, OK)]);
602 let got = send(&transport(fake.clone(), policy), false).await.unwrap();
603 assert_eq!(got, (200, Bytes::from_static(OK.as_bytes())), "{status}");
604 assert_eq!(fake.hits(), 2, "{status}");
605 }
606 }
607 }
608
609 #[tokio::test(start_paused = true)]
610 async fn send_returns_other_statuses_read() {
611 for status in [400u16, 401, 403, 404, 422] {
612 let fake = ScriptedClient::sequence(vec![reply(status, BOOM), reply(200, OK)]);
613 let got = send(&anthropic(fake.clone(), 2), false).await.unwrap();
614 assert_eq!(got, (status, Bytes::from_static(BOOM.as_bytes())));
615 assert_eq!(fake.hits(), 1, "{status}");
616 }
617 }
618
619 #[tokio::test(start_paused = true)]
620 async fn send_max_retries_0_1_2() {
621 for max_retries in [0u32, 1, 2] {
622 let fake = ScriptedClient::always(reply(500, BOOM));
623 let got = send(&anthropic(fake.clone(), max_retries), false)
624 .await
625 .unwrap();
626 assert_eq!(fake.hits(), max_retries as usize + 1, "{max_retries}");
627 assert_eq!(got, (500, Bytes::from_static(BOOM.as_bytes())));
628 }
629 }
630
631 #[tokio::test(start_paused = true)]
632 async fn send_x_should_retry_overrides_status() {
633 let fake = ScriptedClient::sequence(vec![
635 reply(200, "first").header("x-should-retry", "true"),
636 reply(200, OK),
637 ]);
638 assert_eq!(
639 send(&anthropic(fake.clone(), 2), false).await.unwrap().1,
640 OK.as_bytes()
641 );
642 assert_eq!(fake.hits(), 2);
643
644 let fake = ScriptedClient::sequence(vec![
646 reply(400, BOOM).header("x-should-retry", "true"),
647 reply(200, OK),
648 ]);
649 send(&anthropic(fake.clone(), 2), false).await.unwrap();
650 assert_eq!(fake.hits(), 2);
651
652 let fake = ScriptedClient::sequence(vec![
654 reply(503, BOOM).header("x-should-retry", "false"),
655 reply(200, OK),
656 ]);
657 assert_eq!(
658 send(&anthropic(fake.clone(), 2), false).await.unwrap().0,
659 503
660 );
661 assert_eq!(fake.hits(), 1);
662
663 let fake = ScriptedClient::always(reply(200, "last").header("x-should-retry", "true"));
665 assert_eq!(
666 send(&anthropic(fake.clone(), 0), false).await.unwrap().1,
667 "last".as_bytes()
668 );
669 assert_eq!(fake.hits(), 1);
670 }
671
672 #[tokio::test(start_paused = true)]
675 async fn send_backoff_bounds_with_jitter() {
676 let fake = ScriptedClient::sequence(vec![
677 reply(500, BOOM),
678 reply(500, BOOM),
679 reply(500, BOOM),
680 reply(200, OK),
681 ]);
682 send(&anthropic(fake.clone(), 3), false).await.unwrap();
683 assert_eq!(fake.hits(), 4);
684 for n in 0..3 {
685 assert_backoff(fake.gap(n as usize), n, Duration::ZERO);
686 }
687 }
688
689 #[tokio::test(start_paused = true)]
690 async fn send_honours_retry_after_ms() {
691 let fake = ScriptedClient::sequence(vec![
692 reply(429, BOOM).header("retry-after-ms", "1234"),
693 reply(200, OK),
694 ]);
695 send(&anthropic(fake.clone(), 2), false).await.unwrap();
696 assert_eq!(fake.gap(0), Duration::from_millis(1234));
697 }
698
699 #[tokio::test(start_paused = true)]
700 async fn send_honours_retry_after_seconds() {
701 let fake = ScriptedClient::sequence(vec![
702 reply(503, BOOM).header("retry-after", "7"),
703 reply(200, OK),
704 ]);
705 send(&anthropic(fake.clone(), 2), false).await.unwrap();
706 assert_eq!(fake.gap(0), Duration::from_secs(7));
707 }
708
709 fn http_date(from_now: i64) -> String {
710 (chrono::Utc::now() + chrono::Duration::seconds(from_now))
711 .format("%a, %d %b %Y %H:%M:%S GMT")
712 .to_string()
713 }
714
715 #[tokio::test(start_paused = true)]
716 async fn send_honours_retry_after_date() {
717 let fake = ScriptedClient::sequence(vec![
718 reply(503, BOOM).header("retry-after", http_date(30)),
719 reply(200, OK),
720 ]);
721 send(&anthropic(fake.clone(), 2), false).await.unwrap();
722 let gap = fake.gap(0);
723 assert!(
724 gap > Duration::from_secs(28) && gap <= Duration::from_secs(30),
725 "{gap:?}"
726 );
727 }
728
729 #[tokio::test(start_paused = true)]
732 async fn openai_retry_after_beyond_the_limit_returns_the_response() {
733 let cases: [(&str, &str, String); 4] = [
734 ("seconds_121", "retry-after", "121".to_string()),
735 ("seconds_overflow", "retry-after", "1e400".to_string()),
736 ("ms_overflow", "retry-after-ms", "1e400".to_string()),
737 ("date_beyond_two_minutes", "retry-after", http_date(180)),
738 ];
739 for (name, header, value) in cases {
740 let fake = ScriptedClient::sequence(vec![
741 reply(429, BOOM).header(header, value),
742 reply(200, OK),
743 ]);
744 let got = send(&openai(fake.clone(), 2), false).await.unwrap();
745 assert_eq!(fake.hits(), 1, "{name}");
746 assert_eq!(got, (429, Bytes::from_static(BOOM.as_bytes())), "{name}");
747 }
748 }
749
750 #[tokio::test(start_paused = true)]
751 async fn openai_stop_on_a_retried_2xx_returns_that_2xx() {
752 let fake = ScriptedClient::sequence(vec![
753 reply(200, "first")
754 .header("x-should-retry", "true")
755 .header("retry-after", "121"),
756 reply(200, OK),
757 ]);
758 let got = send(&openai(fake.clone(), 2), false).await.unwrap();
759 assert_eq!(got, (200, Bytes::from_static(b"first")));
760 assert_eq!(fake.hits(), 1);
761 }
762
763 #[tokio::test(start_paused = true)]
764 async fn openai_skipped_retry_after_falls_back_to_backoff() {
765 for value in ["inf", "+Inf", "NaN", "-5"] {
766 let fake = ScriptedClient::sequence(vec![
767 reply(429, BOOM).header("retry-after", value),
768 reply(200, OK),
769 ]);
770 send(&openai(fake.clone(), 2), false).await.unwrap();
771 assert_eq!(fake.hits(), 2, "{value}");
772 assert_backoff(fake.gap(0), 0, Duration::ZERO);
773 }
774 }
775
776 #[tokio::test(start_paused = true)]
777 async fn openai_retry_after_within_the_limit_is_honoured() {
778 let fake = ScriptedClient::sequence(vec![
779 reply(429, BOOM).header("retry-after", "120"),
780 reply(429, BOOM).header("retry-after", http_date(-60)),
781 reply(200, OK),
782 ]);
783 send(&openai(fake.clone(), 2), false).await.unwrap();
784 assert_eq!(fake.gap(0), Duration::from_secs(120));
785 assert_eq!(fake.gap(1), Duration::ZERO, "a past date waits zero");
786 }
787
788 #[tokio::test(start_paused = true)]
789 async fn anthropic_honours_any_retry_after() {
790 let fake = ScriptedClient::sequence(vec![
791 reply(429, BOOM).header("retry-after", "121"),
792 reply(200, OK),
793 ]);
794 send(&anthropic(fake.clone(), 2), false).await.unwrap();
795 assert_eq!(fake.gap(0), Duration::from_secs(121));
796 }
797
798 #[tokio::test(start_paused = true)]
801 async fn send_retries_connection_errors() {
802 let fake = ScriptedClient::sequence(vec![
803 FakeResponse::reset("connection refused"),
804 reply(200, OK),
805 ]);
806 send(&anthropic(fake.clone(), 2), false).await.unwrap();
807 assert_eq!(fake.hits(), 2);
808 assert_backoff(fake.gap(0), 0, Duration::ZERO);
809
810 let fake = ScriptedClient::always(FakeResponse::reset("connection refused"));
811 let err = send(&anthropic(fake.clone(), 2), false).await.unwrap_err();
812 assert_eq!(fake.hits(), 3);
813 let RestError::Transport(ModelError::Transport(cause)) = err else {
814 panic!("want a transport error, got {err:?}");
815 };
816 assert_eq!(cause.to_string(), "connection refused");
817 }
818
819 #[tokio::test(start_paused = true)]
820 async fn send_retries_header_failures() {
821 let fake = ScriptedClient::always(reply(200, OK));
822 let headers = CountingHeaders {
823 calls: AtomicUsize::new(0),
824 fail: 1,
825 };
826 let t = anthropic(fake.clone(), 2);
827 let uri = Uri::from_static(URI);
828 let reply = t
829 .send(
830 &uri,
831 Bytes::from_static(BODY),
832 false,
833 &headers,
834 CallTimeout::None,
835 )
836 .await
837 .unwrap();
838 assert!(matches!(reply, RestReply::Read(..)));
839 assert_eq!(fake.hits(), 1);
840
841 let headers = CountingHeaders {
842 calls: AtomicUsize::new(0),
843 fail: usize::MAX,
844 };
845 let err = t
846 .send(
847 &uri,
848 Bytes::from_static(BODY),
849 false,
850 &headers,
851 CallTimeout::None,
852 )
853 .await
854 .unwrap_err();
855 assert_eq!(headers.calls.load(Ordering::SeqCst), 3);
856 assert_eq!(fake.hits(), 1, "nothing more was sent");
857 let RestError::Headers(cause) = err else {
858 panic!("want a header error, got {err:?}");
859 };
860 assert_eq!(cause.to_string(), "credentials: boom");
861 }
862
863 #[tokio::test(start_paused = true)]
864 async fn send_response_header_timeout() {
865 let fake = ScriptedClient::sequence(vec![FakeResponse::never(), reply(200, OK)]);
866 let mut t = anthropic(fake.clone(), 2);
867 t.response_header_timeout = Some(DEFAULT_RESPONSE_HEADER_TIMEOUT);
868 send(&t, false).await.unwrap();
869 assert_backoff(fake.gap(0), 0, DEFAULT_RESPONSE_HEADER_TIMEOUT);
870 assert_eq!(fake.drops(), 1, "the timed-out send was dropped");
871
872 let fake = ScriptedClient::always(FakeResponse::never());
873 let mut t = anthropic(fake.clone(), 0);
874 t.response_header_timeout = Some(DEFAULT_RESPONSE_HEADER_TIMEOUT);
875 let err = send(&t, false).await.unwrap_err();
876 assert!(matches!(err, RestError::ResponseHeaderTimeout), "{err:?}");
877 }
878
879 #[tokio::test(start_paused = true)]
880 async fn response_header_timeout_does_not_limit_a_streaming_body() {
881 let fake = ScriptedClient::always(FakeResponse::sse("data: a\n\n").hang());
882 let mut t = anthropic(fake, 0);
883 t.response_header_timeout = Some(Duration::from_secs(1));
884 let res = streaming(send_with(&t, true, CallTimeout::None).await.unwrap());
885 let mut body = res.into_body();
886 assert_eq!(body.next().await.unwrap().unwrap(), "data: a\n\n");
887 assert!(
888 tokio::time::timeout(Duration::from_secs(3600), body.next())
889 .await
890 .is_err(),
891 "the body stays open"
892 );
893 }
894
895 #[tokio::test(start_paused = true)]
898 async fn per_attempt_timeout_is_retried() {
899 let fake = ScriptedClient::sequence(vec![
900 FakeResponse::never(),
901 FakeResponse::never(),
902 reply(200, OK),
903 ]);
904 let got = send_timeout(
905 &anthropic(fake.clone(), 2),
906 false,
907 CallTimeout::PerAttempt(Duration::from_secs(1)),
908 )
909 .await
910 .unwrap();
911 assert_eq!(got.1, OK.as_bytes());
912 assert_eq!(fake.hits(), 3);
913 assert_backoff(fake.gap(0), 0, Duration::from_secs(1));
914 assert_backoff(fake.gap(1), 1, Duration::from_secs(1));
915 assert_eq!(fake.drops(), 2, "timed-out sends dropped");
916 }
917
918 #[tokio::test(start_paused = true)]
919 async fn per_attempt_timeout_on_last_attempt_is_deadline_exceeded() {
920 for max_retries in [0u32, 2] {
921 let fake = ScriptedClient::always(FakeResponse::never());
922 let err = send_timeout(
923 &anthropic(fake.clone(), max_retries),
924 false,
925 CallTimeout::PerAttempt(Duration::from_secs(1)),
926 )
927 .await
928 .unwrap_err();
929 assert_eq!(fake.hits(), max_retries as usize + 1);
930 assert!(matches!(err, RestError::DeadlineExceeded), "{err:?}");
931 }
932 }
933
934 #[tokio::test(start_paused = true)]
935 async fn per_attempt_timeout_covers_a_non_streaming_body() {
936 let stalled = reply(200, "{").hang();
937 let fake = ScriptedClient::sequence(vec![stalled.clone(), reply(200, OK)]);
938 let got = send_timeout(
939 &anthropic(fake.clone(), 1),
940 false,
941 CallTimeout::PerAttempt(Duration::from_secs(2)),
942 )
943 .await
944 .unwrap();
945 assert_eq!(got.1, OK.as_bytes());
946 assert_eq!(fake.hits(), 2);
947
948 let fake = ScriptedClient::always(stalled);
949 let err = send_timeout(
950 &anthropic(fake, 1),
951 false,
952 CallTimeout::PerAttempt(Duration::from_secs(2)),
953 )
954 .await
955 .unwrap_err();
956 assert!(matches!(err, RestError::DeadlineExceeded), "{err:?}");
957 }
958
959 #[tokio::test(start_paused = true)]
960 async fn per_attempt_timeout_keeps_running_on_a_streaming_body() {
961 let fake = ScriptedClient::always(FakeResponse::sse("data: a\n\n").hang());
962 let start = Instant::now();
963 let res = streaming(
964 send_with(
965 &anthropic(fake, 2),
966 true,
967 CallTimeout::PerAttempt(Duration::from_secs(5)),
968 )
969 .await
970 .unwrap(),
971 );
972 let mut body = res.into_body();
973 assert_eq!(body.next().await.unwrap().unwrap(), "data: a\n\n");
974 let err = body.next().await.unwrap().unwrap_err();
975 assert_eq!(start.elapsed(), Duration::from_secs(5));
976 assert_deadline_body_error(err);
977 assert!(
978 body.next().await.is_none(),
979 "the body ends after the deadline"
980 );
981 }
982
983 #[tokio::test(start_paused = true)]
986 async fn duration_max_per_attempt_timeout_is_no_deadline() {
987 let fake = ScriptedClient::always(reply(200, OK));
988 let got = send_timeout(
989 &anthropic(fake.clone(), 2),
990 false,
991 CallTimeout::PerAttempt(Duration::MAX),
992 )
993 .await
994 .unwrap();
995 assert_eq!(got.1, OK.as_bytes());
996 assert_eq!(fake.hits(), 1);
997
998 let fake = ScriptedClient::always(FakeResponse::sse("data: a\n\n").hang());
999 let res = streaming(
1000 send_with(
1001 &anthropic(fake, 0),
1002 true,
1003 CallTimeout::PerAttempt(Duration::MAX),
1004 )
1005 .await
1006 .unwrap(),
1007 );
1008 let mut body = res.into_body();
1009 assert_eq!(body.next().await.unwrap().unwrap(), "data: a\n\n");
1010 assert!(
1011 tokio::time::timeout(Duration::from_secs(3600), body.next())
1012 .await
1013 .is_err(),
1014 "no deadline ends the body"
1015 );
1016 }
1017
1018 #[tokio::test(start_paused = true)]
1019 async fn zero_per_attempt_timeout_is_no_timeout() {
1020 let fake = ScriptedClient::always(FakeResponse::sse("data: a\n\n").hang());
1021 let res = streaming(
1022 send_with(
1023 &anthropic(fake, 0),
1024 true,
1025 CallTimeout::PerAttempt(Duration::ZERO),
1026 )
1027 .await
1028 .unwrap(),
1029 );
1030 let mut body = res.into_body();
1031 assert!(body.next().await.unwrap().is_ok());
1032 assert!(
1033 tokio::time::timeout(Duration::from_secs(3600), body.next())
1034 .await
1035 .is_err()
1036 );
1037 }
1038
1039 #[tokio::test(start_paused = true)]
1042 async fn call_deadline_on_the_first_attempt_is_not_retried() {
1043 let fake = ScriptedClient::sequence(vec![FakeResponse::never(), reply(200, OK)]);
1044 let start = Instant::now();
1045 let err = send_timeout(
1046 &openai(fake.clone(), 2),
1047 false,
1048 CallTimeout::Call(start + Duration::from_secs(1)),
1049 )
1050 .await
1051 .unwrap_err();
1052 assert!(matches!(err, RestError::DeadlineExceeded), "{err:?}");
1053 assert_eq!(start.elapsed(), Duration::from_secs(1));
1054 assert_eq!(fake.hits(), 1);
1055 assert_eq!(fake.drops(), 1, "the in-flight send was dropped");
1056 }
1057
1058 #[tokio::test(start_paused = true)]
1059 async fn call_deadline_cuts_a_backoff_sleep_short() {
1060 let fake = ScriptedClient::sequence(vec![
1061 reply(503, BOOM).header("retry-after", "60"),
1062 reply(200, OK),
1063 ]);
1064 let start = Instant::now();
1065 let err = send_timeout(
1066 &openai(fake.clone(), 2),
1067 false,
1068 CallTimeout::Call(start + Duration::from_secs(5)),
1069 )
1070 .await
1071 .unwrap_err();
1072 assert!(matches!(err, RestError::DeadlineExceeded), "{err:?}");
1073 assert_eq!(start.elapsed(), Duration::from_secs(5));
1074 assert_eq!(fake.hits(), 1);
1075 }
1076
1077 #[tokio::test(start_paused = true)]
1078 async fn call_deadline_spans_every_attempt() {
1079 let fake = ScriptedClient::always(
1082 reply(500, BOOM)
1083 .header("retry-after-ms", "0")
1084 .delay_headers(Duration::from_secs(3)),
1085 );
1086 let start = Instant::now();
1087 let err = send_timeout(
1088 &openai(fake.clone(), 2),
1089 false,
1090 CallTimeout::Call(start + Duration::from_secs(5)),
1091 )
1092 .await
1093 .unwrap_err();
1094 assert!(matches!(err, RestError::DeadlineExceeded), "{err:?}");
1095 assert_eq!(start.elapsed(), Duration::from_secs(5));
1096 assert_eq!(fake.hits(), 2);
1097 }
1098
1099 #[tokio::test(start_paused = true)]
1100 async fn call_deadline_covers_a_non_streaming_body() {
1101 let fake = ScriptedClient::sequence(vec![reply(200, "{").hang(), reply(200, OK)]);
1102 let start = Instant::now();
1103 let err = send_timeout(
1104 &openai(fake.clone(), 2),
1105 false,
1106 CallTimeout::Call(start + Duration::from_secs(2)),
1107 )
1108 .await
1109 .unwrap_err();
1110 assert!(matches!(err, RestError::DeadlineExceeded), "{err:?}");
1111 assert_eq!(fake.hits(), 1);
1112 }
1113
1114 #[tokio::test(start_paused = true)]
1115 async fn call_deadline_covers_a_streaming_body() {
1116 let fake = ScriptedClient::always(
1117 FakeResponse::sse("data: a\n\n")
1118 .delay_headers(Duration::from_secs(1))
1119 .hang(),
1120 );
1121 let start = Instant::now();
1122 let res = streaming(
1123 send_with(
1124 &openai(fake, 2),
1125 true,
1126 CallTimeout::Call(start + Duration::from_secs(5)),
1127 )
1128 .await
1129 .unwrap(),
1130 );
1131 let mut body = res.into_body();
1132 assert_eq!(body.next().await.unwrap().unwrap(), "data: a\n\n");
1133 let err = body.next().await.unwrap().unwrap_err();
1134 assert_eq!(
1135 start.elapsed(),
1136 Duration::from_secs(5),
1137 "the call's deadline"
1138 );
1139 assert_deadline_body_error(err);
1140 assert!(body.next().await.is_none());
1141 }
1142
1143 #[tokio::test(start_paused = true)]
1144 async fn call_deadline_already_passed_sends_nothing() {
1145 let fake = ScriptedClient::always(reply(200, OK));
1146 let err = send_timeout(
1147 &openai(fake.clone(), 2),
1148 false,
1149 CallTimeout::Call(Instant::now()),
1150 )
1151 .await
1152 .unwrap_err();
1153 assert!(matches!(err, RestError::DeadlineExceeded), "{err:?}");
1154 assert_eq!(fake.hits(), 0);
1155 }
1156
1157 #[tokio::test(start_paused = true)]
1158 async fn call_deadline_not_reached_returns_the_reply() {
1159 let fake = ScriptedClient::sequence(vec![reply(500, BOOM), reply(200, OK)]);
1160 let got = send_timeout(
1161 &openai(fake.clone(), 2),
1162 false,
1163 CallTimeout::Call(Instant::now() + Duration::from_secs(60)),
1164 )
1165 .await
1166 .unwrap();
1167 assert_eq!(got, (200, Bytes::from_static(OK.as_bytes())));
1168 }
1169
1170 #[tokio::test(start_paused = true)]
1173 async fn anthropic_retries_a_dropped_body() {
1174 let fake =
1175 ScriptedClient::sequence(vec![reply(200, "{").fail("unexpected EOF"), reply(200, OK)]);
1176 assert_eq!(
1177 send(&anthropic(fake.clone(), 2), false).await.unwrap().1,
1178 OK.as_bytes()
1179 );
1180 assert_eq!(fake.hits(), 2);
1181 assert_backoff(fake.gap(0), 0, Duration::ZERO);
1182 }
1183
1184 #[tokio::test(start_paused = true)]
1185 async fn anthropic_dropped_body_honours_retry_after() {
1186 let fake = ScriptedClient::sequence(vec![
1187 reply(200, "{")
1188 .fail("unexpected EOF")
1189 .header("retry-after-ms", "2000"),
1190 reply(200, OK),
1191 ]);
1192 send(&anthropic(fake.clone(), 2), false).await.unwrap();
1193 assert_eq!(fake.gap(0), Duration::from_secs(2));
1194 }
1195
1196 fn assert_dropped(err: RestError, status: u16) {
1197 let RestError::DroppedBody { parts, source } = err else {
1198 panic!("want a dropped body, got {err:?}");
1199 };
1200 assert_eq!(parts.status.as_u16(), status);
1201 let ModelError::Transport(cause) = source else {
1202 panic!("want a transport cause, got {source:?}");
1203 };
1204 assert_eq!(cause.to_string(), "unexpected EOF");
1205 }
1206
1207 #[tokio::test(start_paused = true)]
1208 async fn anthropic_dropped_body_not_retried() {
1209 let fake = ScriptedClient::sequence(vec![
1211 reply(200, "{")
1212 .fail("unexpected EOF")
1213 .header("x-should-retry", "false"),
1214 reply(200, OK),
1215 ]);
1216 let err = send(&anthropic(fake.clone(), 2), false).await.unwrap_err();
1217 assert_eq!(fake.hits(), 1);
1218 assert_dropped(err, 200);
1219 let fake = ScriptedClient::always(reply(200, "{").fail("unexpected EOF"));
1221 let err = send(&anthropic(fake.clone(), 1), false).await.unwrap_err();
1222 assert_eq!(fake.hits(), 2);
1223 assert_dropped(err, 200);
1224 let fake = ScriptedClient::always(reply(500, "{").fail("unexpected EOF"));
1226 let err = send(&anthropic(fake.clone(), 0), false).await.unwrap_err();
1227 assert_dropped(err, 500);
1228 }
1229
1230 #[tokio::test(start_paused = true)]
1231 async fn openai_never_retries_a_dropped_body() {
1232 let fake =
1234 ScriptedClient::sequence(vec![reply(200, "{").fail("unexpected EOF"), reply(200, OK)]);
1235 let err = send(&openai(fake.clone(), 2), false).await.unwrap_err();
1236 assert_eq!(fake.hits(), 1);
1237 assert_dropped(err, 200);
1238 let fake = ScriptedClient::always(reply(500, "{").fail("unexpected EOF"));
1240 let err = send(&openai(fake.clone(), 2), false).await.unwrap_err();
1241 assert_eq!(fake.hits(), 3);
1242 assert_dropped(err, 500);
1243 }
1244
1245 #[tokio::test(start_paused = true)]
1248 async fn send_streaming_returns_the_live_body() {
1249 let fake = ScriptedClient::sequence(vec![
1250 reply(503, BOOM).fail("unexpected EOF"),
1251 FakeResponse::sse("data: a\n\n").hang(),
1252 ]);
1253 let res = streaming(
1254 send_with(&anthropic(fake.clone(), 2), true, CallTimeout::None)
1255 .await
1256 .unwrap(),
1257 );
1258 assert_eq!(fake.hits(), 2);
1260 let mut body = res.into_body();
1261 assert_eq!(body.next().await.unwrap().unwrap(), "data: a\n\n");
1262 }
1263
1264 #[tokio::test(start_paused = true)]
1265 async fn send_streaming_error_status_reads_the_body() {
1266 let fake = ScriptedClient::always(reply(400, BOOM));
1267 let RestReply::Read(parts, body) = send_with(&anthropic(fake, 2), true, CallTimeout::None)
1268 .await
1269 .unwrap()
1270 else {
1271 panic!("want a read reply");
1272 };
1273 assert_eq!(parts.status, StatusCode::BAD_REQUEST);
1274 assert_eq!(body, BOOM.as_bytes());
1275 }
1276
1277 #[tokio::test(start_paused = true)]
1280 async fn dropping_send_during_backoff_sends_nothing_more() {
1281 let fake = ScriptedClient::sequence(vec![
1282 reply(503, BOOM).header("retry-after", "60"),
1283 reply(200, OK),
1284 ]);
1285 let t = anthropic(fake.clone(), 2);
1286 let res = tokio::time::timeout(Duration::from_secs(10), send(&t, false)).await;
1287 assert!(res.is_err(), "still backing off");
1288 assert_eq!(fake.hits(), 1);
1289 tokio::time::sleep(Duration::from_secs(120)).await;
1290 assert_eq!(fake.hits(), 1);
1291 }
1292
1293 #[tokio::test(start_paused = true)]
1294 async fn dropping_send_drops_the_in_flight_request() {
1295 let fake = ScriptedClient::always(FakeResponse::never());
1296 let t = anthropic(fake.clone(), 2);
1297 let res = tokio::time::timeout(Duration::from_secs(1), send(&t, false)).await;
1298 assert!(res.is_err());
1299 assert_eq!(fake.drops(), 1);
1300 assert_eq!(fake.hits(), 1);
1301 }
1302
1303 #[test]
1304 fn call_timeout_default_is_none() {
1305 assert_eq!(CallTimeout::default(), CallTimeout::None);
1306 }
1307}