Skip to main content

feldera_rest_api/
retry.rs

1//! Retry layer for the generated client.
2//!
3//! Every request the generated `Client` sends passes through
4//! [`execute_with_retry`] (wired up by the `ClientHooks` impl in `lib.rs`),
5//! which resends requests that failed for reasons known to be transient:
6//! transport failures and the HTTP statuses in [`RETRYABLE_STATUSES`]. Waits
7//! between attempts grow exponentially; a `Retry-After` header overrides the
8//! computed wait, and a 502 waits based on a cluster-health probe (see
9//! [`cluster_is_healthy`]).
10//!
11//! Repeating a request is only safe when the first attempt provably caused no
12//! server-side effect, or when the operation yields the same state however
13//! often it runs. [`is_idempotent`] classifies operations; non-idempotent
14//! ones retry only failures where the request never reached its target.
15
16use std::time::Duration;
17
18use reqwest::header::HeaderMap;
19use reqwest::{Method, Request, Response, StatusCode};
20
21/// Retry behavior for transient request failures.
22///
23/// Carried by `Client` as its inner state: construct one and pass it to
24/// `Client::new` / `Client::new_with_client`.
25#[derive(Debug, Clone, PartialEq, Eq)]
26pub struct RetryPolicy {
27    /// Retries after the initial attempt. `3` means up to 4 attempts total;
28    /// `0` disables retrying.
29    pub max_retries: u32,
30    /// Wait before the first retry. Each further retry doubles the wait.
31    pub initial_backoff: Duration,
32    /// Upper bound on the wait between attempts.
33    pub max_backoff: Duration,
34    /// Flat wait between 502 retries while the cluster reports unhealthy on
35    /// `/v0/cluster_healthz`: the cluster is likely upgrading or restarting,
36    /// so a flat pause beats an exponential ramp. Not capped by
37    /// `max_backoff`.
38    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    /// A policy that never retries.
54    pub fn none() -> Self {
55        Self {
56            max_retries: 0,
57            ..Self::default()
58        }
59    }
60
61    /// Wait before retry number `retry_index` (zero-based).
62    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
69/// Statuses that signal a transient condition worth retrying (for idempotent
70/// operations): request timeout, rate limit, and gateway/service failures.
71const 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
79/// Mutating operations that are nonetheless safe to repeat: desired-state
80/// setters (repeating yields the same desired state) and pure functions of
81/// their input. Operations absent from this list retry only failures where
82/// the request never reached its target.
83const 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    // Set-based updates: repeating writes the same field values.
96    "patch_pipeline",
97    "patch_tenant",
98];
99
100/// GET/HEAD/PUT/DELETE are idempotent by HTTP semantics; POST and PATCH only
101/// when the operation is known to be safe to repeat.
102fn 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
109/// Whether a 503 body proves the request never reached the pipeline, making a
110/// retry safe even for non-idempotent operations.
111///
112/// The api-server answers 503 `PipelineInteractionConnectFailed` when it could
113/// not connect to the pipeline. Older api-servers answer
114/// `PipelineInteractionUnreachable` for every proxy failure, so for that code
115/// only the connect-phase wording ("Failed to connect to host", the awc
116/// connect error prefix) proves the pipeline never saw the request. An
117/// exchange that timed out or disconnected mid-flight may already have been
118/// applied.
119fn 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
132/// Rebuild a response consumed while inspecting its body, so the caller can
133/// parse the error as if the response arrived untouched. The rebuilt response
134/// loses request metadata such as the URL, which error handling never reads.
135fn 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
142/// Server-requested wait from a `Retry-After` header (seconds form only; the
143/// HTTP-date form is rare and falls back to the computed backoff).
144fn 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
155/// How long the `/v0/cluster_healthz` probe may take before the cluster
156/// counts as unhealthy.
157const HEALTH_PROBE_TIMEOUT: Duration = Duration::from_secs(5);
158
159/// Probe `/v0/cluster_healthz` to tell a spurious 502 (retry immediately)
160/// from an unhealthy cluster, e.g. one whose upgrade is in progress (flat
161/// long wait). The endpoint answers 200 only when every service is healthy;
162/// any other status or a probe failure counts as unhealthy.
163async 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
171/// Pick the wait before the next retry:
172/// a `Retry-After` value from the server wins (capped at `max_backoff`);
173/// a 502 from a healthy cluster was spurious, so retry immediately;
174/// a 502 from an unhealthy cluster (e.g. an upgrade in progress) waits the
175/// flat `unhealthy_backoff`; everything else backs off exponentially.
176fn 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        /// Wait requested by the server via `Retry-After`; overrides the
195        /// computed backoff (still capped at `max_backoff`).
196        server_wait: Option<Duration>,
197        status: StatusCode,
198    },
199}
200
201/// Decide whether a completed exchange warrants a retry. Consumes the
202/// response only when a body inspection is needed; hands it back otherwise.
203async 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
232/// Execute `request`, retrying transient failures per `policy`.
233///
234/// Requests with streaming bodies cannot be cloned and get a single attempt.
235pub(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        // Clone before executing: execute() consumes the request, and a
246        // failed attempt leaves nothing to resend.
247        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            // Final attempt: retries exhausted, or a streaming body that
258            // cannot be resent.
259            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                // Idempotent operations repeat on any transport failure
282                // (timeouts, resets mid-exchange). A connect failure never
283                // reached the server, so it is safe for every operation;
284                // other failures may already have been applied.
285                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        // A 502 comes from in front of the api-server; probe cluster health
294        // to pick the right wait (see `next_wait`). Skipped when the server
295        // already prescribed a wait via `Retry-After`.
296        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    /// Backoff doubles per retry and is capped at `max_backoff`.
319    #[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    /// Idempotency follows the HTTP method except for allowlisted operations.
334    #[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    /// Wait selection: `Retry-After` wins (capped), a 502 waits per cluster
346    /// health, everything else backs off exponentially.
347    #[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        // Server-prescribed wait wins, capped at max_backoff.
356        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        // 502 with healthy cluster: immediate; unhealthy: flat, uncapped.
365        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        // Otherwise exponential.
371        assert_eq!(next_wait(&policy, 1, None, None), Duration::from_secs(4));
372    }
373
374    /// Only the seconds form of `Retry-After` yields a wait.
375    #[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    /// Only a connect-phase failure marks a 503 as safe for any operation.
389    #[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}