1use std::time::Duration;
18
19use serde::{Deserialize, Serialize};
21
22use crate::model;
24
25pub const UNBOUNDED: Duration = Duration::from_secs(1 << 32);
28
29#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
36#[serde(deny_unknown_fields)]
37pub struct OperationPolicy {
38 pub timeout: Duration,
40
41 pub attempt_timeout: Duration,
43
44 pub cancellation_timeout: Duration,
46
47 pub retries: RetryPolicy,
48}
49
50#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
53#[serde(rename_all = "snake_case", deny_unknown_fields)]
54pub enum RetryPolicy {
55 Never,
56 OnTransient { total_attempts: usize, backoff: Backoff },
57}
58
59#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
60#[serde(rename_all = "snake_case", deny_unknown_fields)]
61pub enum Backoff {
62 Fixed { delay: Duration, jitter: Jitter },
63 Exponential { initial: Duration, maximum: Duration, jitter: Jitter },
64}
65
66#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
67#[serde(rename_all = "snake_case", deny_unknown_fields)]
68pub enum Jitter {
69 None,
70 Deterministic,
71}
72
73#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
74#[serde(rename_all = "snake_case")]
75pub enum FailureKind {
76 Permanent,
77 Transient,
78 Ambiguous,
79 Unauthorized,
80 Invalid,
81 Cancelled,
82}
83
84#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
85#[serde(rename_all = "snake_case", deny_unknown_fields)]
86pub enum ReplaySafety {
87 Unknown,
88 Idempotent,
89 Deduplicated,
90}
91
92#[derive(Clone, Copy, Debug, PartialEq, Eq, thiserror::Error)]
93pub enum PolicyError {
94 #[error("Declare Operation Policy: Supply a Valid Protobuf Duration")]
95 InvalidDuration,
96
97 #[error("Declare Operation Policy: Use Positive Deadlines (overall {timeout:?}, attempt {attempt_timeout:?})")]
98 Deadline { timeout: Duration, attempt_timeout: Duration },
99
100 #[error("Declare Retry Policy: Use at Least Two Total Attempts or Select Never")]
101 EmptyRetries,
102
103 #[error("Declare Restart Policy: Use Positive Credit and Sustained Health or Select Never")]
104 EmptyRestarts,
105
106 #[error("Declare Backoff: Use Positive, Ordered Delays (initial {initial:?}, maximum {maximum:?})")]
107 Backoff { initial: Duration, maximum: Duration },
108}
109
110impl OperationPolicy {
115 pub fn validate(self) -> Result<(), PolicyError> {
116 if self.timeout.is_zero() || self.attempt_timeout.is_zero() {
117 return Err(PolicyError::Deadline {
118 timeout: self.timeout,
119 attempt_timeout: self.attempt_timeout,
120 });
121 }
122
123 self.retries.validate()
124 }
125}
126
127impl RetryPolicy {
128 pub fn validate(self) -> Result<(), PolicyError> {
129 match self {
130 Self::Never => Ok(()),
131 Self::OnTransient { total_attempts: 0 | 1, .. } => Err(PolicyError::EmptyRetries),
132 Self::OnTransient { backoff, .. } => backoff.validate(),
133 }
134 }
135
136 pub fn retry_after(self, failed_attempt: usize, failure: FailureKind, replay: ReplaySafety, entropy: u64) -> Option<Duration> {
137 let Self::OnTransient { total_attempts, backoff } = self else {
138 return None;
139 };
140 let invalid = self.validate().is_err();
141 let exhausted = failed_attempt.saturating_add(1) >= total_attempts;
142 let unsafe_replay = replay == ReplaySafety::Unknown;
143 if invalid || exhausted || unsafe_replay {
144 return None;
145 }
146 let transient = failure == FailureKind::Transient;
147 let ambiguous_replay = failure == FailureKind::Ambiguous && replay != ReplaySafety::Unknown;
148 if !transient && !ambiguous_replay {
149 return None;
150 }
151
152 backoff.delay(failed_attempt, entropy).ok()
153 }
154}
155
156impl Backoff {
157 pub fn validate(self) -> Result<(), PolicyError> {
158 let (initial, maximum) = match self {
159 Self::Fixed { delay, .. } => (delay, delay),
160 Self::Exponential { initial, maximum, .. } => (initial, maximum),
161 };
162 if initial.is_zero() || maximum < initial {
163 return Err(PolicyError::Backoff { initial, maximum });
164 }
165
166 Ok(())
167 }
168
169 pub fn delay(self, failed_attempt: usize, entropy: u64) -> Result<Duration, PolicyError> {
170 self.validate()?;
171
172 let (nominal, maximum, jitter) = match self {
173 Self::Fixed { delay, jitter } => (delay, delay.saturating_add(from_nanos(delay.as_nanos() / 4)), jitter),
174 Self::Exponential { initial, maximum, jitter } => {
175 let shift = u32::try_from(failed_attempt).unwrap_or(u32::MAX);
176 let nanos = if shift >= 128 || initial.as_nanos() > (u128::MAX >> shift) {
177 maximum.as_nanos()
178 } else {
179 (initial.as_nanos() << shift).min(maximum.as_nanos())
180 };
181
182 (from_nanos(nanos), maximum, jitter)
183 }
184 };
185 if jitter == Jitter::None {
186 return Ok(nominal.min(maximum));
187 }
188 let mixed = u128::from(entropy)
189 .wrapping_mul(0x9e37_79b9_7f4a_7c15)
190 .wrapping_add((failed_attempt as u128).wrapping_mul(17).wrapping_add(11));
191 let nanos = mixed % (nominal.as_nanos() / 4 + 1);
192
193 Ok(nominal.saturating_add(from_nanos(nanos)).min(maximum))
194 }
195}
196
197impl TryFrom<Option<&model::OperationPolicy>> for OperationPolicy {
198 type Error = PolicyError;
199
200 fn try_from(wire: Option<&model::OperationPolicy>) -> Result<Self, Self::Error> {
201 let wire = wire.cloned().unwrap_or_default();
202 let timeout = duration(wire.timeout, UNBOUNDED)?;
203 let attempt_timeout = duration(wire.attempt_timeout, UNBOUNDED)?;
204 let cancellation_timeout = duration(wire.cancellation_timeout, Duration::ZERO)?;
205 let retries = wire.retries.as_ref().map(retry_policy).transpose()?.unwrap_or(RetryPolicy::Never);
206 let policy = Self {
207 timeout,
208 attempt_timeout,
209 cancellation_timeout,
210 retries,
211 };
212 policy.validate()?;
213 Ok(policy)
214 }
215}
216
217fn duration(value: Option<prost_types::Duration>, default: Duration) -> Result<Duration, PolicyError> {
222 let duration = value.map(Duration::try_from).transpose().map_err(|_| PolicyError::InvalidDuration)?;
223 Ok(duration.unwrap_or(default))
224}
225
226fn retry_policy(retry: &model::RetryPolicy) -> Result<RetryPolicy, PolicyError> {
227 if retry.total_attempts == 0 {
228 return Err(PolicyError::EmptyRetries);
229 }
230 if retry.total_attempts == 1 {
231 return Ok(RetryPolicy::Never);
232 }
233
234 let initial = duration(retry.initial, Duration::ZERO)?;
235 let jitter = if retry.deterministic_jitter { Jitter::Deterministic } else { Jitter::None };
236 let backoff = match retry.maximum {
237 Some(maximum) => Backoff::Exponential {
238 initial,
239 maximum: duration(Some(maximum), Duration::ZERO)?,
240 jitter,
241 },
242 None => Backoff::Fixed { delay: initial, jitter },
243 };
244 let total_attempts = usize::try_from(retry.total_attempts).map_err(|_| PolicyError::EmptyRetries)?;
245 Ok(RetryPolicy::OnTransient { total_attempts, backoff })
246}
247
248fn from_nanos(nanos: u128) -> Duration {
250 Duration::new((nanos / 1_000_000_000) as u64, (nanos % 1_000_000_000) as u32)
251}
252
253