1use core::fmt;
9use core::num::{NonZeroU32, NonZeroU64};
10use core::str::FromStr;
11use std::collections::BTreeMap;
12
13use crate::ErrorClass;
14use serde::Deserialize;
15
16#[derive(Debug, Clone, PartialEq, Eq)]
19pub struct ParseError {
20 what: &'static str,
21 input: String,
22 note: Option<&'static str>,
26}
27
28impl ParseError {
29 fn new(what: &'static str, input: &str) -> Self {
30 Self {
31 what,
32 input: input.to_owned(),
33 note: None,
34 }
35 }
36
37 fn with_note(what: &'static str, input: &str, note: &'static str) -> Self {
38 Self {
39 what,
40 input: input.to_owned(),
41 note: Some(note),
42 }
43 }
44}
45
46impl fmt::Display for ParseError {
47 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
48 match self.note {
49 None => write!(f, "unparseable {} literal: {:?}", self.what, self.input),
50 Some(note) => write!(
51 f,
52 "invalid {} literal: {:?} — {note}",
53 self.what, self.input
54 ),
55 }
56 }
57}
58
59impl core::error::Error for ParseError {}
60
61#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Deserialize)]
63#[serde(try_from = "String")]
64pub struct DurationMs(pub u64);
65
66impl FromStr for DurationMs {
67 type Err = ParseError;
68
69 fn from_str(s: &str) -> Result<Self, Self::Err> {
70 let err = || ParseError::new("duration", s);
71 let s = s.trim();
72 let unit_at = s.find(|c: char| !c.is_ascii_digit()).ok_or_else(err)?;
73 let (number, unit) = s.split_at(unit_at);
74 let n: u64 = number.parse().map_err(|_| err())?;
75 let mult = match unit {
76 "ms" => 1,
77 "s" => 1_000,
78 "m" => 60_000,
79 "h" => 3_600_000,
80 _ => return Err(err()),
81 };
82 Ok(Self(n * mult))
83 }
84}
85
86impl TryFrom<String> for DurationMs {
87 type Error = ParseError;
88
89 fn try_from(s: String) -> Result<Self, Self::Error> {
90 s.parse()
91 }
92}
93
94#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize)]
96#[serde(try_from = "String")]
97pub struct Rate {
98 pub limit: NonZeroU64,
99 pub window_ms: u64,
100}
101
102impl FromStr for Rate {
103 type Err = ParseError;
104
105 fn from_str(s: &str) -> Result<Self, Self::Err> {
106 let err = || ParseError::new("rate", s);
107 let (limit, window) = s.trim().split_once('/').ok_or_else(err)?;
108 let limit: NonZeroU64 = limit.trim().parse().map_err(|_| err())?;
109 let window_ms = match window.trim() {
110 "s" | "sec" => 1_000,
111 "min" => 60_000,
112 "h" | "hour" => 3_600_000,
113 _ => return Err(err()),
114 };
115 Ok(Self { limit, window_ms })
116 }
117}
118
119impl TryFrom<String> for Rate {
120 type Error = ParseError;
121
122 fn try_from(s: String) -> Result<Self, Self::Error> {
123 s.parse()
124 }
125}
126
127#[derive(Debug, Clone, PartialEq, Deserialize)]
136#[serde(try_from = "String")]
137pub struct Schedule {
138 pub segments: Vec<ScheduleSegment>,
141}
142
143#[derive(Debug, Clone, Copy, PartialEq)]
145pub struct ScheduleSegment {
146 pub primary: SchedulePrimary,
147 pub up_to_ms: Option<u64>,
149}
150
151#[derive(Debug, Clone, Copy, PartialEq)]
153pub enum SchedulePrimary {
154 Exp {
155 base_ms: u64,
156 factor: f64,
157 cap_ms: u64,
158 jitter: bool,
159 },
160 Fixed {
161 period_ms: u64,
162 },
163}
164
165impl SchedulePrimary {
166 #[expect(
169 clippy::cast_precision_loss,
170 clippy::cast_possible_truncation,
171 clippy::cast_sign_loss,
172 clippy::cast_possible_wrap,
173 reason = "backoff arithmetic: values are small and non-negative by construction"
174 )]
175 fn wait_ms(self, attempt: u32) -> u64 {
176 match self {
177 Self::Exp {
178 base_ms,
179 factor,
180 cap_ms,
181 ..
182 } => {
183 let wait = base_ms as f64 * factor.powi(attempt as i32 - 1);
184 wait.min(cap_ms as f64).round() as u64
185 }
186 Self::Fixed { period_ms } => period_ms,
187 }
188 }
189
190 fn jitter(self) -> bool {
191 matches!(self, Self::Exp { jitter: true, .. })
192 }
193}
194
195impl Default for Schedule {
196 fn default() -> Self {
198 Self {
199 segments: vec![ScheduleSegment {
200 primary: SchedulePrimary::Exp {
201 base_ms: 200,
202 factor: 2.0,
203 cap_ms: 30_000,
204 jitter: true,
205 },
206 up_to_ms: None,
207 }],
208 }
209 }
210}
211
212impl Schedule {
213 #[must_use]
216 pub fn wait_ms(&self, attempt: u32) -> u64 {
217 self.wait_and_jitter(attempt).0
218 }
219
220 #[must_use]
232 pub fn wait_and_jitter(&self, attempt: u32) -> (u64, bool) {
233 let attempt = attempt.max(1);
234 let last = self.segments.len() - 1;
235 let (mut i, mut a, mut e) = (0_usize, 1_u32, 0_u64);
236 let mut emitted = 0_u32;
237 loop {
238 let segment = self.segments[i];
239 let wait = segment.primary.wait_ms(a);
240 if i < last
243 && let Some(bound) = segment.up_to_ms
244 && e.saturating_add(wait) > bound
245 {
246 (i, a, e) = (i + 1, 1, 0);
247 continue;
248 }
249 emitted += 1;
250 if emitted == attempt {
251 return (wait, segment.primary.jitter());
252 }
253 a += 1;
254 e = e.saturating_add(wait);
255 }
256 }
257}
258
259impl FromStr for SchedulePrimary {
260 type Err = ParseError;
261
262 fn from_str(s: &str) -> Result<Self, Self::Err> {
263 let err = || ParseError::new("schedule", s);
264 let s = s.trim();
265 if let Some(inner) = s.strip_prefix("exp(").and_then(|r| r.strip_suffix(')')) {
266 let parts: Vec<&str> = inner.split(',').map(str::trim).collect();
267 let [base, factor, rest @ ..] = parts.as_slice() else {
268 return Err(err());
269 };
270 let base_ms = base.parse::<DurationMs>().map_err(|_| err())?.0;
271 let factor: f64 = factor
272 .strip_prefix('x')
273 .ok_or_else(err)?
274 .parse()
275 .map_err(|_| err())?;
276 let mut cap_ms = u64::MAX;
277 let mut jitter = false;
278 for part in rest {
279 if let Some(d) = part.strip_prefix("max ") {
280 cap_ms = d.parse::<DurationMs>().map_err(|_| err())?.0;
281 } else if *part == "jitter" {
282 jitter = true;
283 } else {
284 return Err(err());
285 }
286 }
287 Ok(Self::Exp {
288 base_ms,
289 factor,
290 cap_ms,
291 jitter,
292 })
293 } else if let Some(inner) = s.strip_prefix("fixed(").and_then(|r| r.strip_suffix(')')) {
294 let period_ms = inner.parse::<DurationMs>().map_err(|_| err())?.0;
295 Ok(Self::Fixed { period_ms })
296 } else {
297 Err(err())
298 }
299 }
300}
301
302impl FromStr for Schedule {
303 type Err = ParseError;
304
305 fn from_str(s: &str) -> Result<Self, Self::Err> {
306 let err = || ParseError::new("schedule", s);
307 let tokens: Vec<&str> = s.split_whitespace().collect();
314 if tokens.is_empty() {
315 return Err(err());
316 }
317 let mut segments = Vec::new();
318 for segment_tokens in tokens.split(|t| *t == "andThen") {
319 let (primary_tokens, up_to_ms) = match segment_tokens.iter().position(|t| *t == "upTo")
320 {
321 None => (segment_tokens, None),
322 Some(pos) => {
323 let [duration] = &segment_tokens[pos + 1..] else {
325 return Err(err());
326 };
327 let bound = duration.parse::<DurationMs>().map_err(|_| err())?.0;
328 (&segment_tokens[..pos], Some(bound))
329 }
330 };
331 if primary_tokens.is_empty() {
332 return Err(err());
333 }
334 let primary: SchedulePrimary = primary_tokens.join(" ").parse().map_err(|_| err())?;
335 segments.push(ScheduleSegment { primary, up_to_ms });
336 }
337 let last = segments.len() - 1;
341 if segments
342 .iter()
343 .enumerate()
344 .any(|(i, segment)| (i < last) != segment.up_to_ms.is_some())
345 {
346 return Err(ParseError::with_note(
347 "schedule",
348 s,
349 "`upTo` must bound every segment except the last, and never the last \
350 (an unbounded segment never hands off; a bounded tail would leave \
351 attempts without a wait — cap total retrying with `attempts`)",
352 ));
353 }
354 Ok(Self { segments })
355 }
356}
357
358impl TryFrom<String> for Schedule {
359 type Error = ParseError;
360
361 fn try_from(s: String) -> Result<Self, Self::Error> {
362 s.parse()
363 }
364}
365
366#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize)]
369#[serde(try_from = "String")]
370pub enum Condition {
371 Conn,
372 Timeout,
373 Cancelled,
374 Other,
375 Class4xx,
376 Class5xx,
377 Status(u16),
378}
379
380impl Condition {
381 pub fn matches(self, class: ErrorClass, http_status: Option<u16>) -> bool {
382 match self {
383 Self::Conn => class == ErrorClass::Conn,
384 Self::Timeout => class == ErrorClass::Timeout,
385 Self::Cancelled => class == ErrorClass::Cancelled,
386 Self::Other => class == ErrorClass::Other,
387 Self::Class4xx => {
388 class == ErrorClass::Http && http_status.is_some_and(|s| (400..=499).contains(&s))
389 }
390 Self::Class5xx => {
391 class == ErrorClass::Http && http_status.is_some_and(|s| (500..=599).contains(&s))
392 }
393 Self::Status(want) => class == ErrorClass::Http && http_status == Some(want),
394 }
395 }
396}
397
398impl FromStr for Condition {
399 type Err = ParseError;
400
401 fn from_str(s: &str) -> Result<Self, Self::Err> {
402 match s {
403 "conn" => Ok(Self::Conn),
404 "timeout" => Ok(Self::Timeout),
405 "cancelled" => Ok(Self::Cancelled),
406 "other" => Ok(Self::Other),
407 "4xx" => Ok(Self::Class4xx),
408 "5xx" => Ok(Self::Class5xx),
409 exact if exact.len() == 3 && exact.bytes().all(|b| b.is_ascii_digit()) => {
413 let code: u16 = exact
414 .parse()
415 .map_err(|_| ParseError::new("retry condition", s))?;
416 if (100..=599).contains(&code) {
417 Ok(Self::Status(code))
418 } else {
419 Err(ParseError::new("retry condition", s))
420 }
421 }
422 _ => Err(ParseError::new("retry condition", s)),
423 }
424 }
425}
426
427impl TryFrom<String> for Condition {
428 type Error = ParseError;
429
430 fn try_from(s: String) -> Result<Self, Self::Error> {
431 s.parse()
432 }
433}
434
435#[derive(Debug, Clone, PartialEq, Deserialize)]
438#[serde(default, deny_unknown_fields)]
439pub struct RetryPolicy {
440 pub attempts: NonZeroU32,
441 pub schedule: Schedule,
442 pub on: Vec<Condition>,
443}
444
445impl RetryPolicy {
446 pub const DEFAULT_ATTEMPTS: NonZeroU32 = NonZeroU32::new(3).unwrap();
447
448 pub fn default_on() -> Vec<Condition> {
450 vec![
451 Condition::Conn,
452 Condition::Timeout,
453 Condition::Status(429),
454 Condition::Class5xx,
455 ]
456 }
457
458 pub fn is_retryable(&self, class: ErrorClass, http_status: Option<u16>) -> bool {
459 self.on.iter().any(|c| c.matches(class, http_status))
460 }
461}
462
463impl Default for RetryPolicy {
464 fn default() -> Self {
465 Self {
466 attempts: Self::DEFAULT_ATTEMPTS,
467 schedule: Schedule::default(),
468 on: Self::default_on(),
469 }
470 }
471}
472
473#[derive(Debug, Clone, PartialEq, Deserialize)]
488#[serde(try_from = "BreakerPolicyDe")]
489pub struct BreakerPolicy {
490 pub failures: Option<NonZeroU64>,
493 pub cooldown: DurationMs,
494 pub window: Option<DurationMs>,
495 pub failure_rate: Option<f64>,
496 pub min_calls: Option<NonZeroU32>,
497}
498
499#[derive(Debug, Clone, Copy, PartialEq)]
502pub enum BreakerMode {
503 Count { failures: NonZeroU64 },
505 Rate {
507 window: DurationMs,
508 failure_rate: f64,
509 min_calls: NonZeroU32,
510 },
511}
512
513impl BreakerPolicy {
514 pub const DEFAULT_FAILURES: NonZeroU64 = NonZeroU64::new(5).unwrap();
516 pub const DEFAULT_MIN_CALLS: NonZeroU32 = NonZeroU32::new(10).unwrap();
518
519 #[must_use]
524 pub fn mode(&self) -> BreakerMode {
525 match (self.failures, self.window, self.failure_rate) {
526 (None, Some(window), Some(failure_rate)) => BreakerMode::Rate {
527 window,
528 failure_rate,
529 min_calls: self.min_calls.unwrap_or(Self::DEFAULT_MIN_CALLS),
530 },
531 (failures, _, _) => BreakerMode::Count {
532 failures: failures.unwrap_or(Self::DEFAULT_FAILURES),
533 },
534 }
535 }
536
537 #[must_use]
541 pub fn has_inert_rate_knobs(&self) -> bool {
542 self.failures.is_some()
543 && (self.window.is_some() || self.failure_rate.is_some() || self.min_calls.is_some())
544 }
545}
546
547#[derive(Deserialize)]
550#[serde(default, deny_unknown_fields)]
551struct BreakerPolicyDe {
552 failures: Option<NonZeroU64>,
553 cooldown: DurationMs,
554 window: Option<DurationMs>,
555 #[serde(deserialize_with = "de_failure_rate")]
556 failure_rate: Option<f64>,
557 min_calls: Option<NonZeroU32>,
558}
559
560impl Default for BreakerPolicyDe {
561 fn default() -> Self {
562 Self {
563 failures: None,
564 cooldown: DurationMs(15_000),
565 window: None,
566 failure_rate: None,
567 min_calls: None,
568 }
569 }
570}
571
572impl TryFrom<BreakerPolicyDe> for BreakerPolicy {
573 type Error = String;
574
575 fn try_from(de: BreakerPolicyDe) -> Result<Self, Self::Error> {
576 let rate_pair = de.window.is_some() && de.failure_rate.is_some();
577 let any_rate_knob =
578 de.window.is_some() || de.failure_rate.is_some() || de.min_calls.is_some();
579 if de.failures.is_none() && any_rate_knob && !rate_pair {
580 return Err(String::from(
581 "breaker rate mode requires both `window` and `failure_rate` \
582 (count mode sets `failures` instead)",
583 ));
584 }
585 Ok(Self {
586 failures: de.failures,
587 cooldown: de.cooldown,
588 window: de.window,
589 failure_rate: de.failure_rate,
590 min_calls: de.min_calls,
591 })
592 }
593}
594
595fn de_failure_rate<'de, D>(deserializer: D) -> Result<Option<f64>, D::Error>
600where
601 D: serde::Deserializer<'de>,
602{
603 let value = Option::<f64>::deserialize(deserializer)?;
604 if let Some(rate) = value
605 && !(rate > 0.0 && rate <= 1.0)
606 {
607 return Err(serde::de::Error::custom(format!(
608 "breaker.failure_rate must be greater than 0 and at most 1 (got {rate})"
609 )));
610 }
611 Ok(value)
612}
613
614impl Default for BreakerPolicy {
615 fn default() -> Self {
616 Self {
617 failures: None,
618 cooldown: DurationMs(15_000),
619 window: None,
620 failure_rate: None,
621 min_calls: None,
622 }
623 }
624}
625
626#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Deserialize)]
627#[serde(rename_all = "snake_case")]
628pub enum CacheScope {
629 #[default]
630 Memory,
631 Persistent,
632}
633
634#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Deserialize)]
635#[serde(rename_all = "snake_case")]
636pub enum CacheMode {
637 #[default]
638 Always,
639 Dev,
641}
642
643#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Deserialize)]
644#[serde(rename_all = "snake_case")]
645pub enum CacheKeySource {
646 #[default]
647 Args,
648 Url,
649}
650
651#[derive(Debug, Clone, PartialEq, Default, Deserialize)]
653#[serde(default, deny_unknown_fields)]
654pub struct CachePolicy {
655 pub ttl: Option<DurationMs>,
656 pub scope: CacheScope,
657 pub mode: CacheMode,
658 pub key: CacheKeySource,
659}
660
661#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
663#[serde(deny_unknown_fields)]
664pub struct IdempotencyPolicy {
665 pub header: String,
666}
667
668#[derive(Debug, Clone, PartialEq, Default, Deserialize)]
671#[serde(default, deny_unknown_fields)]
672pub struct TargetPolicy {
673 pub timeout: Option<DurationMs>,
674 pub retry: Option<RetryPolicy>,
675 pub breaker: Option<BreakerPolicy>,
676 pub rate: Option<Rate>,
677 pub cache: Option<CachePolicy>,
678 pub idempotency: Option<IdempotencyPolicy>,
679 pub fallback: Option<Vec<String>>,
680 pub budget: Option<String>,
681}
682
683#[derive(Debug, Clone, PartialEq, Default, Deserialize)]
684#[serde(default, deny_unknown_fields)]
685pub struct Defaults {
686 pub outbound: Option<TargetPolicy>,
687 pub llm: Option<TargetPolicy>,
688}
689
690#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Deserialize)]
691#[serde(rename_all = "snake_case")]
692pub enum NondeterminismResponse {
693 #[default]
694 Fail,
695 Warn,
696 Branch,
697}
698
699#[derive(Debug, Clone, PartialEq, Eq, Default, Deserialize)]
701#[serde(default, deny_unknown_fields)]
702pub struct FlowsPolicy {
703 pub entrypoints: Vec<String>,
704 pub on_nondeterminism: NondeterminismResponse,
705}
706
707#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
714#[serde(try_from = "String")]
715pub struct JournalLocation(pub String);
716
717impl FromStr for JournalLocation {
718 type Err = ParseError;
719
720 fn from_str(s: &str) -> Result<Self, Self::Err> {
721 let valid = s.strip_prefix("file:").is_some_and(|rest| !rest.is_empty())
722 || s.strip_prefix("postgres://")
723 .is_some_and(|rest| !rest.is_empty());
724 if valid {
725 Ok(Self(s.to_owned()))
726 } else {
727 Err(ParseError::new("journal location", s))
728 }
729 }
730}
731
732impl TryFrom<String> for JournalLocation {
733 type Error = ParseError;
734
735 fn try_from(s: String) -> Result<Self, Self::Error> {
736 s.parse()
737 }
738}
739
740#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
749#[serde(default, deny_unknown_fields)]
750pub struct TelemetryPolicy {
751 pub otlp_endpoint: Option<String>,
752 pub console: bool,
753}
754
755impl Default for TelemetryPolicy {
756 fn default() -> Self {
757 Self {
759 otlp_endpoint: None,
760 console: true,
761 }
762 }
763}
764
765#[derive(Debug, Clone, PartialEq, Default, Deserialize)]
774#[serde(default, deny_unknown_fields)]
775pub struct Policy {
776 pub defaults: Defaults,
777 pub target: BTreeMap<String, TargetPolicy>,
778 pub flows: Option<FlowsPolicy>,
779 pub journal: Option<JournalLocation>,
782 pub telemetry: Option<TelemetryPolicy>,
786}
787
788#[derive(Debug, Clone, Default)]
791pub struct ResolvedPolicy {
792 pub timeout: Option<DurationMs>,
793 pub retry: Option<RetryPolicy>,
794 pub breaker: Option<BreakerPolicy>,
795 pub rate: Option<Rate>,
796 pub cache: Option<CachePolicy>,
797 pub idempotency: Option<IdempotencyPolicy>,
802}
803
804impl Policy {
805 pub fn resolve(&self, target: &str) -> ResolvedPolicy {
806 ResolvedPolicy {
807 timeout: self.layer(target, |t| t.timeout.as_ref()).copied(),
808 retry: self.layer(target, |t| t.retry.as_ref()).cloned(),
809 breaker: self.layer(target, |t| t.breaker.as_ref()).cloned(),
810 rate: self.layer(target, |t| t.rate.as_ref()).copied(),
811 cache: self.layer(target, |t| t.cache.as_ref()).cloned(),
812 idempotency: self.layer(target, |t| t.idempotency.as_ref()).cloned(),
813 }
814 }
815
816 fn layer<'a, T>(
817 &'a self,
818 target: &str,
819 pick: impl Fn(&'a TargetPolicy) -> Option<&'a T>,
820 ) -> Option<&'a T> {
821 if let Some(t) = self.target.get(target)
822 && let Some(v) = pick(t)
823 {
824 return Some(v);
825 }
826 if target.starts_with("llm:")
827 && let Some(llm) = self.defaults.llm.as_ref()
828 && let Some(v) = pick(llm)
829 {
830 return Some(v);
831 }
832 self.defaults.outbound.as_ref().and_then(pick)
833 }
834}
835
836#[cfg(test)]
837mod tests {
838 use super::*;
839 use serde_json::json;
840
841 #[test]
842 fn duration_literals() {
843 assert_eq!("200ms".parse(), Ok(DurationMs(200)));
844 assert_eq!("30s".parse(), Ok(DurationMs(30_000)));
845 assert_eq!("5m".parse(), Ok(DurationMs(300_000)));
846 assert_eq!("2h".parse(), Ok(DurationMs(7_200_000)));
847 assert!("30".parse::<DurationMs>().is_err());
848 assert!("30sec".parse::<DurationMs>().is_err());
849 assert!("-1s".parse::<DurationMs>().is_err());
850 }
851
852 #[test]
853 fn rate_literals() {
854 let rate: Rate = "90/s".parse().unwrap();
855 assert_eq!((rate.limit.get(), rate.window_ms), (90, 1_000));
856 let rate: Rate = "60/min".parse().unwrap();
857 assert_eq!((rate.limit.get(), rate.window_ms), (60, 60_000));
858 assert!("0/s".parse::<Rate>().is_err(), "zero limit unrepresentable");
859 assert!("10/day".parse::<Rate>().is_err());
860 }
861
862 #[test]
863 fn schedule_exp_waits_and_cap() {
864 let schedule: Schedule = "exp(1s, x2, max 4s)".parse().unwrap();
865 let waits: Vec<u64> = (1..=4).map(|n| schedule.wait_ms(n)).collect();
866 assert_eq!(waits, [1_000, 2_000, 4_000, 4_000]);
867 }
868
869 #[test]
870 fn schedule_fixed_and_rejections() {
871 assert_eq!(
872 "fixed(1s)".parse::<Schedule>(),
873 Ok(Schedule {
874 segments: vec![ScheduleSegment {
875 primary: SchedulePrimary::Fixed { period_ms: 1_000 },
876 up_to_ms: None,
877 }],
878 })
879 );
880 assert!("linear(1s)".parse::<Schedule>().is_err());
881 }
882
883 #[test]
884 fn schedule_composition_parses_the_spec_example() {
885 let schedule: Schedule = "exp(1s, x2, max 5m) upTo 10m andThen fixed(1m)"
887 .parse()
888 .unwrap();
889 assert_eq!(
890 schedule.segments,
891 vec![
892 ScheduleSegment {
893 primary: SchedulePrimary::Exp {
894 base_ms: 1_000,
895 factor: 2.0,
896 cap_ms: 300_000,
897 jitter: false,
898 },
899 up_to_ms: Some(600_000),
900 },
901 ScheduleSegment {
902 primary: SchedulePrimary::Fixed { period_ms: 60_000 },
903 up_to_ms: None,
904 },
905 ]
906 );
907 assert_eq!(
909 "exp(1s, x2, max 5m) upTo 10m andThen fixed(1m)".parse::<Schedule>(),
910 Ok(schedule)
911 );
912 }
913
914 #[test]
915 fn schedule_composition_hands_off_when_the_bound_would_be_overshot() {
916 let schedule: Schedule = "exp(1s, x2) upTo 4s andThen fixed(500ms)".parse().unwrap();
917 let waits: Vec<u64> = (1..=5).map(|n| schedule.wait_ms(n)).collect();
918 assert_eq!(waits, [1_000, 2_000, 500, 500, 500]);
920 }
921
922 #[test]
923 fn schedule_composition_exact_fit_stays_and_cascade_skips() {
924 let schedule: Schedule =
925 "fixed(1s) upTo 3s andThen fixed(10s) upTo 5s andThen fixed(250ms)"
926 .parse()
927 .unwrap();
928 let waits: Vec<u64> = (1..=6).map(|n| schedule.wait_ms(n)).collect();
929 assert_eq!(waits, [1_000, 1_000, 1_000, 250, 250, 250]);
933 }
934
935 #[test]
936 fn schedule_composition_restarts_exp_and_tracks_jitter_per_segment() {
937 let schedule: Schedule = "fixed(1s) upTo 2s andThen exp(100ms, x3, jitter)"
938 .parse()
939 .unwrap();
940 let waits: Vec<u64> = (1..=5).map(|n| schedule.wait_ms(n)).collect();
942 assert_eq!(waits, [1_000, 1_000, 100, 300, 900]);
943 assert_eq!(schedule.wait_and_jitter(1), (1_000, false));
945 assert_eq!(schedule.wait_and_jitter(3), (100, true));
946 }
947
948 #[test]
949 fn schedule_composition_shape_rule_rejections() {
950 for degenerate in [
955 "fixed(1s) andThen fixed(2s)",
956 "exp(1s, x2, max 5m) upTo 10m",
957 "fixed(1s) upTo 3s andThen fixed(2s) andThen fixed(4s)",
958 "fixed(1s) upTo 3s andThen fixed(2s) upTo 5s",
959 ] {
960 let error = degenerate.parse::<Schedule>().unwrap_err();
961 assert!(
962 error.to_string().contains("upTo"),
963 "{degenerate}: expected the shape-rule note, got {error}"
964 );
965 }
966 for broken in [
968 "fixed(1s) upTo",
969 "upTo 3s andThen fixed(1s)",
970 "fixed(1s) upTo 1s upTo 2s andThen fixed(1s)",
971 "fixed(1s) andThen",
972 "andThen fixed(1s)",
973 "fixed(1s) upTo 3s fixed(2s)",
974 ] {
975 assert!(
976 broken.parse::<Schedule>().is_err(),
977 "{broken} must be rejected"
978 );
979 }
980 }
981
982 #[test]
983 fn condition_matching() {
984 let on = RetryPolicy::default_on();
985 let matches = |class, status| on.iter().any(|c| c.matches(class, status));
986 assert!(matches(ErrorClass::Conn, None));
987 assert!(matches(ErrorClass::Http, Some(429)));
988 assert!(matches(ErrorClass::Http, Some(503)));
989 assert!(!matches(ErrorClass::Http, Some(400)));
990 assert!(!matches(ErrorClass::Cancelled, None));
991 assert!("teapot".parse::<Condition>().is_err());
992 assert_eq!("429".parse::<Condition>(), Ok(Condition::Status(429)));
994 assert_eq!("100".parse::<Condition>(), Ok(Condition::Status(100)));
995 assert_eq!("599".parse::<Condition>(), Ok(Condition::Status(599)));
996 for bad in ["999", "099", "600", "000", "12", "1234", "1x9"] {
997 assert!(bad.parse::<Condition>().is_err(), "{bad} must be rejected");
998 }
999 }
1000
1001 #[test]
1002 fn zero_attempts_is_unrepresentable() {
1003 let doc = json!({ "target": { "x": { "retry": { "attempts": 0 } } } });
1004 let err = serde_path_to_error::deserialize::<_, Policy>(&doc).unwrap_err();
1005 assert_eq!(err.path().to_string(), "target.x.retry.attempts");
1006 }
1007
1008 #[test]
1009 fn breaker_failure_rate_range_is_enforced() {
1010 let bad = |rate: serde_json::Value| {
1012 let doc = json!({ "target": { "x": { "breaker": { "failure_rate": rate } } } });
1013 serde_path_to_error::deserialize::<_, Policy>(&doc)
1014 };
1015 for rate in [json!(0.0), json!(-0.1), json!(1.5), json!(2.0)] {
1016 let err = bad(rate.clone()).unwrap_err();
1017 assert_eq!(
1018 err.path().to_string(),
1019 "target.x.breaker.failure_rate",
1020 "out-of-range failure_rate {rate} must fail at its path"
1021 );
1022 }
1023 for rate in [0.01_f64, 0.5, 1.0] {
1026 let doc = json!({
1027 "target": { "x": { "breaker": { "window": "30s", "failure_rate": rate } } }
1028 });
1029 let policy = serde_path_to_error::deserialize::<_, Policy>(&doc).unwrap();
1030 let breaker = policy.target["x"].breaker.as_ref().unwrap();
1031 assert_eq!(breaker.failure_rate, Some(rate));
1032 }
1033 }
1034
1035 #[test]
1036 fn breaker_mode_selection_follows_the_schema() {
1037 let breaker = |doc: serde_json::Value| -> BreakerPolicy {
1038 let doc = json!({ "target": { "x": { "breaker": doc } } });
1039 let policy: Policy = serde_path_to_error::deserialize(&doc).unwrap();
1040 policy.target["x"].breaker.clone().unwrap()
1041 };
1042
1043 assert_eq!(
1045 breaker(json!({})).mode(),
1046 BreakerMode::Count {
1047 failures: BreakerPolicy::DEFAULT_FAILURES
1048 }
1049 );
1050
1051 assert_eq!(
1053 breaker(json!({ "window": "30s", "failure_rate": 0.5 })).mode(),
1054 BreakerMode::Rate {
1055 window: DurationMs(30_000),
1056 failure_rate: 0.5,
1057 min_calls: BreakerPolicy::DEFAULT_MIN_CALLS,
1058 }
1059 );
1060 assert_eq!(
1061 breaker(json!({ "window": "10s", "failure_rate": 1.0, "min_calls": 4 })).mode(),
1062 BreakerMode::Rate {
1063 window: DurationMs(10_000),
1064 failure_rate: 1.0,
1065 min_calls: NonZeroU32::new(4).unwrap(),
1066 }
1067 );
1068
1069 let mixed = breaker(json!({ "failures": 3, "window": "30s", "failure_rate": 0.5 }));
1072 assert_eq!(
1073 mixed.mode(),
1074 BreakerMode::Count {
1075 failures: NonZeroU64::new(3).unwrap()
1076 }
1077 );
1078 assert!(mixed.has_inert_rate_knobs());
1079 assert!(!breaker(json!({ "failures": 3 })).has_inert_rate_knobs());
1080 }
1081
1082 #[test]
1083 fn half_configured_breaker_rate_mode_is_rejected() {
1084 for doc in [
1088 json!({ "window": "30s" }),
1089 json!({ "failure_rate": 0.5 }),
1090 json!({ "min_calls": 10 }),
1091 json!({ "window": "30s", "min_calls": 10 }),
1092 json!({ "failure_rate": 0.5, "min_calls": 10 }),
1093 ] {
1094 let policy = json!({ "target": { "x": { "breaker": doc } } });
1095 let err = serde_path_to_error::deserialize::<_, Policy>(&policy).unwrap_err();
1096 assert_eq!(err.path().to_string(), "target.x.breaker", "doc: {doc}");
1097 assert!(
1098 err.inner().to_string().contains("rate mode requires both"),
1099 "doc {doc}: got {}",
1100 err.inner()
1101 );
1102 }
1103 let policy =
1106 json!({ "target": { "x": { "breaker": { "failures": 3, "window": "30s" } } } });
1107 assert!(serde_path_to_error::deserialize::<_, Policy>(&policy).is_ok());
1108 }
1109
1110 #[test]
1111 fn unknown_key_is_rejected_with_its_path() {
1112 let doc = json!({ "target": { "api.stripe.com": { "retry": { "atempts": 10 } } } });
1116 let err = serde_path_to_error::deserialize::<_, Policy>(&doc).unwrap_err();
1117 assert!(
1118 err.inner().to_string().contains("atempts")
1119 || err.inner().to_string().contains("unknown field"),
1120 "expected an unknown-field error, got {}",
1121 err.inner()
1122 );
1123 }
1124
1125 #[test]
1126 fn unknown_top_level_and_layer_keys_are_rejected() {
1127 assert!(
1128 serde_path_to_error::deserialize::<_, Policy>(&json!({ "bogus_top": true })).is_err()
1129 );
1130 assert!(
1131 serde_path_to_error::deserialize::<_, Policy>(
1132 &json!({ "target": { "api.x": { "retrys": {} } } })
1133 )
1134 .is_err(),
1135 "a mistyped layer table must be rejected, not dropped"
1136 );
1137 }
1138
1139 #[test]
1140 fn journal_and_telemetry_parse_and_validate() {
1141 let doc = json!({
1142 "journal": "file:/srv/keel/journal.db",
1143 "telemetry": { "otlp_endpoint": "http://collector:4317" }
1144 });
1145 let policy: Policy = serde_path_to_error::deserialize(&doc).unwrap();
1146 assert_eq!(
1147 policy.journal.unwrap(),
1148 JournalLocation("file:/srv/keel/journal.db".to_owned())
1149 );
1150 let telemetry = policy.telemetry.unwrap();
1151 assert_eq!(
1152 telemetry.otlp_endpoint.as_deref(),
1153 Some("http://collector:4317")
1154 );
1155 assert!(telemetry.console, "schema default console = true");
1156
1157 let bad = json!({ "journal": "sqlite:/tmp/x.db" });
1159 assert!(serde_path_to_error::deserialize::<_, Policy>(&bad).is_err());
1160 }
1161
1162 #[test]
1163 fn idempotency_resolves_like_any_other_layer() {
1164 let doc = json!({
1168 "defaults": {
1169 "outbound": { "idempotency": { "header": "X-Idem" } },
1170 "llm": { "idempotency": { "header": "X-Llm-Idem" } }
1171 },
1172 "target": {
1173 "api.stripe.com": { "idempotency": { "header": "Idempotency-Key" } },
1174 "api.plain.example": { "timeout": "1s" }
1175 }
1176 });
1177 let policy: Policy = serde_path_to_error::deserialize(&doc).unwrap();
1178
1179 let stripe = policy.resolve("api.stripe.com");
1181 assert_eq!(
1182 stripe.idempotency.as_ref().map(|i| i.header.as_str()),
1183 Some("Idempotency-Key")
1184 );
1185 let llm = policy.resolve("llm:openai");
1187 assert_eq!(
1188 llm.idempotency.as_ref().map(|i| i.header.as_str()),
1189 Some("X-Llm-Idem")
1190 );
1191 let plain = policy.resolve("api.plain.example");
1192 assert_eq!(
1193 plain.idempotency.as_ref().map(|i| i.header.as_str()),
1194 Some("X-Idem")
1195 );
1196 let empty: Policy = serde_path_to_error::deserialize(&json!({})).unwrap();
1198 assert!(empty.resolve("api.stripe.com").idempotency.is_none());
1199 }
1200
1201 #[test]
1202 fn layer_resolution_precedence() {
1203 let doc = json!({
1204 "defaults": {
1205 "outbound": { "retry": { "attempts": 3 }, "rate": "9/s" },
1206 "llm": { "retry": { "attempts": 6 } }
1207 },
1208 "target": { "llm:openai": { "cache": { "ttl": "10m" } } }
1209 });
1210 let policy: Policy = serde_path_to_error::deserialize(&doc).unwrap();
1211
1212 let llm = policy.resolve("llm:openai");
1215 assert_eq!(llm.cache.unwrap().ttl, Some(DurationMs(600_000)));
1216 assert_eq!(llm.retry.unwrap().attempts.get(), 6);
1217 assert_eq!(llm.rate.unwrap().limit.get(), 9);
1218
1219 let plain = policy.resolve("api.example.com");
1221 assert_eq!(plain.retry.unwrap().attempts.get(), 3);
1222 assert!(plain.cache.is_none());
1223 }
1224}