Skip to main content

llama_cpp_log_decoder/
log_decoder.rs

1use crate::decode_anomaly::DecodeAnomaly;
2use crate::decode_output::DecodeOutput;
3use crate::decode_result::DecodeResult;
4use crate::incoming_log_level::IncomingLogLevel;
5use crate::log_level::LogLevel;
6use crate::log_line::LogLine;
7
8pub struct LogDecoder {
9    buffered: Option<LogLine>,
10    previous_level: LogLevel,
11}
12
13impl LogDecoder {
14    #[must_use]
15    pub const fn new() -> Self {
16        Self {
17            buffered: None,
18            previous_level: LogLevel::None,
19        }
20    }
21
22    pub fn feed(&mut self, level: IncomingLogLevel, text: &str) -> DecodeResult {
23        match level {
24            IncomingLogLevel::Cont => self.feed_cont(text),
25            IncomingLogLevel::Debug => self.feed_non_cont(LogLevel::Debug, text),
26            IncomingLogLevel::Error => self.feed_non_cont(LogLevel::Error, text),
27            IncomingLogLevel::Info => self.feed_non_cont(LogLevel::Info, text),
28            IncomingLogLevel::None => self.feed_non_cont(LogLevel::None, text),
29            IncomingLogLevel::Unknown(raw) => self.feed_non_cont(LogLevel::Unknown(raw), text),
30            IncomingLogLevel::Warn => self.feed_non_cont(LogLevel::Warn, text),
31        }
32    }
33
34    fn feed_cont(&mut self, text: &str) -> DecodeResult {
35        if let Some(LogLine {
36            level,
37            text: mut buffer,
38        }) = self.buffered.take()
39        {
40            buffer.push_str(text);
41            if let Some(without_newline) = buffer.strip_suffix('\n') {
42                DecodeResult {
43                    output: DecodeOutput::Line(LogLine {
44                        level,
45                        text: without_newline.to_owned(),
46                    }),
47                    anomaly: None,
48                }
49            } else {
50                self.buffered = Some(LogLine {
51                    level,
52                    text: buffer,
53                });
54                DecodeResult {
55                    output: DecodeOutput::None,
56                    anomaly: None,
57                }
58            }
59        } else {
60            self.feed_orphan_cont(text)
61        }
62    }
63
64    fn feed_orphan_cont(&mut self, text: &str) -> DecodeResult {
65        let level = self.previous_level;
66        if let Some(without_newline) = text.strip_suffix('\n') {
67            DecodeResult {
68                output: DecodeOutput::Line(LogLine {
69                    level,
70                    text: without_newline.to_owned(),
71                }),
72                anomaly: Some(DecodeAnomaly::OrphanCont),
73            }
74        } else {
75            self.buffered = Some(LogLine {
76                level,
77                text: text.to_owned(),
78            });
79            DecodeResult {
80                output: DecodeOutput::None,
81                anomaly: Some(DecodeAnomaly::OrphanCont),
82            }
83        }
84    }
85
86    fn feed_non_cont(&mut self, level: LogLevel, text: &str) -> DecodeResult {
87        self.previous_level = level;
88        let stale = self.buffered.take();
89        match (text.strip_suffix('\n'), stale) {
90            (
91                Some(without_newline),
92                Some(LogLine {
93                    level: stale_level,
94                    text: stale_text,
95                }),
96            ) => DecodeResult {
97                output: DecodeOutput::TwoLines {
98                    earlier: LogLine {
99                        level: stale_level,
100                        text: stale_text,
101                    },
102                    current: LogLine {
103                        level,
104                        text: without_newline.to_owned(),
105                    },
106                },
107                anomaly: Some(DecodeAnomaly::StaleBufferAbandoned),
108            },
109            (Some(without_newline), None) => DecodeResult {
110                output: DecodeOutput::Line(LogLine {
111                    level,
112                    text: without_newline.to_owned(),
113                }),
114                anomaly: None,
115            },
116            (
117                None,
118                Some(LogLine {
119                    level: stale_level,
120                    text: stale_text,
121                }),
122            ) => {
123                self.buffered = Some(LogLine {
124                    level,
125                    text: text.to_owned(),
126                });
127                DecodeResult {
128                    output: DecodeOutput::Line(LogLine {
129                        level: stale_level,
130                        text: stale_text,
131                    }),
132                    anomaly: Some(DecodeAnomaly::StaleBufferAbandoned),
133                }
134            }
135            (None, None) => {
136                self.buffered = Some(LogLine {
137                    level,
138                    text: text.to_owned(),
139                });
140                DecodeResult {
141                    output: DecodeOutput::None,
142                    anomaly: None,
143                }
144            }
145        }
146    }
147}
148
149impl Default for LogDecoder {
150    fn default() -> Self {
151        Self::new()
152    }
153}
154
155#[cfg(test)]
156mod tests {
157    use super::LogDecoder;
158    use crate::decode_anomaly::DecodeAnomaly;
159    use crate::decode_output::DecodeOutput;
160    use crate::decode_result::DecodeResult;
161    use crate::incoming_log_level::IncomingLogLevel;
162    use crate::log_level::LogLevel;
163    use crate::log_line::LogLine;
164
165    #[test]
166    fn a_complete_line_is_decoded_without_its_newline() {
167        let mut decoder = LogDecoder::new();
168        let result = decoder.feed(IncomingLogLevel::Info, "hello\n");
169
170        assert_eq!(
171            result,
172            DecodeResult {
173                output: DecodeOutput::Line(LogLine {
174                    level: LogLevel::Info,
175                    text: "hello".to_owned(),
176                }),
177                anomaly: None,
178            }
179        );
180    }
181
182    #[test]
183    fn a_line_without_a_newline_is_held_back() {
184        let mut decoder = LogDecoder::new();
185        let result = decoder.feed(IncomingLogLevel::Info, "hello");
186
187        assert_eq!(
188            result,
189            DecodeResult {
190                output: DecodeOutput::None,
191                anomaly: None,
192            }
193        );
194    }
195
196    #[test]
197    fn continuations_join_until_the_newline() {
198        let mut decoder = LogDecoder::new();
199        decoder.feed(IncomingLogLevel::Info, "part1 ");
200        decoder.feed(IncomingLogLevel::Cont, "part2 ");
201        let result = decoder.feed(IncomingLogLevel::Cont, "part3\n");
202
203        assert_eq!(
204            result,
205            DecodeResult {
206                output: DecodeOutput::Line(LogLine {
207                    level: LogLevel::Info,
208                    text: "part1 part2 part3".to_owned(),
209                }),
210                anomaly: None,
211            }
212        );
213    }
214
215    #[test]
216    fn a_new_complete_line_flushes_the_held_line_as_stale() {
217        let mut decoder = LogDecoder::new();
218        decoder.feed(IncomingLogLevel::Info, "stale");
219        let result = decoder.feed(IncomingLogLevel::Warn, "fresh\n");
220
221        assert_eq!(
222            result,
223            DecodeResult {
224                output: DecodeOutput::TwoLines {
225                    earlier: LogLine {
226                        level: LogLevel::Info,
227                        text: "stale".to_owned(),
228                    },
229                    current: LogLine {
230                        level: LogLevel::Warn,
231                        text: "fresh".to_owned(),
232                    },
233                },
234                anomaly: Some(DecodeAnomaly::StaleBufferAbandoned),
235            }
236        );
237    }
238
239    #[test]
240    fn a_new_partial_line_flushes_the_held_line_and_is_held_in_its_place() {
241        let mut decoder = LogDecoder::new();
242        decoder.feed(IncomingLogLevel::Info, "first");
243        let result = decoder.feed(IncomingLogLevel::Warn, "second");
244
245        assert_eq!(
246            result,
247            DecodeResult {
248                output: DecodeOutput::Line(LogLine {
249                    level: LogLevel::Info,
250                    text: "first".to_owned(),
251                }),
252                anomaly: Some(DecodeAnomaly::StaleBufferAbandoned),
253            }
254        );
255
256        let follow_up = decoder.feed(IncomingLogLevel::Cont, "more\n");
257        assert_eq!(
258            follow_up,
259            DecodeResult {
260                output: DecodeOutput::Line(LogLine {
261                    level: LogLevel::Warn,
262                    text: "secondmore".to_owned(),
263                }),
264                anomaly: None,
265            }
266        );
267    }
268
269    #[test]
270    fn a_continuation_without_any_earlier_line_is_an_orphan_anomaly() {
271        let mut decoder = LogDecoder::new();
272        let result = decoder.feed(IncomingLogLevel::Cont, "ghost\n");
273
274        assert_eq!(
275            result,
276            DecodeResult {
277                output: DecodeOutput::Line(LogLine {
278                    level: LogLevel::None,
279                    text: "ghost".to_owned(),
280                }),
281                anomaly: Some(DecodeAnomaly::OrphanCont),
282            }
283        );
284    }
285
286    #[test]
287    fn an_orphan_continuation_takes_the_previous_line_level() {
288        let mut decoder = LogDecoder::new();
289        decoder.feed(IncomingLogLevel::Warn, "complete\n");
290        let result = decoder.feed(IncomingLogLevel::Cont, "ghost\n");
291
292        assert_eq!(
293            result,
294            DecodeResult {
295                output: DecodeOutput::Line(LogLine {
296                    level: LogLevel::Warn,
297                    text: "ghost".to_owned(),
298                }),
299                anomaly: Some(DecodeAnomaly::OrphanCont),
300            }
301        );
302    }
303
304    #[test]
305    fn a_complete_line_keeps_the_level_it_arrived_with() {
306        let incoming_levels = [
307            IncomingLogLevel::None,
308            IncomingLogLevel::Unknown(9999),
309            IncomingLogLevel::Debug,
310            IncomingLogLevel::Error,
311        ];
312
313        assert_eq!(
314            incoming_levels.map(|incoming_level| LogDecoder::new().feed(incoming_level, "line\n")),
315            [
316                LogLevel::None,
317                LogLevel::Unknown(9999),
318                LogLevel::Debug,
319                LogLevel::Error
320            ]
321            .map(|level| {
322                DecodeResult {
323                    output: DecodeOutput::Line(LogLine {
324                        level,
325                        text: "line".to_owned(),
326                    }),
327                    anomaly: None,
328                }
329            })
330        );
331    }
332
333    #[test]
334    fn feed_orphan_cont_without_newline_buffers_text() {
335        let mut decoder = LogDecoder::new();
336        let result = decoder.feed(IncomingLogLevel::Cont, "fragment");
337
338        assert_eq!(
339            result,
340            DecodeResult {
341                output: DecodeOutput::None,
342                anomaly: Some(DecodeAnomaly::OrphanCont),
343            }
344        );
345
346        let follow_up = decoder.feed(IncomingLogLevel::Cont, " rest\n");
347        assert_eq!(
348            follow_up,
349            DecodeResult {
350                output: DecodeOutput::Line(LogLine {
351                    level: LogLevel::None,
352                    text: "fragment rest".to_owned(),
353                }),
354                anomaly: None,
355            }
356        );
357    }
358
359    #[test]
360    fn a_default_decoder_decodes_like_a_new_one() {
361        let mut default_decoder = LogDecoder::default();
362        let new_decoder_result = LogDecoder::new().feed(IncomingLogLevel::Info, "compare\n");
363        let default_result = default_decoder.feed(IncomingLogLevel::Info, "compare\n");
364
365        assert_eq!(default_result, new_decoder_result);
366    }
367}