Debian Codegraph @

rust/hg-core/src/utils/debug.rs

raw
1 //! Utils for debugging hg-core
2
3 use crate::config::Config;
4
5 /// Write the file path given by the config option `devel.<config_option>` with
6 /// the suffix `.waiting`, then wait for the file path given by the
7 /// config option `devel.<config_option>` to appear on disk
8 /// up to `devel.<config_option>-timeout` seconds.
9 /// Note that the timeout may be higher because we scale it if global
10 /// `run-tests` timeouts are raised to prevent flakiness on slower hardware.
11 ///
12 /// Useful for testing race conditions.
13 pub fn debug_wait_for_file(
14 config: &Config,
15 config_option: &str,
16 ) -> Result<(), String> {
17 let path_opt = format!("sync.{config_option}");
18 let file_path = match config.get_str(b"devel", path_opt.as_bytes()).ok() {
19 Some(Some(file_path)) => file_path,
20 _ => return Ok(()),
21 };
22
23 // TODO make it so `configitems` is shared between Rust and Python so that
24 // defaults work out of the box, etc.
25 let default_timeout = 2;
26 let timeout_opt = format!("sync.{config_option}-timeout");
27 let timeout_seconds = match config.get_u32(b"devel", timeout_opt.as_bytes())
28 {
29 Ok(Some(timeout)) => timeout,
30 _ => default_timeout,
31 };
32 let timeout_seconds = timeout_seconds as u64;
33
34 tracing::debug!(
35 "Config option `{config_option}` found, \
36 waiting for file `{file_path}` to be created"
37 );
38 std::fs::File::create(format!("{file_path}.waiting")).ok();
39 // If the test timeout have been extended, scale the timer relative
40 // to the normal timing.
41 let global_timeout_perc: u64 = std::env::var("HGTEST_TIMEOUT_PERCENTAGE")
42 .map(|t| t.parse())
43 .unwrap_or(Ok(100))
44 .unwrap();
45 let timeout_seconds = (timeout_seconds * global_timeout_perc) / 100;
46 let timeout = std::time::Duration::from_secs(timeout_seconds);
47
48 let start = std::time::Instant::now();
49 let path = std::path::Path::new(file_path);
50 let mut found = false;
51 while start.elapsed() < timeout {
52 if path.exists() {
53 tracing::debug!("File `{file_path}` was created");
54 found = true;
55 break;
56 } else {
57 std::thread::sleep(std::time::Duration::from_millis(10));
58 }
59 }
60 if !found {
61 let msg = format!(
62 "File `{file_path}` set by `{config_option}` was not found \
63 within the allocated {timeout_seconds} seconds timeout"
64 );
65 Err(msg)
66 } else {
67 Ok(())
68 }
69 }
70
71 pub fn debug_wait_for_file_or_print(config: &Config, config_option: &str) {
72 if let Err(e) = debug_wait_for_file(config, config_option) {
73 eprintln!("{e}");
74 };
75 }