1use std::path::{Path, PathBuf};
4
5use crate::error::TraceError;
6
7#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
10pub enum TraceMode {
11 Off,
13 #[default]
15 OnFailure,
16 Always,
18}
19
20impl TraceMode {
21 #[must_use]
23 pub fn writes(self, passed: bool) -> bool {
24 match self {
25 TraceMode::Off => false,
26 TraceMode::OnFailure => !passed,
27 TraceMode::Always => true,
28 }
29 }
30}
31
32#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
34pub enum FramePolicy {
35 None,
37 #[default]
39 EveryStep,
40 ActionsOnly,
42}
43
44#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
46pub struct ByteSize(u64);
47
48impl ByteSize {
49 #[must_use]
51 pub const fn bytes(bytes: u64) -> Self {
52 Self(bytes)
53 }
54
55 #[must_use]
57 pub const fn kib(kib: u64) -> Self {
58 Self(kib.saturating_mul(1024))
59 }
60
61 #[must_use]
63 pub const fn mib(mib: u64) -> Self {
64 Self(mib.saturating_mul(1024 * 1024))
65 }
66
67 #[must_use]
69 pub const fn get(self) -> u64 {
70 self.0
71 }
72}
73
74#[must_use]
77#[derive(Debug, Clone, PartialEq, Eq)]
78pub struct TraceConfig {
79 mode: TraceMode,
80 out_dir: PathBuf,
81 max_size: ByteSize,
82 frames: FramePolicy,
83}
84
85impl Default for TraceConfig {
86 fn default() -> Self {
87 Self {
88 mode: TraceMode::default(),
89 out_dir: PathBuf::from("target/icedwright"),
90 max_size: ByteSize::mib(64),
91 frames: FramePolicy::default(),
92 }
93 }
94}
95
96const TRACE_VAR: &str = "ICEDWRIGHT_TRACE";
97const OUT_DIR_VAR: &str = "ICEDWRIGHT_OUT_DIR";
98const MAX_MB_VAR: &str = "ICEDWRIGHT_TRACE_MAX_MB";
99
100impl TraceConfig {
101 pub fn new() -> Self {
104 Self::default()
105 }
106
107 pub fn mode(self, mode: TraceMode) -> Self {
109 Self { mode, ..self }
110 }
111
112 pub fn out_dir(self, dir: impl Into<PathBuf>) -> Self {
114 Self {
115 out_dir: dir.into(),
116 ..self
117 }
118 }
119
120 pub fn max_size(self, bytes: ByteSize) -> Self {
122 Self {
123 max_size: bytes,
124 ..self
125 }
126 }
127
128 pub fn frames(self, policy: FramePolicy) -> Self {
130 Self {
131 frames: policy,
132 ..self
133 }
134 }
135
136 pub fn from_env(self, env: &impl Fn(&str) -> Option<String>) -> Result<Self, TraceError> {
139 let mut config = self;
140 if let Some(value) = env(TRACE_VAR) {
141 config.mode = match value.as_str() {
142 "off" => TraceMode::Off,
143 "on-failure" => TraceMode::OnFailure,
144 "always" => TraceMode::Always,
145 _ => {
146 return Err(TraceError::BadEnv {
147 var: TRACE_VAR,
148 value,
149 expected: "off, on-failure or always",
150 });
151 }
152 };
153 }
154 if let Some(value) = env(OUT_DIR_VAR) {
155 if value.is_empty() {
156 return Err(TraceError::BadEnv {
157 var: OUT_DIR_VAR,
158 value,
159 expected: "a directory path",
160 });
161 }
162 config.out_dir = PathBuf::from(value);
163 }
164 if let Some(value) = env(MAX_MB_VAR) {
165 let mib = value.trim().parse::<u64>().ok().filter(|mib| *mib > 0);
166 let Some(mib) = mib else {
167 return Err(TraceError::BadEnv {
168 var: MAX_MB_VAR,
169 value,
170 expected: "a whole number of MiB above zero",
171 });
172 };
173 config.max_size = ByteSize::mib(mib);
174 }
175 Ok(config)
176 }
177
178 #[must_use]
180 pub fn trace_mode(&self) -> TraceMode {
181 self.mode
182 }
183
184 #[must_use]
186 pub fn output_dir(&self) -> &Path {
187 &self.out_dir
188 }
189
190 #[must_use]
192 pub fn size_cap(&self) -> ByteSize {
193 self.max_size
194 }
195
196 #[must_use]
198 pub fn frame_policy(&self) -> FramePolicy {
199 self.frames
200 }
201
202 #[must_use]
205 pub fn trace_path(&self, module_path: &str, test: &str) -> PathBuf {
206 let mut path = self.out_dir.join("traces");
207 module_path
208 .split("::")
209 .filter(|part| !part.is_empty())
210 .for_each(|part| path.push(part));
211 path.push(format!("{test}.iwtrace"));
212 path
213 }
214}
215
216#[cfg(test)]
217mod tests {
218 use super::*;
219
220 fn env<'a>(vars: &'a [(&'a str, &'a str)]) -> impl Fn(&str) -> Option<String> + 'a {
221 move |name| {
222 vars.iter()
223 .find(|(var, _)| *var == name)
224 .map(|(_, value)| (*value).to_owned())
225 }
226 }
227
228 #[test]
229 fn defaults() {
230 let config = TraceConfig::new();
231 assert_eq!(config.trace_mode(), TraceMode::OnFailure);
232 assert_eq!(config.output_dir(), Path::new("target/icedwright"));
233 assert_eq!(config.size_cap(), ByteSize::mib(64));
234 assert_eq!(config.frame_policy(), FramePolicy::EveryStep);
235 }
236
237 #[test]
238 fn builder_sets_each_field() {
239 let config = TraceConfig::new()
240 .mode(TraceMode::Always)
241 .out_dir("/tmp/out")
242 .max_size(ByteSize::kib(3))
243 .frames(FramePolicy::ActionsOnly);
244 assert_eq!(config.trace_mode(), TraceMode::Always);
245 assert_eq!(config.output_dir(), Path::new("/tmp/out"));
246 assert_eq!(config.size_cap().get(), 3072);
247 assert_eq!(config.frame_policy(), FramePolicy::ActionsOnly);
248 }
249
250 type Vars<'a> = &'a [(&'a str, &'a str)];
251
252 #[test]
253 fn environment_table() -> Result<(), TraceError> {
254 let cases: &[(Vars<'_>, TraceMode, &str, u64)] = &[
255 (&[], TraceMode::OnFailure, "target/icedwright", 64),
256 (
257 &[("ICEDWRIGHT_TRACE", "off")],
258 TraceMode::Off,
259 "target/icedwright",
260 64,
261 ),
262 (
263 &[("ICEDWRIGHT_TRACE", "always")],
264 TraceMode::Always,
265 "target/icedwright",
266 64,
267 ),
268 (
269 &[
270 ("ICEDWRIGHT_TRACE", "on-failure"),
271 ("ICEDWRIGHT_OUT_DIR", "out"),
272 ],
273 TraceMode::OnFailure,
274 "out",
275 64,
276 ),
277 (
278 &[("ICEDWRIGHT_TRACE_MAX_MB", "8")],
279 TraceMode::OnFailure,
280 "target/icedwright",
281 8,
282 ),
283 ];
284 for (vars, mode, dir, mib) in cases {
285 let config = TraceConfig::new().from_env(&env(vars))?;
286 assert_eq!(config.trace_mode(), *mode, "{vars:?}");
287 assert_eq!(config.output_dir(), Path::new(dir), "{vars:?}");
288 assert_eq!(config.size_cap(), ByteSize::mib(*mib), "{vars:?}");
289 }
290 Ok(())
291 }
292
293 #[test]
294 fn invalid_environment_values_name_the_variable() {
295 let cases: &[(&str, &str, &str)] = &[
296 (
297 "ICEDWRIGHT_TRACE",
298 "yes",
299 "ICEDWRIGHT_TRACE=\"yes\" is not valid: off, on-failure or always",
300 ),
301 (
302 "ICEDWRIGHT_OUT_DIR",
303 "",
304 "ICEDWRIGHT_OUT_DIR=\"\" is not valid: a directory path",
305 ),
306 (
307 "ICEDWRIGHT_TRACE_MAX_MB",
308 "0",
309 "ICEDWRIGHT_TRACE_MAX_MB=\"0\" is not valid: a whole number of MiB above zero",
310 ),
311 (
312 "ICEDWRIGHT_TRACE_MAX_MB",
313 "1.5",
314 "ICEDWRIGHT_TRACE_MAX_MB=\"1.5\" is not valid: a whole number of MiB above zero",
315 ),
316 ];
317 for (var, value, message) in cases {
318 let vars = [(*var, *value)];
319 let error = TraceConfig::new().from_env(&env(&vars)).err();
320 assert_eq!(error.map(|e| e.to_string()).as_deref(), Some(*message));
321 }
322 }
323
324 #[test]
325 fn modes_decide_what_is_written() {
326 assert!(!TraceMode::Off.writes(false));
327 assert!(!TraceMode::OnFailure.writes(true));
328 assert!(TraceMode::OnFailure.writes(false));
329 assert!(TraceMode::Always.writes(true));
330 }
331
332 #[test]
333 fn trace_paths_follow_the_module_path() {
334 let path = TraceConfig::new().trace_path("examples_notes::ui", "restoring_a_note");
335 assert_eq!(
336 path,
337 Path::new("target/icedwright/traces/examples_notes/ui/restoring_a_note.iwtrace")
338 );
339 }
340}