1use vlo_types::{Backoff, Cause, Jitter, PlanRetryInput, RetryPlan, RetryPolicy};
5
6use crate::error::{code, err, KResult};
7use crate::validate::is_random_hex;
8
9const MAX_EXPONENT: u32 = 64;
11
12const JITTER_HEX_LEN: usize = 16;
14
15fn is_retryable(cause: Cause) -> bool {
16 !matches!(
17 cause,
18 Cause::SchemaViolation | Cause::UserCancel | Cause::NondeterminismDetected
19 )
20}
21
22fn base_delay_ms(policy: &RetryPolicy, attempt: u32) -> u64 {
23 let max = policy.max_ms as u128;
24 let base = match policy.backoff {
25 Backoff::Fixed => policy.initial_ms as u128,
26 Backoff::Exponential if policy.factor <= 1 => policy.initial_ms as u128,
27 Backoff::Exponential => {
28 let mut value = policy.initial_ms as u128;
29 for _ in 1..attempt.min(MAX_EXPONENT) {
30 value = value.saturating_mul(policy.factor as u128);
31 if value >= max {
32 break;
33 }
34 }
35 value
36 }
37 };
38 base.min(max) as u64
39}
40
41pub fn plan_retry(input: &PlanRetryInput) -> KResult<RetryPlan> {
48 if !is_random_hex(&input.random) {
49 return Err(err(
50 code::INVALID_EVENT,
51 "random must be 32 lowercase hex chars",
52 ));
53 }
54 if !is_retryable(input.cause) {
55 return Ok(RetryPlan::stop());
56 }
57 if input.attempt >= input.policy.max_attempts {
58 return Ok(RetryPlan::stop());
59 }
60
61 let base = base_delay_ms(&input.policy, input.attempt);
62 let delay_ms = match input.policy.jitter {
63 Jitter::None => base,
64 Jitter::Full => {
65 let entropy = u64::from_str_radix(&input.random[..JITTER_HEX_LEN], 16)
66 .map_err(|e| err(code::INVALID_EVENT, format!("random is not hex: {e}")))?;
67 ((base as u128 * entropy as u128) / u64::MAX as u128) as u64
68 }
69 };
70 Ok(RetryPlan::again(input.attempt + 1, delay_ms))
71}