use std::time::Duration;
use reqwest::header::HeaderMap;
use reqwest::{Method, Request, Response, StatusCode};
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct RetryPolicy {
pub max_retries: u32,
pub initial_backoff: Duration,
pub max_backoff: Duration,
pub unhealthy_backoff: Duration,
}
impl Default for RetryPolicy {
fn default() -> Self {
Self {
max_retries: 3,
initial_backoff: Duration::from_secs(2),
max_backoff: Duration::from_secs(60),
unhealthy_backoff: Duration::from_secs(90),
}
}
}
impl RetryPolicy {
pub fn none() -> Self {
Self {
max_retries: 0,
..Self::default()
}
}
fn backoff(&self, retry_index: u32) -> Duration {
self.initial_backoff
.saturating_mul(2u32.saturating_pow(retry_index))
.min(self.max_backoff)
}
}
const RETRYABLE_STATUSES: [StatusCode; 5] = [
StatusCode::REQUEST_TIMEOUT,
StatusCode::TOO_MANY_REQUESTS,
StatusCode::BAD_GATEWAY,
StatusCode::SERVICE_UNAVAILABLE,
StatusCode::GATEWAY_TIMEOUT,
];
const IDEMPOTENT_OPERATIONS: &[&str] = &[
"post_pipeline_start",
"post_pipeline_pause",
"post_pipeline_resume",
"post_pipeline_stop",
"post_pipeline_clear",
"post_pipeline_activate",
"post_pipeline_approve",
"post_pipeline_dismiss_error",
"post_pipeline_input_connector_action",
"post_pipeline_diff",
"post_validate_program",
"patch_pipeline",
"patch_tenant",
];
fn is_idempotent(method: &Method, operation_id: &str) -> bool {
matches!(
*method,
Method::GET | Method::HEAD | Method::PUT | Method::DELETE
) || IDEMPOTENT_OPERATIONS.contains(&operation_id)
}
fn is_never_dispatched_503(body: &[u8]) -> bool {
serde_json::from_slice::<serde_json::Value>(body).is_ok_and(|v| {
match v.get("error_code").and_then(|c| c.as_str()) {
Some("PipelineInteractionConnectFailed") => true,
Some("PipelineInteractionUnreachable") => v
.get("message")
.and_then(|m| m.as_str())
.is_some_and(|m| m.contains("Failed to connect to host")),
_ => false,
}
})
}
fn rebuild_response(status: StatusCode, headers: HeaderMap, body: bytes::Bytes) -> Response {
let mut rebuilt = http::Response::new(body);
*rebuilt.status_mut() = status;
*rebuilt.headers_mut() = headers;
Response::from(rebuilt)
}
fn retry_after(headers: &HeaderMap) -> Option<Duration> {
let secs = headers
.get(reqwest::header::RETRY_AFTER)?
.to_str()
.ok()?
.trim()
.parse()
.ok()?;
Some(Duration::from_secs(secs))
}
const HEALTH_PROBE_TIMEOUT: Duration = Duration::from_secs(5);
async fn cluster_is_healthy(client: &reqwest::Client, baseurl: &str) -> bool {
let url = format!("{}/v0/cluster_healthz", baseurl.trim_end_matches('/'));
match client.get(url).timeout(HEALTH_PROBE_TIMEOUT).send().await {
Ok(response) => response.status().is_success(),
Err(_) => false,
}
}
fn next_wait(
policy: &RetryPolicy,
retry_index: u32,
server_wait: Option<Duration>,
cluster_healthy_after_502: Option<bool>,
) -> Duration {
match (server_wait, cluster_healthy_after_502) {
(Some(server_wait), _) => server_wait.min(policy.max_backoff),
(None, Some(true)) => Duration::ZERO,
(None, Some(false)) => policy.unhealthy_backoff,
(None, None) => policy.backoff(retry_index),
}
}
enum Verdict {
Return(Response),
Retry {
reason: &'static str,
server_wait: Option<Duration>,
status: StatusCode,
},
}
async fn judge_response(response: Response, idempotent: bool) -> reqwest::Result<Verdict> {
let status = response.status();
if !RETRYABLE_STATUSES.contains(&status) {
return Ok(Verdict::Return(response));
}
let server_wait = retry_after(response.headers());
if idempotent {
return Ok(Verdict::Retry {
reason: "transient HTTP status",
server_wait,
status,
});
}
if status != StatusCode::SERVICE_UNAVAILABLE {
return Ok(Verdict::Return(response));
}
let headers = response.headers().clone();
let body = response.bytes().await?;
if is_never_dispatched_503(&body) {
Ok(Verdict::Retry {
reason: "pipeline unreachable, request never sent",
server_wait,
status,
})
} else {
Ok(Verdict::Return(rebuild_response(status, headers, body)))
}
}
pub(crate) async fn execute_with_retry(
client: &reqwest::Client,
policy: &RetryPolicy,
baseurl: &str,
mut request: Request,
operation_id: &str,
) -> reqwest::Result<Response> {
let idempotent = is_idempotent(request.method(), operation_id);
let mut retry_index = 0u32;
loop {
let retry_request = if retry_index < policy.max_retries {
request.try_clone()
} else {
None
};
let retries_remain = retry_index < policy.max_retries;
let outcome = client.execute(request).await;
let Some(retry_request) = retry_request else {
let failed_transiently = match &outcome {
Ok(response) => RETRYABLE_STATUSES.contains(&response.status()),
Err(_) => true,
};
if retries_remain && failed_transiently {
log::info!(
"{operation_id}: not retrying a transient failure because the request body is a stream and cannot be resent"
);
}
return outcome;
};
let (reason, detail, server_wait, retried_status) = match outcome {
Ok(response) => match judge_response(response, idempotent).await? {
Verdict::Return(response) => return Ok(response),
Verdict::Retry {
reason,
server_wait,
status,
} => (reason, String::new(), server_wait, Some(status)),
},
Err(error) => {
if !(idempotent || error.is_connect()) {
return Err(error);
}
("transport error", format!(": {error}"), None, None)
}
};
request = retry_request;
let cluster_healthy_after_502 =
if server_wait.is_none() && retried_status == Some(StatusCode::BAD_GATEWAY) {
Some(cluster_is_healthy(client, baseurl).await)
} else {
None
};
let wait = next_wait(policy, retry_index, server_wait, cluster_healthy_after_502);
retry_index += 1;
log::debug!(
"{operation_id}: {reason}{detail} - retrying in {}s (attempt {} of {})",
wait.as_secs(),
retry_index + 1,
policy.max_retries + 1,
);
tokio::time::sleep(wait).await;
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn backoff_doubles_and_caps() {
let policy = RetryPolicy {
max_retries: 5,
initial_backoff: Duration::from_secs(2),
max_backoff: Duration::from_secs(6),
..RetryPolicy::default()
};
assert_eq!(policy.backoff(0), Duration::from_secs(2));
assert_eq!(policy.backoff(1), Duration::from_secs(4));
assert_eq!(policy.backoff(2), Duration::from_secs(6));
assert_eq!(policy.backoff(30), Duration::from_secs(6));
}
#[test]
fn idempotency_classification() {
assert!(is_idempotent(&Method::GET, "get_pipeline"));
assert!(is_idempotent(&Method::PUT, "put_pipeline"));
assert!(is_idempotent(&Method::DELETE, "delete_pipeline"));
assert!(is_idempotent(&Method::POST, "post_pipeline_start"));
assert!(!is_idempotent(&Method::POST, "clock_advance"));
assert!(!is_idempotent(&Method::POST, "http_input"));
assert!(!is_idempotent(&Method::PATCH, "patch_something_new"));
}
#[test]
fn next_wait_selection() {
let policy = RetryPolicy {
max_retries: 3,
initial_backoff: Duration::from_secs(2),
max_backoff: Duration::from_secs(60),
unhealthy_backoff: Duration::from_secs(90),
};
assert_eq!(
next_wait(&policy, 0, Some(Duration::from_secs(7)), None),
Duration::from_secs(7)
);
assert_eq!(
next_wait(&policy, 0, Some(Duration::from_secs(600)), None),
Duration::from_secs(60)
);
assert_eq!(next_wait(&policy, 0, None, Some(true)), Duration::ZERO);
assert_eq!(
next_wait(&policy, 0, None, Some(false)),
Duration::from_secs(90)
);
assert_eq!(next_wait(&policy, 1, None, None), Duration::from_secs(4));
}
#[test]
fn retry_after_parses_seconds_only() {
let with = |v: &str| {
let mut h = HeaderMap::new();
h.insert(reqwest::header::RETRY_AFTER, v.parse().unwrap());
h
};
assert_eq!(retry_after(&with("7")), Some(Duration::from_secs(7)));
assert_eq!(retry_after(&with("Wed, 21 Oct 2026 07:28:00 GMT")), None);
assert_eq!(retry_after(&with("-3")), None);
assert_eq!(retry_after(&HeaderMap::new()), None);
}
#[test]
fn never_dispatched_detection() {
let connect = br#"{"message": "Failed to connect to host: Timeout while establishing connection", "error_code": "PipelineInteractionUnreachable", "details": {}}"#;
let timeout = br#"{"message": "timeout (5s) was reached", "error_code": "PipelineInteractionUnreachable", "details": {}}"#;
let other_code = br#"{"message": "Failed to connect to host", "error_code": "PipelineInteractionNotDeployed", "details": {}}"#;
let connect_failed =
br#"{"message": "x", "error_code": "PipelineInteractionConnectFailed", "details": {}}"#;
assert!(is_never_dispatched_503(connect_failed));
assert!(is_never_dispatched_503(connect));
assert!(!is_never_dispatched_503(timeout));
assert!(!is_never_dispatched_503(other_code));
assert!(!is_never_dispatched_503(b"not json"));
}
}