iroh/test_utils/qlog.rs
1//! Utils for emitting qlog files from iroh endpoint.
2
3use std::path::{Path, PathBuf};
4#[cfg(feature = "qlog")]
5use std::sync::Arc;
6
7use n0_error::Result;
8#[cfg(feature = "qlog")]
9use n0_future::time::Instant;
10
11#[cfg(feature = "qlog")]
12use crate::endpoint::QlogFileFactory;
13use crate::endpoint::QuicTransportConfig;
14
15/// Builder to create one or more related qlog configs.
16///
17/// This struct is available independently of feature flags, but if the "qlog" feature is not enabled
18/// it does not do anything.
19#[derive(Debug, Clone)]
20pub struct QlogFileGroup {
21 #[cfg(feature = "qlog")]
22 directory: PathBuf,
23 #[cfg(feature = "qlog")]
24 title: String,
25 #[cfg(feature = "qlog")]
26 start: Instant,
27}
28
29impl QlogFileGroup {
30 /// Creates a new [`QlogFileGroup`] that is only enabled if feature flags and environment variables match.
31 ///
32 /// The qlog files will be written to `CARGO_MANIFEST_DIR/qlog`.
33 ///
34 /// The [`QlogFileGroup`] can be used independent of feature flags, but it will only emit qlog files
35 /// if the "qlog" feature is enabled and the environment variable IROH_TEST_QLOG is set to 1.
36 pub fn from_env(title: impl ToString) -> Self {
37 let directory = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("qlog");
38 Self::new(directory, title)
39 }
40
41 /// Creates a new [`QlogFileGroup`] that writes qlog files to the specified directory.
42 ///
43 /// The [`QlogFileGroup`] can be used independent of feature flags, but it will only emit qlog files
44 /// if the "qlog" feature is enabled and the environment variable IROH_TEST_QLOG is set to 1.
45 pub fn new(directory: impl AsRef<Path>, title: impl ToString) -> Self {
46 #[cfg(not(feature = "qlog"))]
47 let this = {
48 let _ = (directory, title);
49 Self {}
50 };
51
52 #[cfg(feature = "qlog")]
53 let this = Self {
54 title: title.to_string(),
55 directory: directory.as_ref().to_owned(),
56 start: Instant::now(),
57 };
58
59 this
60 }
61
62 /// Creates a [`QuicTransportConfig`] that emits qlog files, if enabled.
63 ///
64 /// If the "qlog" feature is enabled, and the environment variable IROH_TEST_QLOG is set,
65 /// this returns a transport config that writes qlog configs to the configured output directory.
66 /// Otherwise, a default transport config is returned.
67 pub fn create(&self, name: impl ToString) -> Result<QuicTransportConfig> {
68 #[cfg(not(feature = "qlog"))]
69 {
70 let _name = name;
71 Ok(QuicTransportConfig::default())
72 }
73 #[cfg(feature = "qlog")]
74 {
75 let mut builder = QuicTransportConfig::builder();
76
77 if std::env::var("IROH_TEST_QLOG").is_ok() {
78 let prefix = format!("{}.{}", self.title, name.to_string());
79 let factory = QlogFileFactory::new(self.directory.clone())
80 .with_prefix(prefix)
81 .with_start_instant(self.start.into());
82 builder = builder.qlog_factory(Arc::new(factory));
83 }
84 Ok(builder.build())
85 }
86 }
87}