tale_ndjson/lib.rs
1//! Tale - A high-performance log pretty-printer for ndjson files
2//!
3//! This library provides utilities for reading, parsing, and formatting
4//! newline-delimited JSON log files with memory-efficient processing
5//! and chunked file processing.
6//!
7//! ## Library surface
8//!
9//! This crate is, first and foremost, the `tale` binary. The `pub` items here
10//! exist to serve that binary and the `benches/` — both separate crate targets,
11//! so they can only reach `pub` items. They are **not** a stability-guaranteed
12//! public API. Items re-exported solely for the benchmarks are marked
13//! `#[doc(hidden)]`; `TaleError` and the [`FileProcessor`] trait are the only
14//! pieces shaped as a reusable surface.
15
16use std::io;
17
18use bytes::{Buf, BytesMut};
19use logpatterns::*;
20use miette::Result;
21
22pub mod colors;
23pub mod config;
24pub(crate) mod defaults;
25pub(crate) mod errors;
26#[cfg(debug_assertions)]
27pub mod json_profiler;
28pub(crate) mod logpatterns;
29pub(crate) mod memory_budget;
30pub mod metrics;
31pub mod multiplexed;
32pub mod readers;
33
34#[cfg(test)]
35mod tests;
36
37// The error type and the core reader trait are the reusable surface.
38pub use errors::TaleError;
39// Re-exported only so `benches/` (a separate crate target) can reach them.
40// Still `pub` so the benchmarks compile; hidden from the published docs.
41#[doc(hidden)]
42pub use memory_budget::{MemoryBudget, MemoryPressure};
43#[doc(hidden)]
44pub use readers::ChunkedFileReader;
45pub use readers::FileProcessor;
46#[doc(hidden)]
47pub use readers::strategies::StaticStrategy;
48
49/// Capacity for the buffered stdout writer. Without it, `Stdout`'s internal
50/// line writer flushes a syscall for every newline — one per log line.
51pub(crate) const STDOUT_BUFFER_CAPACITY: usize = 64 * 1024;
52
53/// A stdout writer buffered well past the line length, so writes coalesce
54/// into ~64KB syscalls instead of one syscall per line.
55pub(crate) fn buffered_stdout() -> io::BufWriter<io::StdoutLock<'static>> {
56 io::BufWriter::with_capacity(STDOUT_BUFFER_CAPACITY, io::stdout().lock())
57}
58
59/// Write to an output writer, preserving the underlying `io::ErrorKind`.
60///
61/// `IntoDiagnostic::into_diagnostic` flattens an `io::Error` into a stringly
62/// custom error, losing `ErrorKind::BrokenPipe` — which `main` relies on to
63/// exit quietly when a downstream consumer (`tale big.log | head`) closes the
64/// pipe on us. Use this (or [`flush_out`]) for every write to stdout.
65#[inline]
66pub(crate) fn write_out<W: io::Write>(out: &mut W, bytes: &[u8]) -> Result<()> {
67 out.write_all(bytes).map_err(TaleError::from)?;
68 Ok(())
69}
70
71/// Flush an output writer, preserving `io::ErrorKind` the way [`write_out`]
72/// does.
73#[inline]
74pub(crate) fn flush_out<W: io::Write>(out: &mut W) -> Result<()> {
75 out.flush().map_err(TaleError::from)?;
76 Ok(())
77}
78
79/// Process a single line of input (JSON or plain text) and write to output.
80#[inline]
81pub fn process_line<W: io::Write>(line: &str, buffer: &mut BytesMut, out: &mut W) -> Result<()> {
82 match serde_json::from_str::<Printable<'_>>(line) {
83 Ok(message) => {
84 // Profile which variant was parsed (debug builds only for minimal
85 // overhead)
86 #[cfg(debug_assertions)]
87 json_profiler::record_variant(&message);
88
89 message.write(buffer);
90 write_out(out, buffer.chunk())?;
91 write_out(out, b"\n")?; // blank line between log entries
92 buffer.clear();
93 }
94 Err(_) => {
95 // Profile parse failures (debug builds only)
96 #[cfg(debug_assertions)]
97 json_profiler::record_parse_error();
98
99 // Not JSON, but it may still be a logfmt line (Heroku-style
100 // `key=value` pairs). Those are only reachable here: the
101 // untagged enum requires valid JSON before it can ever see
102 // the Logfmt variant.
103 if let Some(logfmt_line) = logpatterns::try_parse_logfmt(line) {
104 let printable = Printable::Logfmt(logfmt_line);
105 #[cfg(debug_assertions)]
106 json_profiler::record_variant(&printable);
107
108 printable.write(buffer);
109 write_out(out, buffer.chunk())?;
110 write_out(out, b"\n")?;
111 buffer.clear();
112 } else {
113 write_out(out, line.as_bytes())?;
114 write_out(out, b"\n")?;
115 }
116 }
117 }
118 Ok(())
119}
120
121/// Strip trailing newline(s) from the string input, handling Windows line
122/// endings as well.
123#[inline]
124pub fn strip_line_ending(line: &mut String) {
125 if line.ends_with('\n') {
126 line.pop();
127 if line.ends_with('\r') {
128 // Windows line endings are not handled well by Rust's line
129 // iterators, but we might as well try.
130 line.pop();
131 }
132 }
133}