1use std::fmt;
2use std::time::SystemTime;
3
4use chrono::{DateTime, SecondsFormat, Utc};
5use tracing::Level;
6
7pub(crate) fn render_line(
12 at: SystemTime,
13 level: &Level,
14 logger: &str,
15 bound: &[(String, String)],
16 message: &str,
17 fields: &[(String, String)],
18) -> String {
19 let timestamp = DateTime::<Utc>::from(at).to_rfc3339_opts(SecondsFormat::Millis, true);
20 let mut line = format!("{timestamp} {:<5} {logger}:", level.as_str());
21
22 if !bound.is_empty() {
23 line.push_str(" [");
24 for (index, (key, value)) in bound.iter().enumerate() {
25 if index > 0 {
26 line.push(' ');
27 }
28 line.push_str(key);
29 line.push('=');
30 line.push_str(&format_value(value));
31 }
32 line.push(']');
33 }
34 if !message.is_empty() {
35 line.push(' ');
36 line.push_str(&escape_message(message));
37 }
38 for (key, value) in fields {
39 line.push(' ');
40 line.push_str(key);
41 line.push('=');
42 line.push_str(&format_value(value));
43 }
44
45 line
46}
47
48#[derive(Clone, Copy)]
49pub(crate) enum LoggerPath<'a> {
50 Bare,
51 Component(&'a str),
52 Dependency(&'a str),
53}
54
55impl<'a> LoggerPath<'a> {
56 pub(crate) fn from_target(module_id: &str, target: &'a str) -> Self {
57 if target.is_empty() || target == module_id || target.contains("::") {
58 return Self::Bare;
59 }
60 if target.split('.').all(is_segment) {
61 Self::Component(target)
62 } else {
63 Self::Bare
64 }
65 }
66
67 pub(crate) fn dependency(crate_name: &'a str) -> Self {
68 Self::Dependency(crate_name)
69 }
70
71 pub(crate) fn dependency_name(self) -> Option<&'a str> {
72 match self {
73 Self::Dependency(crate_name) => Some(crate_name),
74 Self::Bare | Self::Component(_) => None,
75 }
76 }
77
78 pub(crate) fn logger_name(self, module_id: &str) -> String {
79 match self {
80 Self::Bare => module_id.to_owned(),
81 Self::Component(target) => format!("{module_id}.{target}"),
82 Self::Dependency(crate_name) if valid_crate_segment(crate_name) => {
83 let mut logger = String::with_capacity(module_id.len() + crate_name.len() + 5);
84 logger.push_str(module_id);
85 logger.push_str(".dep.");
86 for character in crate_name.chars() {
87 logger.push(if character == '_' { '-' } else { character });
88 }
89 logger
90 }
91 Self::Dependency(_) => module_id.to_owned(),
92 }
93 }
94
95 pub(crate) fn matches_prefix(self, module_id: &str, prefix: &str) -> bool {
96 let mut directive = prefix.split('.');
97 for segment in module_id.split('.') {
98 if let Some(matches) = match_segment(&mut directive, segment) {
99 return matches;
100 }
101 }
102
103 match self {
104 Self::Bare => directive.next().is_none(),
105 Self::Component(target) => {
106 for segment in target.split('.') {
107 if let Some(matches) = match_segment(&mut directive, segment) {
108 return matches;
109 }
110 }
111 directive.next().is_none()
112 }
113 Self::Dependency(crate_name) if valid_crate_segment(crate_name) => {
114 if let Some(matches) = match_segment(&mut directive, "dep") {
115 return matches;
116 }
117 let Some(crate_segment) = directive.next() else {
118 return true;
119 };
120 crate_segment_matches(crate_segment, crate_name) && directive.next().is_none()
121 }
122 Self::Dependency(_) => directive.next().is_none(),
123 }
124 }
125}
126
127fn match_segment<'a>(directive: &mut std::str::Split<'a, char>, segment: &str) -> Option<bool> {
128 match directive.next() {
129 None => Some(true),
130 Some(expected) if expected == segment => None,
131 Some(_) => Some(false),
132 }
133}
134
135fn crate_segment_matches(expected: &str, crate_name: &str) -> bool {
136 let mut actual = crate_name.chars();
137 expected.chars().all(|expected| {
138 actual.next().is_some_and(|actual| {
139 if actual == '_' {
140 expected == '-'
141 } else {
142 actual == expected
143 }
144 })
145 }) && actual.next().is_none()
146}
147
148fn valid_crate_segment(crate_name: &str) -> bool {
149 let mut characters = crate_name.chars();
150 matches!(characters.next(), Some('a'..='z'))
151 && characters.all(|character| matches!(character, 'a'..='z' | '0'..='9' | '_'))
152}
153
154pub(crate) fn is_segment(segment: &str) -> bool {
155 let mut chars = segment.chars();
156 matches!(chars.next(), Some('a'..='z'))
157 && chars.all(|character| matches!(character, 'a'..='z' | '0'..='9' | '-'))
158}
159
160fn is_escaped_control(character: char) -> bool {
171 matches!(character as u32, 0x00..=0x1f | 0x7f..=0x9f) && !matches!(character, '\n' | '\r')
172}
173
174fn push_control_escape(output: &mut String, character: char) {
175 output.push_str(&format!("\\u{:04x}", character as u32));
176}
177
178fn strip_complete_sequences(field: &str) -> std::borrow::Cow<'_, str> {
182 if !field
183 .chars()
184 .any(|character| matches!(character, '\u{1b}' | '\u{9b}' | '\u{9d}'))
185 {
186 return std::borrow::Cow::Borrowed(field);
187 }
188 let characters: Vec<char> = field.chars().collect();
189 let mut output = String::with_capacity(field.len());
190 let mut index = 0;
191 while index < characters.len() {
192 let character = characters[index];
193 let next = characters.get(index + 1).copied();
194 let csi_body = match (character, next) {
195 ('\u{1b}', Some('[')) => Some(index + 2),
196 ('\u{9b}', _) => Some(index + 1),
197 _ => None,
198 };
199 let osc_body = match (character, next) {
200 ('\u{1b}', Some(']')) => Some(index + 2),
201 ('\u{9d}', _) => Some(index + 1),
202 _ => None,
203 };
204 let end = if let Some(body) = csi_body {
205 csi_end(&characters, body)
206 } else if let Some(body) = osc_body {
207 osc_end(&characters, body)
208 } else {
209 None
210 };
211 match end {
212 Some(end) => index = end,
213 None => {
214 output.push(character);
215 index += 1;
216 }
217 }
218 }
219 std::borrow::Cow::Owned(output)
220}
221
222fn csi_end(characters: &[char], body: usize) -> Option<usize> {
226 for (offset, character) in characters[body..].iter().enumerate() {
227 match *character as u32 {
228 0x40..=0x7e => return Some(body + offset + 1),
229 0x20..=0x3f => {}
230 _ => return None,
231 }
232 }
233 None
234}
235
236fn osc_end(characters: &[char], body: usize) -> Option<usize> {
238 let mut index = body;
239 while index < characters.len() {
240 match characters[index] {
241 '\u{7}' | '\u{9c}' => return Some(index + 1),
242 '\u{1b}' if characters.get(index + 1) == Some(&'\\') => return Some(index + 2),
243 _ => index += 1,
244 }
245 }
246 None
247}
248
249fn escape_message(message: &str) -> String {
252 let cleaned = strip_complete_sequences(message);
253 let mut output = String::with_capacity(cleaned.len());
254 for character in cleaned.chars() {
255 match character {
256 '\\' => output.push_str("\\\\"),
257 '\r' => output.push_str("\\r"),
258 '\n' => output.push_str("\\n"),
259 control if is_escaped_control(control) => push_control_escape(&mut output, control),
260 other => output.push(other),
261 }
262 }
263 output
264}
265
266fn format_value(value: &str) -> String {
267 let cleaned = strip_complete_sequences(value);
269 let needs_quotes = cleaned.is_empty()
270 || cleaned.chars().any(|character| {
271 matches!(character, ' ' | '"' | '\n' | '\r' | ']') || is_escaped_control(character)
272 });
273 if !needs_quotes {
274 return cleaned.into_owned();
277 }
278 let mut output = String::with_capacity(cleaned.len() + 2);
279 output.push('"');
280 for character in cleaned.chars() {
281 match character {
282 '\\' => output.push_str("\\\\"),
283 '"' => output.push_str("\\\""),
284 '\r' => output.push_str("\\r"),
285 '\n' => output.push_str("\\n"),
286 control if is_escaped_control(control) => push_control_escape(&mut output, control),
287 other => output.push(other),
288 }
289 }
290 output.push('"');
291 output
292}
293
294pub(crate) fn escape_raw_controls(line: &str) -> std::borrow::Cow<'_, str> {
298 if !line
299 .chars()
300 .any(|character| matches!(character, '\n' | '\r') || is_escaped_control(character))
301 {
302 return std::borrow::Cow::Borrowed(line);
303 }
304 let mut output = String::with_capacity(line.len());
305 for character in line.chars() {
306 match character {
307 '\r' => output.push_str("\\r"),
308 '\n' => output.push_str("\\n"),
309 control if is_escaped_control(control) => push_control_escape(&mut output, control),
310 other => output.push(other),
311 }
312 }
313 std::borrow::Cow::Owned(output)
314}
315
316#[derive(Clone, Copy, Debug, Eq, PartialEq)]
318pub enum ParsedLevel {
319 Trace,
321 Debug,
323 Info,
325 Warn,
327 Error,
329}
330
331#[derive(Clone, Debug, Eq, PartialEq)]
333pub struct ParsedLine<'a> {
334 pub timestamp: SystemTime,
336 pub level: ParsedLevel,
338 pub logger: &'a str,
340 pub module_id: &'a str,
342 pub bound: Option<&'a str>,
344 pub body: &'a str,
346}
347
348impl ParsedLine<'_> {
349 pub fn session(&self) -> Option<&str> {
351 self.bound.and_then(|bound| bound_value(bound, "session"))
352 }
353}
354
355fn bound_value<'a>(bound: &'a str, key: &str) -> Option<&'a str> {
356 bound
357 .split(' ')
358 .filter_map(|pair| pair.split_once('='))
359 .find(|(candidate, _)| *candidate == key)
360 .map(|(_, value)| value)
361}
362
363#[derive(Clone, Copy, Debug, Eq, PartialEq)]
365pub struct ParseError {
366 reason: &'static str,
367}
368
369impl ParseError {
370 pub(crate) const fn new(reason: &'static str) -> Self {
371 Self { reason }
372 }
373
374 pub const fn reason(self) -> &'static str {
376 self.reason
377 }
378}
379
380impl fmt::Display for ParseError {
381 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
382 formatter.write_str(self.reason)
383 }
384}
385
386impl std::error::Error for ParseError {}
387
388pub(crate) fn parse(line: &str) -> Result<ParsedLine<'_>, ParseError> {
389 if line.contains('\u{1b}') || line.contains('\u{9b}') {
390 return Err(ParseError::new("ansi_forbidden"));
391 }
392 if line.contains(['\n', '\r']) {
393 return Err(ParseError::new("line_break"));
394 }
395
396 let (timestamp_text, after_timestamp) = line
397 .split_once(' ')
398 .ok_or_else(|| ParseError::new("timestamp_missing"))?;
399 if !timestamp_text.ends_with('Z') {
400 return Err(ParseError::new("timestamp_not_utc_z"));
401 }
402 if timestamp_text.len() != 24 {
403 return Err(ParseError::new("timestamp_precision"));
404 }
405 let timestamp = DateTime::parse_from_rfc3339(timestamp_text)
406 .map_err(|_| ParseError::new("timestamp_invalid"))?;
407
408 let (level, after_level) = parse_level(after_timestamp)?;
409
410 let (logger_token, mut body) = match after_level.split_once(' ') {
414 Some(split) => split,
415 None => (after_level, ""),
416 };
417 let logger = logger_token
418 .strip_suffix(':')
419 .ok_or_else(|| ParseError::new("logger_not_terminated"))?;
420 if logger.is_empty() {
421 return Err(ParseError::new("logger_missing"));
422 }
423 if !logger.split('.').all(is_segment) {
424 return Err(ParseError::new("logger_segment_grammar"));
425 }
426 let module_id = logger.split('.').next().unwrap_or(logger);
427
428 let mut bound = None;
429 if let Some(rest) = body.strip_prefix('[') {
430 let close =
431 find_bracket_close(rest).ok_or_else(|| ParseError::new("bound_unterminated"))?;
432 let inside = &rest[..close];
433 if inside.is_empty() {
434 return Err(ParseError::new("empty_bound_bracket"));
435 }
436 if let Some(session) = bound_value(inside, "session") {
437 let valid = session
438 .rsplit_once(':')
439 .is_some_and(|(issuer, id)| !issuer.is_empty() && !id.is_empty());
440 if !valid {
444 return Err(ParseError::new("session_missing_issuer"));
445 }
446 }
447 bound = Some(inside);
448 body = rest[close + 1..]
449 .strip_prefix(' ')
450 .unwrap_or(&rest[close + 1..]);
451 }
452
453 if bound.is_none() && body.contains(" [") && body.ends_with(']') {
458 return Err(ParseError::new("bound_after_message"));
459 }
460
461 Ok(ParsedLine {
462 timestamp: SystemTime::from(timestamp),
463 level,
464 logger,
465 module_id,
466 bound,
467 body,
468 })
469}
470
471fn find_bracket_close(input: &str) -> Option<usize> {
475 let mut in_quotes = false;
476 let mut escaped = false;
477 for (index, character) in input.char_indices() {
478 if escaped {
479 escaped = false;
480 continue;
481 }
482 match character {
483 '\\' if in_quotes => escaped = true,
484 '"' => in_quotes = !in_quotes,
485 ']' if !in_quotes => return Some(index),
486 _ => {}
487 }
488 }
489 None
490}
491
492fn parse_level(input: &str) -> Result<(ParsedLevel, &str), ParseError> {
493 for (prefix, level) in [
494 ("TRACE ", ParsedLevel::Trace),
495 ("DEBUG ", ParsedLevel::Debug),
496 ("INFO ", ParsedLevel::Info),
497 ("WARN ", ParsedLevel::Warn),
498 ("ERROR ", ParsedLevel::Error),
499 ] {
500 if let Some(rest) = input.strip_prefix(prefix) {
501 return Ok((level, rest));
502 }
503 }
504
505 if ["TRACE", "DEBUG", "INFO", "WARN", "ERROR"]
506 .iter()
507 .any(|level| input.starts_with(level))
508 {
509 Err(ParseError::new("level_column_width"))
510 } else {
511 Err(ParseError::new("level_invalid"))
512 }
513}