1use std::time::Duration;
17
18use reqwest::header::HeaderMap;
19use reqwest::{Method, Request, Response, StatusCode};
20
21#[derive(Debug, Clone, PartialEq, Eq)]
26pub struct RetryPolicy {
27 pub max_retries: u32,
30 pub initial_backoff: Duration,
32 pub max_backoff: Duration,
34 pub unhealthy_backoff: Duration,
39}
40
41impl Default for RetryPolicy {
42 fn default() -> Self {
43 Self {
44 max_retries: 3,
45 initial_backoff: Duration::from_secs(2),
46 max_backoff: Duration::from_secs(60),
47 unhealthy_backoff: Duration::from_secs(90),
48 }
49 }
50}
51
52impl RetryPolicy {
53 pub fn none() -> Self {
55 Self {
56 max_retries: 0,
57 ..Self::default()
58 }
59 }
60
61 fn backoff(&self, retry_index: u32) -> Duration {
63 self.initial_backoff
64 .saturating_mul(2u32.saturating_pow(retry_index))
65 .min(self.max_backoff)
66 }
67}
68
69const RETRYABLE_STATUSES: [StatusCode; 5] = [
72 StatusCode::REQUEST_TIMEOUT,
73 StatusCode::TOO_MANY_REQUESTS,
74 StatusCode::BAD_GATEWAY,
75 StatusCode::SERVICE_UNAVAILABLE,
76 StatusCode::GATEWAY_TIMEOUT,
77];
78
79const IDEMPOTENT_OPERATIONS: &[&str] = &[
84 "post_pipeline_start",
85 "post_pipeline_pause",
86 "post_pipeline_resume",
87 "post_pipeline_stop",
88 "post_pipeline_clear",
89 "post_pipeline_activate",
90 "post_pipeline_approve",
91 "post_pipeline_dismiss_error",
92 "post_pipeline_input_connector_action",
93 "post_pipeline_diff",
94 "post_validate_program",
95 "patch_pipeline",
97 "patch_tenant",
98];
99
100fn is_idempotent(method: &Method, operation_id: &str) -> bool {
103 matches!(
104 *method,
105 Method::GET | Method::HEAD | Method::PUT | Method::DELETE
106 ) || IDEMPOTENT_OPERATIONS.contains(&operation_id)
107}
108
109fn is_never_dispatched_503(body: &[u8]) -> bool {
120 serde_json::from_slice::<serde_json::Value>(body).is_ok_and(|v| {
121 match v.get("error_code").and_then(|c| c.as_str()) {
122 Some("PipelineInteractionConnectFailed") => true,
123 Some("PipelineInteractionUnreachable") => v
124 .get("message")
125 .and_then(|m| m.as_str())
126 .is_some_and(|m| m.contains("Failed to connect to host")),
127 _ => false,
128 }
129 })
130}
131
132fn rebuild_response(status: StatusCode, headers: HeaderMap, body: bytes::Bytes) -> Response {
136 let mut rebuilt = http::Response::new(body);
137 *rebuilt.status_mut() = status;
138 *rebuilt.headers_mut() = headers;
139 Response::from(rebuilt)
140}
141
142fn retry_after(headers: &HeaderMap) -> Option<Duration> {
145 let secs = headers
146 .get(reqwest::header::RETRY_AFTER)?
147 .to_str()
148 .ok()?
149 .trim()
150 .parse()
151 .ok()?;
152 Some(Duration::from_secs(secs))
153}
154
155const HEALTH_PROBE_TIMEOUT: Duration = Duration::from_secs(5);
158
159async fn cluster_is_healthy(client: &reqwest::Client, baseurl: &str) -> bool {
164 let url = format!("{}/v0/cluster_healthz", baseurl.trim_end_matches('/'));
165 match client.get(url).timeout(HEALTH_PROBE_TIMEOUT).send().await {
166 Ok(response) => response.status().is_success(),
167 Err(_) => false,
168 }
169}
170
171fn next_wait(
177 policy: &RetryPolicy,
178 retry_index: u32,
179 server_wait: Option<Duration>,
180 cluster_healthy_after_502: Option<bool>,
181) -> Duration {
182 match (server_wait, cluster_healthy_after_502) {
183 (Some(server_wait), _) => server_wait.min(policy.max_backoff),
184 (None, Some(true)) => Duration::ZERO,
185 (None, Some(false)) => policy.unhealthy_backoff,
186 (None, None) => policy.backoff(retry_index),
187 }
188}
189
190enum Verdict {
191 Return(Response),
192 Retry {
193 reason: &'static str,
194 server_wait: Option<Duration>,
197 status: StatusCode,
198 },
199}
200
201async fn judge_response(response: Response, idempotent: bool) -> reqwest::Result<Verdict> {
204 let status = response.status();
205 if !RETRYABLE_STATUSES.contains(&status) {
206 return Ok(Verdict::Return(response));
207 }
208 let server_wait = retry_after(response.headers());
209 if idempotent {
210 return Ok(Verdict::Retry {
211 reason: "transient HTTP status",
212 server_wait,
213 status,
214 });
215 }
216 if status != StatusCode::SERVICE_UNAVAILABLE {
217 return Ok(Verdict::Return(response));
218 }
219 let headers = response.headers().clone();
220 let body = response.bytes().await?;
221 if is_never_dispatched_503(&body) {
222 Ok(Verdict::Retry {
223 reason: "pipeline unreachable, request never sent",
224 server_wait,
225 status,
226 })
227 } else {
228 Ok(Verdict::Return(rebuild_response(status, headers, body)))
229 }
230}
231
232pub(crate) async fn execute_with_retry(
236 client: &reqwest::Client,
237 policy: &RetryPolicy,
238 baseurl: &str,
239 mut request: Request,
240 operation_id: &str,
241) -> reqwest::Result<Response> {
242 let idempotent = is_idempotent(request.method(), operation_id);
243 let mut retry_index = 0u32;
244 loop {
245 let retry_request = if retry_index < policy.max_retries {
248 request.try_clone()
249 } else {
250 None
251 };
252
253 let retries_remain = retry_index < policy.max_retries;
254 let outcome = client.execute(request).await;
255
256 let Some(retry_request) = retry_request else {
257 let failed_transiently = match &outcome {
260 Ok(response) => RETRYABLE_STATUSES.contains(&response.status()),
261 Err(_) => true,
262 };
263 if retries_remain && failed_transiently {
264 log::info!(
265 "{operation_id}: not retrying a transient failure because the request body is a stream and cannot be resent"
266 );
267 }
268 return outcome;
269 };
270
271 let (reason, detail, server_wait, retried_status) = match outcome {
272 Ok(response) => match judge_response(response, idempotent).await? {
273 Verdict::Return(response) => return Ok(response),
274 Verdict::Retry {
275 reason,
276 server_wait,
277 status,
278 } => (reason, String::new(), server_wait, Some(status)),
279 },
280 Err(error) => {
281 if !(idempotent || error.is_connect()) {
286 return Err(error);
287 }
288 ("transport error", format!(": {error}"), None, None)
289 }
290 };
291
292 request = retry_request;
293 let cluster_healthy_after_502 =
297 if server_wait.is_none() && retried_status == Some(StatusCode::BAD_GATEWAY) {
298 Some(cluster_is_healthy(client, baseurl).await)
299 } else {
300 None
301 };
302 let wait = next_wait(policy, retry_index, server_wait, cluster_healthy_after_502);
303 retry_index += 1;
304 log::debug!(
305 "{operation_id}: {reason}{detail} - retrying in {}s (attempt {} of {})",
306 wait.as_secs(),
307 retry_index + 1,
308 policy.max_retries + 1,
309 );
310 tokio::time::sleep(wait).await;
311 }
312}
313
314#[cfg(test)]
315mod tests {
316 use super::*;
317
318 #[test]
320 fn backoff_doubles_and_caps() {
321 let policy = RetryPolicy {
322 max_retries: 5,
323 initial_backoff: Duration::from_secs(2),
324 max_backoff: Duration::from_secs(6),
325 ..RetryPolicy::default()
326 };
327 assert_eq!(policy.backoff(0), Duration::from_secs(2));
328 assert_eq!(policy.backoff(1), Duration::from_secs(4));
329 assert_eq!(policy.backoff(2), Duration::from_secs(6));
330 assert_eq!(policy.backoff(30), Duration::from_secs(6));
331 }
332
333 #[test]
335 fn idempotency_classification() {
336 assert!(is_idempotent(&Method::GET, "get_pipeline"));
337 assert!(is_idempotent(&Method::PUT, "put_pipeline"));
338 assert!(is_idempotent(&Method::DELETE, "delete_pipeline"));
339 assert!(is_idempotent(&Method::POST, "post_pipeline_start"));
340 assert!(!is_idempotent(&Method::POST, "clock_advance"));
341 assert!(!is_idempotent(&Method::POST, "http_input"));
342 assert!(!is_idempotent(&Method::PATCH, "patch_something_new"));
343 }
344
345 #[test]
348 fn next_wait_selection() {
349 let policy = RetryPolicy {
350 max_retries: 3,
351 initial_backoff: Duration::from_secs(2),
352 max_backoff: Duration::from_secs(60),
353 unhealthy_backoff: Duration::from_secs(90),
354 };
355 assert_eq!(
357 next_wait(&policy, 0, Some(Duration::from_secs(7)), None),
358 Duration::from_secs(7)
359 );
360 assert_eq!(
361 next_wait(&policy, 0, Some(Duration::from_secs(600)), None),
362 Duration::from_secs(60)
363 );
364 assert_eq!(next_wait(&policy, 0, None, Some(true)), Duration::ZERO);
366 assert_eq!(
367 next_wait(&policy, 0, None, Some(false)),
368 Duration::from_secs(90)
369 );
370 assert_eq!(next_wait(&policy, 1, None, None), Duration::from_secs(4));
372 }
373
374 #[test]
376 fn retry_after_parses_seconds_only() {
377 let with = |v: &str| {
378 let mut h = HeaderMap::new();
379 h.insert(reqwest::header::RETRY_AFTER, v.parse().unwrap());
380 h
381 };
382 assert_eq!(retry_after(&with("7")), Some(Duration::from_secs(7)));
383 assert_eq!(retry_after(&with("Wed, 21 Oct 2026 07:28:00 GMT")), None);
384 assert_eq!(retry_after(&with("-3")), None);
385 assert_eq!(retry_after(&HeaderMap::new()), None);
386 }
387
388 #[test]
390 fn never_dispatched_detection() {
391 let connect = br#"{"message": "Failed to connect to host: Timeout while establishing connection", "error_code": "PipelineInteractionUnreachable", "details": {}}"#;
392 let timeout = br#"{"message": "timeout (5s) was reached", "error_code": "PipelineInteractionUnreachable", "details": {}}"#;
393 let other_code = br#"{"message": "Failed to connect to host", "error_code": "PipelineInteractionNotDeployed", "details": {}}"#;
394 let connect_failed =
395 br#"{"message": "x", "error_code": "PipelineInteractionConnectFailed", "details": {}}"#;
396 assert!(is_never_dispatched_503(connect_failed));
397 assert!(is_never_dispatched_503(connect));
398 assert!(!is_never_dispatched_503(timeout));
399 assert!(!is_never_dispatched_503(other_code));
400 assert!(!is_never_dispatched_503(b"not json"));
401 }
402}