Skip to main content

aft_base/compress/
caps.rs

1use std::collections::BTreeMap;
2
3pub const CAP_ERRORS: usize = 20;
4pub const CAP_WARNINGS: usize = 10;
5pub const CAP_LIST: usize = 20;
6pub const CAP_INVENTORY: usize = 50;
7pub const COMPLETION_FAILURE_TAIL_BYTES: usize = 1792;
8
9#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
10pub enum DropClass {
11    Error,
12    Warning,
13    Failure,
14    Issue,
15    List,
16    Inventory,
17    Timing,
18}
19
20impl DropClass {
21    pub fn default_cap(self) -> usize {
22        match self {
23            Self::Error | Self::Failure => CAP_ERRORS,
24            Self::Warning => CAP_WARNINGS,
25            Self::Issue | Self::List | Self::Timing => CAP_LIST,
26            Self::Inventory => CAP_INVENTORY,
27        }
28    }
29
30    pub fn singular(self) -> &'static str {
31        match self {
32            Self::Error => "error",
33            Self::Warning => "warning",
34            Self::Failure => "failure",
35            Self::Issue => "issue",
36            Self::List => "list item",
37            Self::Inventory => "inventory item",
38            Self::Timing => "timing line",
39        }
40    }
41
42    pub fn plural(self) -> &'static str {
43        match self {
44            Self::Error => "errors",
45            Self::Warning => "warnings",
46            Self::Failure => "failures",
47            Self::Issue => "issues",
48            Self::List => "list items",
49            Self::Inventory => "inventory items",
50            Self::Timing => "timing lines",
51        }
52    }
53}
54
55#[derive(Debug, Clone, PartialEq, Eq)]
56pub struct ClassifiedBlock {
57    pub class: Option<DropClass>,
58    pub text: String,
59}
60
61impl ClassifiedBlock {
62    pub fn new(class: DropClass, text: impl Into<String>) -> Self {
63        Self {
64            class: Some(class),
65            text: text.into(),
66        }
67    }
68
69    pub fn unclassified(text: impl Into<String>) -> Self {
70        Self {
71            class: None,
72            text: text.into(),
73        }
74    }
75}
76
77#[derive(Debug, Clone, PartialEq, Eq, Default)]
78pub struct ClassCapResult {
79    pub text: String,
80    pub dropped_by_class: BTreeMap<DropClass, usize>,
81}
82
83pub fn cap_classified_blocks(blocks: Vec<ClassifiedBlock>) -> ClassCapResult {
84    cap_classified_blocks_with(blocks, DropClass::default_cap)
85}
86
87pub fn cap_classified_blocks_with<F>(blocks: Vec<ClassifiedBlock>, cap_for: F) -> ClassCapResult
88where
89    F: Fn(DropClass) -> usize,
90{
91    let mut seen_by_class: BTreeMap<DropClass, usize> = BTreeMap::new();
92    let mut dropped_by_class: BTreeMap<DropClass, usize> = BTreeMap::new();
93    let mut kept = Vec::new();
94
95    for block in blocks {
96        let Some(class) = block.class else {
97            kept.push(block.text);
98            continue;
99        };
100
101        let seen = seen_by_class.entry(class).or_default();
102        *seen += 1;
103        if *seen <= cap_for(class) {
104            kept.push(block.text);
105        } else {
106            *dropped_by_class.entry(class).or_default() += 1;
107        }
108    }
109
110    ClassCapResult {
111        text: join_blocks(kept),
112        dropped_by_class,
113    }
114}
115
116pub fn join_blocks(blocks: Vec<String>) -> String {
117    blocks
118        .into_iter()
119        .map(|block| block.trim_end().to_string())
120        .filter(|block| !block.is_empty())
121        .collect::<Vec<_>>()
122        .join("\n")
123}
124
125#[cfg(test)]
126mod tests {
127    use super::*;
128
129    #[test]
130    fn keeps_error_and_warning_blocks_spread_through_long_stream() {
131        let mut blocks = Vec::new();
132        for index in 0..40 {
133            blocks.push(ClassifiedBlock::new(
134                DropClass::Error,
135                format!("error {index}\n  error context {index}"),
136            ));
137            if index < 20 {
138                blocks.push(ClassifiedBlock::new(
139                    DropClass::Warning,
140                    format!("warning {index}\n  warning context {index}"),
141                ));
142            }
143            blocks.push(ClassifiedBlock::unclassified(format!("progress {index}")));
144        }
145
146        let capped = cap_classified_blocks(blocks);
147
148        assert_eq!(capped.text.matches("error context").count(), CAP_ERRORS);
149        assert_eq!(capped.text.matches("warning context").count(), CAP_WARNINGS);
150        assert_eq!(capped.dropped_by_class.get(&DropClass::Error), Some(&20));
151        assert_eq!(capped.dropped_by_class.get(&DropClass::Warning), Some(&10));
152        assert!(capped.text.contains("progress 39"));
153        assert!(!capped.text.contains("error 39\n  error context 39"));
154    }
155
156    #[test]
157    fn caps_by_class_without_splitting_blocks() {
158        let blocks = vec![
159            ClassifiedBlock::new(DropClass::Error, "error 1\n  context"),
160            ClassifiedBlock::new(DropClass::Warning, "warning 1\n  context"),
161            ClassifiedBlock::new(DropClass::Error, "error 2\n  context"),
162        ];
163
164        let capped = cap_classified_blocks_with(blocks, |class| match class {
165            DropClass::Error => 1,
166            DropClass::Warning => 10,
167            _ => 0,
168        });
169
170        assert!(capped.text.contains("error 1\n  context"));
171        assert!(capped.text.contains("warning 1\n  context"));
172        assert!(!capped.text.contains("error 2"));
173        assert_eq!(capped.dropped_by_class.get(&DropClass::Error), Some(&1));
174    }
175}