grippo 0.2.3

Parse, match and scrub data faster and more efficiently.
Documentation
// Project:   grippo
// File:      src/format/w3c.rs
// Purpose:   The W3C extended log format, read a line at a time
// Language:  Rust
//
// License:   Apache-2.0
// Copyright: (c) 2026 HYPERI PTY LIMITED

//! W3C extended log files, as web and proxy servers write them.
//!
//! A `#Fields:` directive names the columns of the lines after it, other `#`
//! lines are directives that write nothing, and a record's values are split
//! on ASCII whitespace, with `-` written as an empty field.
//!
//! The names carry from one line to the next, so a reader is kept per file.
//! [`W3c::names`] and [`W3c::with_names`] save and restore them, for a reader
//! that picks a file up where it stopped.

use std::borrow::Cow;

use thiserror::Error;

use crate::parse::{FieldSink, FieldValue, Hint};
use crate::path::key_part;

/// Why a record line can't be read.
#[derive(Debug, Clone, PartialEq, Eq, Error)]
#[non_exhaustive]
pub enum W3cError {
    /// A record came before any `#Fields:` line.
    #[error("no #Fields line was found for this file")]
    NoFields,
    /// A record has a different number of values from the names.
    #[error("expected {expected} fields, got {got}")]
    Columns {
        /// The number of names.
        expected: usize,
        /// The number of values the line holds.
        got: usize,
    },
}

/// What one line was.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum Line {
    /// A `#` directive. A `#Fields:` line sets the names.
    Directive,
    /// A record, and the number of fields it wrote.
    Record(usize),
}

/// One file's reader: the names its last `#Fields:` line gave.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct W3c {
    names: Option<Vec<String>>,
}

impl W3c {
    /// A reader with no names yet.
    #[must_use]
    pub const fn new() -> Self {
        Self { names: None }
    }

    /// A reader that goes on with names saved from an earlier one.
    #[must_use]
    pub const fn with_names(names: Vec<String>) -> Self {
        Self { names: Some(names) }
    }

    /// The names the last `#Fields:` line gave, if one has been read.
    #[must_use]
    pub fn names(&self) -> Option<&[String]> {
        self.names.as_deref()
    }

    /// Reads one line, without its line end. A directive writes nothing, and
    /// a record writes one field per name, in order.
    ///
    /// # Errors
    ///
    /// [`W3cError::NoFields`] for a record before any `#Fields:` line, and
    /// [`W3cError::Columns`] when its value count differs from the names'.
    /// Either way nothing is written.
    pub fn line<'a>(
        &mut self,
        line: &'a [u8],
        out: &mut dyn FieldSink<'a>,
    ) -> Result<Line, W3cError> {
        if let Some(directive) = line.strip_prefix(b"#") {
            if let Some(fields) = directive.strip_prefix(b"Fields:") {
                self.names = Some(
                    words(fields)
                        .map(|name| String::from_utf8_lossy(name).into_owned())
                        .collect(),
                );
            }
            return Ok(Line::Directive);
        }
        let names = self.names.as_deref().ok_or(W3cError::NoFields)?;
        let got = words(line).count();
        if got != names.len() {
            return Err(W3cError::Columns {
                expected: names.len(),
                got,
            });
        }
        for (name, value) in names.iter().zip(words(line)) {
            let value: &[u8] = if value == b"-" { b"" } else { value };
            out.field(
                &key_part(Cow::Borrowed(name)),
                FieldValue::borrowed(value, Hint::Text),
            );
        }
        Ok(Line::Record(got))
    }
}

/// The runs of `text` between ASCII whitespace.
fn words(text: &[u8]) -> impl Iterator<Item = &[u8]> {
    text.split(u8::is_ascii_whitespace)
        .filter(|w| !w.is_empty())
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::parse::Fields;

    type Row = (String, String);

    fn read(w3c: &mut W3c, line: &str) -> (Result<Line, W3cError>, Vec<Row>) {
        let mut out = Fields::new();
        let got = w3c.line(line.as_bytes(), &mut out);
        let rows = out
            .as_slice()
            .iter()
            .map(|(k, v)| (k.clone(), String::from_utf8_lossy(&v.bytes).into_owned()))
            .collect();
        (got, rows)
    }

    #[test]
    fn a_dotted_column_name_is_written_quoted_and_reads_back_whole() {
        for (name, value) in [(r#"["a.b"]"#, "1"), ("c", "2")] {
            let mut w3c = W3c::new();
            let mut out = Fields::new();
            w3c.line(b"#Fields: a.b c", &mut out).unwrap();
            w3c.line(b"1 2", &mut out).unwrap();
            let got = out
                .get(name)
                .map(|v| String::from_utf8_lossy(&v.bytes).into_owned());
            assert_eq!(got.as_deref(), Some(value), "{name}");
            #[cfg(feature = "record")]
            {
                use crate::record::Record;
                let keys: Vec<_> = crate::path::keys(name).collect();
                let at = (&out).find(&keys[..]).unwrap();
                assert_eq!((&out).text(at).unwrap(), value, "{name}");
            }
        }
    }

    #[test]
    fn directives_set_names_and_records_read_by_them() {
        use W3cError::{Columns, NoFields};
        let mut w3c = W3c::new();
        let lines: &[(&str, Result<Line, W3cError>, &[(&str, &str)])] = &[
            ("a b c", Err(NoFields), &[]),
            ("#Software: IIS", Ok(Line::Directive), &[]),
            ("#Version: 1.0", Ok(Line::Directive), &[]),
            ("#Date: 2024-01-01 00:00:00", Ok(Line::Directive), &[]),
            (
                "#Fields: date time cs-method cs(User-Agent)",
                Ok(Line::Directive),
                &[],
            ),
            (
                "2024-01-01 00:00:01 GET Mozilla/5.0+(X11)",
                Ok(Line::Record(4)),
                &[
                    ("date", "2024-01-01"),
                    ("time", "00:00:01"),
                    ("cs-method", "GET"),
                    ("cs(User-Agent)", "Mozilla/5.0+(X11)"),
                ],
            ),
            (
                "2024-01-01\t00:00:02  -  -",
                Ok(Line::Record(4)),
                &[
                    ("date", "2024-01-01"),
                    ("time", "00:00:02"),
                    ("cs-method", ""),
                    ("cs(User-Agent)", ""),
                ],
            ),
            (
                "2024-01-01 00:00:01",
                Err(Columns {
                    expected: 4,
                    got: 2,
                }),
                &[],
            ),
            (
                "a b c d e",
                Err(Columns {
                    expected: 4,
                    got: 5,
                }),
                &[],
            ),
            ("# Fields: x", Ok(Line::Directive), &[]),
            ("#Fields: x y", Ok(Line::Directive), &[]),
            ("1 --", Ok(Line::Record(2)), &[("x", "1"), ("y", "--")]),
            ("#Fields:", Ok(Line::Directive), &[]),
            ("", Ok(Line::Record(0)), &[]),
            (
                "1",
                Err(Columns {
                    expected: 0,
                    got: 1,
                }),
                &[],
            ),
        ];
        for (line, want, fields) in lines {
            let (got, rows) = read(&mut w3c, line);
            assert_eq!(&got, want, "{line:?}");
            let want_rows: Vec<Row> = fields
                .iter()
                .map(|&(k, v)| (k.to_owned(), v.to_owned()))
                .collect();
            assert_eq!(rows, want_rows, "{line:?}");
        }
    }

    #[test]
    fn names_carry_over_to_a_reader_that_goes_on() {
        let mut first = W3c::new();
        assert_eq!(
            read(&mut first, "#Fields: date time").0,
            Ok(Line::Directive)
        );
        assert_eq!(
            first.names(),
            Some(&["date".to_owned(), "time".to_owned()][..])
        );
        let mut next = W3c::with_names(first.names().unwrap_or_default().to_vec());
        assert_eq!(read(&mut next, "2024-01-01 -").0, Ok(Line::Record(2)));
        assert_eq!(
            W3cError::Columns {
                expected: 3,
                got: 2
            }
            .to_string(),
            "expected 3 fields, got 2"
        );
        assert_eq!(
            W3cError::NoFields.to_string(),
            "no #Fields line was found for this file"
        );
    }
}