Debian Codegraph @

third_party/rust/neqo-common/src/qlog.rs

raw
1 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
2 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
3 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
4 // option. This file may not be copied, modified, or distributed
5 // except according to those terms.
6
7 #![allow(
8 clippy::module_name_repetitions,
9 reason = "<https://github.com/mozilla/neqo/issues/2284#issuecomment-2782711813>"
10 )]
11
12 use std::{
13 cell::RefCell,
14 fmt::{self, Display},
15 fs::OpenOptions,
16 io::BufWriter,
17 path::PathBuf,
18 rc::Rc,
19 time::{Instant, SystemTime},
20 };
21
22 use qlog::{
23 streamer::QlogStreamer, CommonFields, Configuration, TraceSeq, VantagePoint, VantagePointType,
24 };
25
26 use crate::Role;
27
28 #[derive(Debug, Clone, Default)]
29 pub struct NeqoQlog {
30 inner: Rc<RefCell<Option<NeqoQlogShared>>>,
31 }
32
33 pub struct NeqoQlogShared {
34 qlog_path: PathBuf,
35 streamer: QlogStreamer,
36 }
37
38 impl NeqoQlog {
39 /// Create an enabled `NeqoQlog` configuration backed by a file.
40 ///
41 /// # Errors
42 ///
43 /// Will return `qlog::Error` if it cannot write to the new file.
44 pub fn enabled_with_file(
45 mut qlog_path: PathBuf,
46 role: Role,
47 title: Option<String>,
48 description: Option<String>,
49 file_prefix: impl Display,
50 ) -> Result<Self, qlog::Error> {
51 qlog_path.push(format!("{file_prefix}.sqlog"));
52
53 let file = OpenOptions::new()
54 .write(true)
55 // As a server, the original DCID is chosen by the client. Using
56 // create_new() prevents attackers from overwriting existing logs.
57 .create_new(true)
58 .open(&qlog_path)
59 .map_err(qlog::Error::IoError)?;
60
61 let streamer = QlogStreamer::new(
62 qlog::QLOG_VERSION.to_string(),
63 title,
64 description,
65 None,
66 Instant::now(),
67 new_trace(role),
68 qlog::events::EventImportance::Base,
69 Box::new(BufWriter::new(file)),
70 );
71 Self::enabled(streamer, qlog_path)
72 }
73
74 /// Create an enabled `NeqoQlog` configuration.
75 ///
76 /// # Errors
77 ///
78 /// Will return `qlog::Error` if it cannot write to the new log.
79 pub fn enabled(mut streamer: QlogStreamer, qlog_path: PathBuf) -> Result<Self, qlog::Error> {
80 streamer.start_log()?;
81
82 Ok(Self {
83 inner: Rc::new(RefCell::new(Some(NeqoQlogShared {
84 qlog_path,
85 streamer,
86 }))),
87 })
88 }
89
90 #[must_use]
91 pub fn inner(&self) -> Rc<RefCell<Option<NeqoQlogShared>>> {
92 Rc::clone(&self.inner)
93 }
94
95 /// Create a disabled `NeqoQlog` configuration.
96 #[must_use]
97 pub fn disabled() -> Self {
98 Self::default()
99 }
100
101 /// If logging enabled, closure may generate an event to be logged.
102 pub fn add_event_with_instant<F>(&self, f: F, now: Instant)
103 where
104 F: FnOnce() -> Option<qlog::events::Event>,
105 {
106 self.add_event_with_stream(|s| {
107 if let Some(evt) = f() {
108 s.add_event_with_instant(evt, now)?;
109 }
110 Ok(())
111 });
112 }
113
114 /// If logging enabled, closure may generate an event to be logged.
115 pub fn add_event_data_with_instant<F>(&self, f: F, now: Instant)
116 where
117 F: FnOnce() -> Option<qlog::events::EventData>,
118 {
119 self.add_event_with_stream(|s| {
120 if let Some(ev_data) = f() {
121 s.add_event_data_with_instant(ev_data, now)?;
122 }
123 Ok(())
124 });
125 }
126
127 /// If logging enabled, closure may generate an event to be logged.
128 ///
129 /// This function is similar to [`NeqoQlog::add_event_data_with_instant`],
130 /// but it does not take `now: Instant` as an input parameter. Instead, it
131 /// internally calls [`std::time::Instant::now`]. Prefer calling
132 /// [`NeqoQlog::add_event_data_with_instant`] when `now` is available, as it
133 /// ensures consistency with the current time, which might differ from
134 /// [`std::time::Instant::now`] (e.g., when using simulated time instead of
135 /// real time).
136 pub fn add_event_data_now<F>(&self, f: F)
137 where
138 F: FnOnce() -> Option<qlog::events::EventData>,
139 {
140 self.add_event_with_stream(|s| {
141 if let Some(ev_data) = f() {
142 s.add_event_data_now(ev_data)?;
143 }
144 Ok(())
145 });
146 }
147
148 /// If logging enabled, closure is given the Qlog stream to write events and
149 /// frames to.
150 pub fn add_event_with_stream<F>(&self, f: F)
151 where
152 F: FnOnce(&mut QlogStreamer) -> Result<(), qlog::Error>,
153 {
154 if let Some(inner) = self.inner.borrow_mut().as_mut() {
155 if let Err(e) = f(&mut inner.streamer) {
156 log::error!("Qlog event generation failed with error {e}; closing qlog.");
157 *self.inner.borrow_mut() = None;
158 }
159 }
160 }
161 }
162
163 impl fmt::Debug for NeqoQlogShared {
164 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
165 write!(f, "NeqoQlog writing to {}", self.qlog_path.display())
166 }
167 }
168
169 impl Drop for NeqoQlogShared {
170 fn drop(&mut self) {
171 if let Err(e) = self.streamer.finish_log() {
172 log::error!("Error dropping NeqoQlog: {e}");
173 }
174 }
175 }
176
177 #[must_use]
178 pub fn new_trace(role: Role) -> TraceSeq {
179 TraceSeq {
180 vantage_point: VantagePoint {
181 name: Some(format!("neqo-{role}")),
182 ty: match role {
183 Role::Client => VantagePointType::Client,
184 Role::Server => VantagePointType::Server,
185 },
186 flow: None,
187 },
188 title: Some(format!("neqo-{role} trace")),
189 description: Some(format!("neqo-{role} trace")),
190 configuration: Some(Configuration {
191 time_offset: Some(0.0),
192 original_uris: None,
193 }),
194 common_fields: Some(CommonFields {
195 group_id: None,
196 protocol_type: None,
197 reference_time: SystemTime::now()
198 .duration_since(SystemTime::UNIX_EPOCH)
199 .map(|d| d.as_secs_f64() * 1_000.0)
200 .ok(),
201 time_format: Some("relative".to_string()),
202 }),
203 }
204 }
205
206 #[cfg(test)]
207 mod test {
208 use std::time::Instant;
209
210 use qlog::events::Event;
211 use regex::Regex;
212 use test_fixture::EXPECTED_LOG_HEADER;
213
214 const EV_DATA: qlog::events::EventData =
215 qlog::events::EventData::SpinBitUpdated(qlog::events::connectivity::SpinBitUpdated {
216 state: true,
217 });
218
219 const EXPECTED_LOG_EVENT: &str = concat!(
220 "\u{1e}",
221 r#"{"time":0.0,"name":"connectivity:spin_bit_updated","data":{"state":true}}"#,
222 "\n"
223 );
224
225 #[test]
226 fn new_neqo_qlog() {
227 let (_log, contents) = test_fixture::new_neqo_qlog();
228 assert_eq!(contents.to_string(), EXPECTED_LOG_HEADER);
229 }
230
231 #[test]
232 fn add_event_with_instant() {
233 let (log, contents) = test_fixture::new_neqo_qlog();
234 log.add_event_with_instant(|| Some(Event::with_time(0.0, EV_DATA)), Instant::now());
235 assert_eq!(
236 Regex::new("\"time\":[0-9]+.[0-9]+,")
237 .unwrap()
238 .replace(&contents.to_string(), "\"time\":0.0,"),
239 format!("{EXPECTED_LOG_HEADER}{EXPECTED_LOG_EVENT}"),
240 );
241 }
242 }