tale-ndjson 0.4.0

A tail-compatible tool for pretty-printing ndjson files, especially logs.
Documentation
//! Tale - A high-performance log pretty-printer for ndjson files
//!
//! This library provides utilities for reading, parsing, and formatting
//! newline-delimited JSON log files with memory-efficient processing
//! and chunked file processing.
//!
//! ## Library surface
//!
//! This crate is, first and foremost, the `tale` binary. The `pub` items here
//! exist to serve that binary and the `benches/` — both separate crate targets,
//! so they can only reach `pub` items. They are **not** a stability-guaranteed
//! public API. Items re-exported solely for the benchmarks are marked
//! `#[doc(hidden)]`; `TaleError` and the [`FileProcessor`] trait are the only
//! pieces shaped as a reusable surface.

use std::io;

use bytes::{Buf, BytesMut};
use logpatterns::*;
use miette::Result;

pub mod colors;
pub mod config;
pub(crate) mod defaults;
pub(crate) mod errors;
#[cfg(debug_assertions)]
pub mod json_profiler;
pub(crate) mod logpatterns;
pub(crate) mod memory_budget;
pub mod metrics;
pub mod multiplexed;
pub mod readers;

#[cfg(test)]
mod tests;

// The error type and the core reader trait are the reusable surface.
pub use errors::TaleError;
// Re-exported only so `benches/` (a separate crate target) can reach them.
// Still `pub` so the benchmarks compile; hidden from the published docs.
#[doc(hidden)]
pub use memory_budget::{MemoryBudget, MemoryPressure};
#[doc(hidden)]
pub use readers::ChunkedFileReader;
pub use readers::FileProcessor;
#[doc(hidden)]
pub use readers::strategies::StaticStrategy;

/// Capacity for the buffered stdout writer. Without it, `Stdout`'s internal
/// line writer flushes a syscall for every newline — one per log line.
pub(crate) const STDOUT_BUFFER_CAPACITY: usize = 64 * 1024;

/// A stdout writer buffered well past the line length, so writes coalesce
/// into ~64KB syscalls instead of one syscall per line.
pub(crate) fn buffered_stdout() -> io::BufWriter<io::StdoutLock<'static>> {
    io::BufWriter::with_capacity(STDOUT_BUFFER_CAPACITY, io::stdout().lock())
}

/// Write to an output writer, preserving the underlying `io::ErrorKind`.
///
/// `IntoDiagnostic::into_diagnostic` flattens an `io::Error` into a stringly
/// custom error, losing `ErrorKind::BrokenPipe` — which `main` relies on to
/// exit quietly when a downstream consumer (`tale big.log | head`) closes the
/// pipe on us. Use this (or [`flush_out`]) for every write to stdout.
#[inline]
pub(crate) fn write_out<W: io::Write>(out: &mut W, bytes: &[u8]) -> Result<()> {
    out.write_all(bytes).map_err(TaleError::from)?;
    Ok(())
}

/// Flush an output writer, preserving `io::ErrorKind` the way [`write_out`]
/// does.
#[inline]
pub(crate) fn flush_out<W: io::Write>(out: &mut W) -> Result<()> {
    out.flush().map_err(TaleError::from)?;
    Ok(())
}

/// Process a single line of input (JSON or plain text) and write to output.
#[inline]
pub fn process_line<W: io::Write>(line: &str, buffer: &mut BytesMut, out: &mut W) -> Result<()> {
    match serde_json::from_str::<Printable<'_>>(line) {
        Ok(message) => {
            // Profile which variant was parsed (debug builds only for minimal
            // overhead)
            #[cfg(debug_assertions)]
            json_profiler::record_variant(&message);

            message.write(buffer);
            write_out(out, buffer.chunk())?;
            write_out(out, b"\n")?; // blank line between log entries
            buffer.clear();
        }
        Err(_) => {
            // Profile parse failures (debug builds only)
            #[cfg(debug_assertions)]
            json_profiler::record_parse_error();

            // Not JSON, but it may still be a logfmt line (Heroku-style
            // `key=value` pairs). Those are only reachable here: the
            // untagged enum requires valid JSON before it can ever see
            // the Logfmt variant.
            if let Some(logfmt_line) = logpatterns::try_parse_logfmt(line) {
                let printable = Printable::Logfmt(logfmt_line);
                #[cfg(debug_assertions)]
                json_profiler::record_variant(&printable);

                printable.write(buffer);
                write_out(out, buffer.chunk())?;
                write_out(out, b"\n")?;
                buffer.clear();
            } else {
                write_out(out, line.as_bytes())?;
                write_out(out, b"\n")?;
            }
        }
    }
    Ok(())
}

/// Strip trailing newline(s) from the string input, handling Windows line
/// endings as well.
#[inline]
pub fn strip_line_ending(line: &mut String) {
    if line.ends_with('\n') {
        line.pop();
        if line.ends_with('\r') {
            // Windows line endings are not handled well by Rust's line
            // iterators, but we might as well try.
            line.pop();
        }
    }
}