toolkit_contract/runtime/
breaker.rs1use std::fmt;
23use std::sync::Arc;
24
25use bytes::Bytes;
26use http_body_util::Full;
27use toolkit_resilience::circuit_breaker::{
28 Bypass, CircuitBreakerLayer, Classify, Outcome, Rejected,
29};
30use tower::{Layer, ServiceExt};
31
32#[derive(Debug, Clone, Copy, PartialEq, Eq)]
37pub struct SkipCircuitBreaker;
38
39#[derive(Clone)]
42pub struct EndpointFailureHook(
43 pub(crate) Arc<dyn Fn() + Send + Sync>,
45);
46
47impl EndpointFailureHook {
48 pub fn new(hook: impl Fn() + Send + Sync + 'static) -> Self {
50 Self(Arc::new(hook))
51 }
52}
53
54impl fmt::Debug for EndpointFailureHook {
55 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
56 f.write_str("EndpointFailureHook")
57 }
58}
59
60#[derive(Debug, Clone, Copy, Default)]
62pub struct HttpEndpointFailure;
63
64const PROBLEM_JSON: &str = "application/problem+json";
65
66impl<B> Classify<http::Response<B>, toolkit_http::HttpError> for HttpEndpointFailure {
67 fn classify(&self, result: &Result<http::Response<B>, toolkit_http::HttpError>) -> Outcome {
68 use toolkit_http::{HttpError, ProxyErrorKind};
69 match result {
70 Ok(resp) => {
71 let gone = matches!(resp.status().as_u16(), 502..=504);
72 if gone && !is_problem(resp.headers()) {
73 Outcome::Failure
74 } else {
75 Outcome::Success
76 }
77 }
78 Err(
79 HttpError::Transport(_)
80 | HttpError::Tls(_)
81 | HttpError::Timeout(_)
82 | HttpError::DeadlineExceeded(_)
83 | HttpError::Proxy {
84 kind: ProxyErrorKind::TunnelRejected,
85 ..
86 },
87 ) => Outcome::Failure,
88 Err(_) => Outcome::Ignore,
89 }
90 }
91}
92
93impl<B> Bypass<http::Request<B>> for HttpEndpointFailure {
94 fn bypass(&self, req: &http::Request<B>) -> bool {
95 req.extensions().get::<SkipCircuitBreaker>().is_some()
96 }
97}
98
99fn is_problem(headers: &http::HeaderMap) -> bool {
100 headers
101 .get(http::header::CONTENT_TYPE)
102 .and_then(|v| v.to_str().ok())
103 .is_some_and(|ct| ct.trim_start().starts_with(PROBLEM_JSON))
104}
105
106type HttpInner = tower::util::BoxCloneService<
107 http::Request<Full<Bytes>>,
108 http::Response<toolkit_http::ResponseBody>,
109 toolkit_http::HttpError,
110>;
111
112#[derive(Debug, Clone, Default)]
121pub(crate) struct AttemptStart(Arc<std::sync::OnceLock<tokio::time::Instant>>);
122
123impl AttemptStart {
124 fn mark(&self) {
126 self.0.set(tokio::time::Instant::now()).ok();
127 }
128
129 pub(crate) async fn bound<F: std::future::Future>(
132 &self,
133 started: tokio::time::Instant,
134 budget: std::time::Duration,
135 fut: F,
136 ) -> Option<F::Output> {
137 let deadline = || self.0.get().copied().unwrap_or(started) + budget;
138 let mut fut = std::pin::pin!(fut);
139 let mut armed = deadline();
140 loop {
141 if let Ok(out) = tokio::time::timeout_at(armed, fut.as_mut()).await {
142 return Some(out);
143 }
144 let later = deadline();
146 if later <= armed {
147 return None;
148 }
149 armed = later;
150 }
151 }
152}
153
154#[must_use]
162pub fn install_http_breaker(
163 builder: toolkit_http::HttpClientBuilder,
164 config: &crate::runtime::config::ClientConfig,
165) -> toolkit_http::HttpClientBuilder {
166 let Some(breaker) = config.circuit_breaker.clone() else {
167 return builder.with_attempt_layer(|svc: HttpInner| mark_attempt_start(svc).boxed_clone());
168 };
169 let mut layer = CircuitBreakerLayer::new(breaker, HttpEndpointFailure);
170 if let Some(hook) = &config.on_endpoint_failure {
171 layer = layer.on_failure(Arc::clone(&hook.0));
172 }
173 builder.with_attempt_layer(move |svc: HttpInner| {
174 let guarded =
175 layer
176 .layer(svc)
177 .map_err(|e: toolkit_resilience::circuit_breaker::BoxError| {
178 match e.downcast::<toolkit_http::HttpError>() {
179 Ok(http) => *http,
180 Err(other) => toolkit_http::HttpError::Transport(other),
181 }
182 });
183 mark_attempt_start(guarded).boxed_clone()
184 })
185}
186
187fn mark_attempt_start<S>(svc: S) -> tower::util::MapRequest<S, fn(HttpRequest) -> HttpRequest>
191where
192 S: tower::Service<HttpRequest>,
193{
194 fn mark(req: HttpRequest) -> HttpRequest {
195 if let Some(start) = req.extensions().get::<AttemptStart>() {
196 start.mark();
197 }
198 req
199 }
200 svc.map_request(mark as fn(HttpRequest) -> HttpRequest)
201}
202
203type HttpRequest = http::Request<Full<Bytes>>;
204
205pub(crate) fn find_rejected<'a>(
207 err: &'a (dyn std::error::Error + 'static),
208) -> Option<&'a Rejected> {
209 let mut cur = Some(err);
210 while let Some(e) = cur {
211 if let Some(r) = e.downcast_ref::<Rejected>() {
212 return Some(r);
213 }
214 cur = e.source();
215 }
216 None
217}
218
219#[cfg(test)]
220#[cfg_attr(coverage_nightly, coverage(off))]
221mod tests {
222 use super::*;
223 use toolkit_http::HttpError;
224
225 use std::time::Duration;
226
227 use tokio::time::{Instant, sleep};
228
229 const BUDGET: Duration = Duration::from_millis(100);
230
231 #[tokio::test(start_paused = true)]
232 async fn bound_runs_from_started_while_the_attempt_is_unmarked() {
233 let start = AttemptStart::default();
234 let started = Instant::now();
235
236 let out = start.bound(started, BUDGET, sleep(BUDGET * 2)).await;
237
238 assert!(out.is_none());
239 assert_eq!(started.elapsed(), BUDGET);
240 }
241
242 #[tokio::test(start_paused = true)]
243 async fn bound_moves_to_a_late_mark() {
244 let start = AttemptStart::default();
245 let started = Instant::now();
246 let late = start.clone();
247 let fut = async move {
248 sleep(BUDGET / 2).await;
249 late.mark();
250 sleep(BUDGET * 7 / 10).await;
251 };
252
253 let out = start.bound(started, BUDGET, fut).await;
254
255 assert!(
256 out.is_some(),
257 "the budget runs from the mark, not from the start"
258 );
259 }
260
261 #[tokio::test(start_paused = true)]
262 async fn a_mark_after_the_budget_ran_out_is_too_late() {
263 let start = AttemptStart::default();
264 let started = Instant::now();
265 let late = start.clone();
266 let fut = async move {
267 sleep(BUDGET * 3 / 2).await;
268 late.mark();
269 };
270
271 let out = start.bound(started, BUDGET, fut).await;
272
273 assert!(out.is_none());
274 assert_eq!(started.elapsed(), BUDGET);
275 }
276
277 #[tokio::test(start_paused = true)]
278 async fn bound_ends_a_budget_after_the_mark() {
279 let start = AttemptStart::default();
280 let started = Instant::now();
281 let late = start.clone();
282 let fut = async move {
283 sleep(BUDGET / 2).await;
284 late.mark();
285 sleep(BUDGET * 2).await;
286 };
287
288 let out = start.bound(started, BUDGET, fut).await;
289
290 assert!(out.is_none());
291 assert_eq!(started.elapsed(), BUDGET * 3 / 2);
292 }
293
294 fn resp(status: u16, content_type: Option<&str>) -> Result<http::Response<()>, HttpError> {
295 let mut b = http::Response::builder().status(status);
296 if let Some(ct) = content_type {
297 b = b.header(http::header::CONTENT_TYPE, ct);
298 }
299 b.body(()).map_err(HttpError::RequestBuild)
300 }
301
302 #[test]
303 fn gateway_errors_without_a_problem_are_failures() {
304 for status in [502, 503, 504] {
305 assert_eq!(
306 HttpEndpointFailure.classify(&resp(status, None)),
307 Outcome::Failure
308 );
309 assert_eq!(
310 HttpEndpointFailure.classify(&resp(status, Some("text/html"))),
311 Outcome::Failure
312 );
313 }
314 }
315
316 #[test]
317 fn a_problem_from_the_backend_is_an_answer() {
318 let r = resp(503, Some("application/problem+json; charset=utf-8"));
319 assert_eq!(HttpEndpointFailure.classify(&r), Outcome::Success);
320 }
321
322 #[test]
323 fn business_statuses_and_throttling_are_answers() {
324 for status in [200, 400, 404, 409, 429, 500] {
325 assert_eq!(
326 HttpEndpointFailure.classify(&resp(status, None)),
327 Outcome::Success
328 );
329 }
330 }
331
332 #[test]
333 fn transport_errors_are_failures_and_local_ones_are_not_counted() {
334 let c = |e: HttpError| {
335 Classify::<http::Response<()>, HttpError>::classify(&HttpEndpointFailure, &Err(e))
336 };
337 assert_eq!(c(HttpError::Transport("refused".into())), Outcome::Failure);
338 assert_eq!(
339 c(HttpError::Timeout(std::time::Duration::from_secs(1))),
340 Outcome::Failure
341 );
342 assert_eq!(c(HttpError::Overloaded), Outcome::Ignore);
343 }
344
345 async fn refusing_proxy(status: &'static str) -> String {
347 use tokio::io::{AsyncReadExt, AsyncWriteExt};
348 let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
349 let addr = listener.local_addr().unwrap();
350 tokio::spawn(async move {
351 while let Ok((mut conn, _)) = listener.accept().await {
352 let mut buf = [0u8; 1024];
353 drop(conn.read(&mut buf).await);
354 let reply = format!("HTTP/1.1 {status}\r\ncontent-length: 0\r\n\r\n");
355 drop(conn.write_all(reply.as_bytes()).await);
356 }
357 });
358 format!("http://{addr}")
359 }
360
361 async fn error_through_proxy(status: &'static str) -> HttpError {
362 drop(toolkit_security::tls::configured_provider().install_default());
363 let client = toolkit_http::HttpClientBuilder::new()
364 .retry(None)
365 .outbound_proxy(toolkit_http::ExplicitProxy::all(
366 refusing_proxy(status).await,
367 ))
368 .build()
369 .unwrap();
370 client
371 .get("https://backend.example/")
372 .send()
373 .await
374 .unwrap_err()
375 }
376
377 #[tokio::test]
378 async fn a_refused_tunnel_is_a_failure_and_proxy_auth_is_not_counted() {
379 let c = |e: HttpError| {
380 Classify::<http::Response<()>, HttpError>::classify(&HttpEndpointFailure, &Err(e))
381 };
382 let refused = error_through_proxy("502 Bad Gateway").await;
383 assert!(
384 matches!(
385 refused,
386 HttpError::Proxy {
387 kind: toolkit_http::ProxyErrorKind::TunnelRejected,
388 ..
389 }
390 ),
391 "{refused:?}"
392 );
393 assert_eq!(c(refused), Outcome::Failure);
394
395 let auth = error_through_proxy("407 Proxy Authentication Required").await;
396 assert!(
397 matches!(
398 auth,
399 HttpError::Proxy {
400 kind: toolkit_http::ProxyErrorKind::AuthRequired,
401 ..
402 }
403 ),
404 "{auth:?}"
405 );
406 assert_eq!(c(auth), Outcome::Ignore);
407 }
408
409 #[test]
410 fn the_skip_marker_bypasses() {
411 let plain = http::Request::new(());
412 let mut marked = http::Request::new(());
413 marked.extensions_mut().insert(SkipCircuitBreaker);
414 assert!(!HttpEndpointFailure.bypass(&plain));
415 assert!(HttpEndpointFailure.bypass(&marked));
416 }
417}