pub(crate) const MAX_PATH_STEPS: usize = 32;
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) struct PathMark {
len: usize,
truncated: bool,
}
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub(crate) struct StepPath {
steps: Vec<String>,
truncated: bool,
walks: Vec<PathMark>,
}
impl StepPath {
pub(crate) fn attempt(&mut self, attempt: u32) {
if attempt <= 1 {
self.walks.push(PathMark {
len: self.steps.len(),
truncated: self.truncated,
});
return;
}
let mark = self.walks.last().copied().unwrap_or(PathMark {
len: 0,
truncated: false,
});
self.steps.truncate(mark.len);
self.truncated = mark.truncated;
}
pub(crate) fn exit(&mut self) {
self.walks.pop();
}
pub(crate) fn push(&mut self, node_id: &str) {
if self.steps.last().is_some_and(|last| last == node_id) {
return;
}
if self.steps.len() >= MAX_PATH_STEPS {
self.truncated = true;
return;
}
self.steps.push(node_id.to_string());
}
pub(crate) fn steps(&self) -> &[String] {
&self.steps
}
pub(crate) fn truncated(&self) -> bool {
self.truncated
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn consecutive_duplicates_collapse_but_revisits_are_kept() {
let mut path = StepPath::default();
for node in ["a", "a", "b", "b", "b", "a"] {
path.push(node);
}
assert_eq!(path.steps(), ["a", "b", "a"]);
assert!(!path.truncated());
}
#[test]
fn a_retry_of_the_top_level_walk_keeps_only_the_last_attempt() {
let mut path = StepPath::default();
path.attempt(1);
for node in ["a", "b"] {
path.push(node);
}
path.attempt(2);
for node in ["a", "b", "c"] {
path.push(node);
}
path.exit();
assert_eq!(path.steps(), ["a", "b", "c"]);
}
#[test]
fn a_retry_that_follows_a_cut_attempt_is_not_cut() {
let mut path = StepPath::default();
path.attempt(1);
for i in 0..40 {
path.push(&format!("n{i}"));
}
assert!(path.truncated());
path.attempt(2);
path.push("ok");
assert_eq!(path.steps(), ["ok"]);
assert!(!path.truncated(), "the failed attempt's cut is discarded");
}
#[test]
fn a_callee_retry_rewinds_only_the_callee() {
let mut path = StepPath::default();
path.attempt(1); path.push("call");
path.attempt(1); path.push("hello");
path.push("flaky");
path.attempt(2); path.push("hello");
path.push("flaky");
path.exit(); path.push("ask");
path.exit();
assert_eq!(path.steps(), ["call", "hello", "flaky", "ask"]);
}
#[test]
fn the_cap_keeps_the_first_32_steps_and_marks_the_path_truncated() {
let mut path = StepPath::default();
for i in 0..MAX_PATH_STEPS {
path.push(&format!("n{i}"));
}
assert_eq!(path.steps().len(), MAX_PATH_STEPS);
assert!(!path.truncated(), "exactly at the cap is not truncated");
path.push(&format!("n{}", MAX_PATH_STEPS - 1));
assert!(!path.truncated());
path.push("one_too_many");
assert!(path.truncated());
assert_eq!(path.steps().len(), MAX_PATH_STEPS);
assert_eq!(path.steps()[0], "n0");
assert_eq!(path.steps()[MAX_PATH_STEPS - 1], "n31");
}
}