freeswitch_log_parser/stream/entry.rs
1//! Types produced per log entry: the reassembled [`Block`] variants, the
2//! [`LogEntry`] record itself, and parsing anomalies ([`ParseWarning`]).
3
4use std::fmt;
5
6use crate::attached::AttachedLines;
7use crate::codec::{CodecMedia, CodecOffer, CodecParseError};
8use crate::decode::truncate_at_char_boundary;
9use crate::fields::FieldLocation;
10use crate::level::LogLevel;
11use crate::line::LineKind;
12use crate::message::{MessageKind, SdpDirection};
13
14use super::collision::MOD_LOGFILE_BUF_SIZE;
15
16/// Structured data extracted from a multi-line dump that follows a primary log entry.
17///
18/// Each variant corresponds to a block type that the stream state machine
19/// recognizes and reassembles from continuation lines.
20#[derive(Debug, Clone, PartialEq, Eq)]
21#[non_exhaustive]
22pub enum Block {
23 /// Channel variable dump — `Channel-*` fields and `variable_*` key-value pairs.
24 /// Multi-line variable values (e.g. embedded SDP) are reassembled with `\n` separators.
25 ChannelData {
26 fields: Vec<(String, String)>,
27 variables: Vec<(String, String)>,
28 },
29 /// SDP session description body, collected line by line.
30 ///
31 /// The marker may be a continuation of another entry — sofia logs the
32 /// outbound invite line and the marker together — and a body carrying no
33 /// marker at all, such as the SIP message a recorder packet dump prints,
34 /// opens on its version line with [`SdpDirection::Unknown`]. Lines ahead of
35 /// the body stay in [`LogEntry::attached`], spanned by [`LogEntry::fields`]
36 /// but not read as a SIP message: that is `freeswitch-sofia-trace-parser`'s
37 /// job, not this crate's.
38 Sdp {
39 direction: SdpDirection,
40 body: Vec<String>,
41 },
42 /// Codec negotiation sequence for one media type. A run only ever covers a
43 /// single [`CodecMedia`]; audio and video traces never share a block.
44 CodecNegotiation {
45 media: CodecMedia,
46 /// `(remote offer, local implementation)` for each pair compared.
47 comparisons: Vec<(CodecOffer, CodecOffer)>,
48 matched: Vec<CodecOffer>,
49 /// Codecs kept as fallbacks because only their ptime differed.
50 near_matched: Vec<CodecOffer>,
51 },
52}
53
54impl Block {
55 /// Value of a `Channel-*` field in a CHANNEL_DATA dump, or `None` if this
56 /// block is another kind or never carried that field.
57 pub fn field(&self, name: &str) -> Option<&str> {
58 let Block::ChannelData { fields, .. } = self else {
59 return None;
60 };
61 fields
62 .iter()
63 .find(|(n, _)| n == name)
64 .map(|(_, v)| v.as_str())
65 }
66
67 /// Value of a channel variable in a CHANNEL_DATA dump.
68 ///
69 /// Accepts any of `freeswitch-types`' variable-name enums, and spares the
70 /// caller from knowing that a dump spells its keys with the `variable_`
71 /// prefix that [`SessionState::variable`](crate::SessionState::variable)
72 /// strips — the two surfaces answer the same question the same way.
73 pub fn variable<V: freeswitch_types::variables::VariableName>(&self, var: V) -> Option<&str> {
74 let Block::ChannelData { variables, .. } = self else {
75 return None;
76 };
77 let wanted = var.as_str();
78 variables
79 .iter()
80 .find(|(n, _)| n.strip_prefix("variable_").unwrap_or(n) == wanted)
81 .map(|(_, v)| v.as_str())
82 }
83}
84
85#[cfg(feature = "sdp")]
86impl Block {
87 /// Codecs described by an SDP body.
88 ///
89 /// `None` when there is no body to read — another block type, or an SDP
90 /// marker that carried none. Sofia logs several (`Duplicate SDP`,
91 /// `Processing updated SDP`) purely as announcements, and an empty body is
92 /// absence rather than a malformed session.
93 ///
94 /// Parsed on each call rather than stored — see `docs/design-rationale.md`.
95 /// Only a session-level failure is an `Err`: a malformed `a=rtpmap` or a
96 /// broken media section degrades into
97 /// [`SdpCodecs::warnings`](freeswitch_types::sdp::SdpCodecs::warnings).
98 pub fn sdp_codecs(
99 &self,
100 ) -> Option<Result<freeswitch_types::sdp::SdpCodecs, freeswitch_types::sdp::SdpCodecError>>
101 {
102 let Block::Sdp { body, .. } = self else {
103 return None;
104 };
105 let text = body.join("\n");
106 if text.trim().is_empty() {
107 return None;
108 }
109 Some(freeswitch_types::sdp::SdpCodecs::parse(&text))
110 }
111}
112
113/// Longest line excerpt a warning carries. An offending line can be tens of
114/// kilobytes; the excerpt is for a human reading the warning, not for matching on.
115pub(super) const WARNING_EXCERPT_LEN: usize = 80;
116
117/// A per-session reading whose value its vocabulary did not know.
118///
119/// Named rather than free-form so a consumer can tell which reading lapsed
120/// without matching on the value it choked on.
121#[derive(Debug, Clone, Copy, PartialEq, Eq)]
122#[non_exhaustive]
123pub enum SessionReading {
124 ChannelState,
125 CallState,
126 CallDirection,
127 HangupCause,
128}
129
130impl fmt::Display for SessionReading {
131 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
132 let label = match self {
133 SessionReading::ChannelState => "channel state",
134 SessionReading::CallState => "call state",
135 SessionReading::CallDirection => "call direction",
136 SessionReading::HangupCause => "hangup cause",
137 };
138 f.write_str(label)
139 }
140}
141
142/// A parsing anomaly, attached to the entry whose lines produced it.
143///
144/// The set is closed and every kind is named — see `docs/design-rationale.md`.
145#[derive(Debug, Clone, PartialEq, Eq)]
146#[non_exhaustive]
147pub enum ParseWarning {
148 /// A CHANNEL_DATA variable opened its `[` and the block ended before the `]`.
149 /// The value collected so far is still recorded.
150 UnclosedVariable { name: String },
151 /// A CHANNEL_DATA variable's value was cut by the logger's write buffer. The
152 /// value is recorded up to the cut; the line after it opens the next variable.
153 TruncatedVariable { name: String },
154 /// A line inside a CHANNEL_DATA block matched neither the field nor the
155 /// variable shape, so it contributed nothing to the block.
156 UnparseableChannelData { line: String },
157 /// A codec negotiation line matched no known trace shape, or its bracketed
158 /// token would not parse. That codec is missing from the block.
159 UnrecognizedCodecLine {
160 line: String,
161 source: Option<CodecParseError>,
162 },
163 /// A continuation line arrived while a codec negotiation block was open.
164 /// The trace has no continuations, so the line belongs to nothing.
165 UnexpectedCodecContinuation { line: String },
166 /// The formatted line exceeded `mod_logfile`'s write buffer, so the record
167 /// was cut short and lost its trailing newline. `bytes` is the formatted
168 /// length, prefix included.
169 OversizeLine { bytes: usize },
170 /// The entry's attached lines outgrew the offsets addressing them, so this
171 /// line could not be stored. Counted in
172 /// [`ParseStats::lines_dropped`](super::ParseStats::lines_dropped).
173 AttachedOverflow { line: String },
174 /// A per-session reading met a value its vocabulary does not know — either
175 /// FreeSWITCH gained one or the line is corrupt. The state that reading
176 /// feeds keeps its last resolved value.
177 UnreadableValue {
178 reading: SessionReading,
179 value: String,
180 },
181}
182
183impl ParseWarning {
184 /// Trim a line down to what a warning is willing to carry.
185 pub(crate) fn excerpt(msg: &str) -> String {
186 truncate_at_char_boundary(msg, WARNING_EXCERPT_LEN).to_string()
187 }
188}
189
190impl fmt::Display for ParseWarning {
191 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
192 match self {
193 ParseWarning::UnclosedVariable { name } => {
194 write!(f, "unclosed multi-line variable: {name}")
195 }
196 ParseWarning::TruncatedVariable { name } => {
197 write!(f, "multi-line variable cut by the log buffer: {name}")
198 }
199 ParseWarning::UnparseableChannelData { line } => {
200 write!(f, "unparseable CHANNEL_DATA line: {line}")
201 }
202 ParseWarning::UnrecognizedCodecLine {
203 line,
204 source: Some(e),
205 } => write!(f, "unrecognized codec negotiation line ({e}): {line}"),
206 ParseWarning::UnrecognizedCodecLine { line, source: None } => {
207 write!(f, "unrecognized codec negotiation line: {line}")
208 }
209 ParseWarning::UnexpectedCodecContinuation { line } => {
210 write!(f, "unexpected codec negotiation continuation: {line}")
211 }
212 ParseWarning::OversizeLine { bytes } => write!(
213 f,
214 "line exceeds mod_logfile {MOD_LOGFILE_BUF_SIZE}-byte buffer \
215 ({bytes} bytes), data may be truncated"
216 ),
217 ParseWarning::UnreadableValue { reading, value } => {
218 write!(f, "unreadable {reading}: {value}")
219 }
220 ParseWarning::AttachedOverflow { line } => {
221 write!(f, "entry's attached lines full, dropped: {line}")
222 }
223 }
224 }
225}
226
227/// A complete parsed log entry with all context resolved.
228///
229/// Produced by [`LogStream`](super::LogStream). Continuation lines have been
230/// grouped, UUID/timestamp inherited from context where needed, and
231/// multi-line blocks reassembled.
232#[derive(Debug)]
233pub struct LogEntry {
234 /// Session UUID; `None` for system lines (no channel context).
235 pub uuid: Option<String>,
236 /// Timestamp with microsecond precision; inherited from the previous entry for continuations.
237 pub timestamp: String,
238 /// `None` for continuation and truncated lines.
239 pub level: Option<LogLevel>,
240 /// Core scheduler idle percentage; `None` for continuations.
241 pub idle_pct: Option<String>,
242 /// Source file:line; `None` for continuations.
243 pub source: Option<String>,
244 /// The primary message text.
245 pub message: String,
246 /// Which line format originated this entry.
247 pub kind: LineKind,
248 /// Semantic classification of the message content.
249 pub message_kind: MessageKind,
250 /// Typed, parsed multi-line block; `None` for entries without a trailing block.
251 pub block: Option<Block>,
252 /// Raw continuation lines that followed the primary line.
253 pub attached: AttachedLines,
254 /// 1-based line number in the input stream.
255 pub line_number: u64,
256 /// Per-entry warnings about parsing anomalies.
257 pub warnings: Vec<ParseWarning>,
258 /// The entry's own texts that ended at a split rather than at their own
259 /// newline, because the logger's write buffer cut the record short.
260 /// [`is_truncated`](LogEntry::is_truncated) is how a span asks about them.
261 pub cut_texts: Vec<FieldLocation>,
262}
263
264impl LogEntry {
265 /// An entry for output the parser never produced — a separator line
266 /// between files or dates, or a hand-built test fixture. Carries no
267 /// uuid, timestamp, level, source or block; override individual fields
268 /// with struct-update syntax for callers that need one set.
269 pub fn synthetic(message: impl Into<String>) -> LogEntry {
270 LogEntry {
271 uuid: None,
272 timestamp: String::new(),
273 level: None,
274 idle_pct: None,
275 source: None,
276 message: message.into(),
277 kind: LineKind::Full,
278 message_kind: MessageKind::General,
279 block: None,
280 attached: AttachedLines::new(),
281 line_number: 0,
282 warnings: Vec::new(),
283 cut_texts: Vec::new(),
284 }
285 }
286}