grippo 0.2.4

Parse, match and scrub data faster and more efficiently.
Documentation
// Project:   grippo
// File:      src/format/access.rs
// Purpose:   Access log formats, translated to dissect patterns
// Language:  Rust
//
// License:   Apache-2.0
// Copyright: (c) 2026 HYPERI PTY LIMITED

//! A web server's access log format string becomes a dissect pattern, so the
//! line it writes splits on the same literals it was built from.
//!
//! nginx's `$name` becomes `%{name}`. Apache's directives (`%h`, `%>s`,
//! `%{User-agent}i`) become their usual field names.

use super::dissect::{Dissect, DissectConfig, DissectError};

/// An nginx `log_format` string as a dissect pattern.
#[must_use]
pub fn nginx_pattern(format: &str) -> String {
    let mut out = String::with_capacity(format.len() + 16);
    let mut chars = format.char_indices();
    while let Some((i, c)) = chars.next() {
        if c != '$' {
            out.push(c);
            continue;
        }
        let rest = &format[i + 1..];
        let n = rest
            .find(|ch: char| !(ch.is_ascii_alphanumeric() || ch == '_'))
            .unwrap_or(rest.len());
        if n == 0 {
            out.push(c);
            continue;
        }
        out.push_str("%{");
        out.push_str(&rest[..n]);
        out.push('}');
        for _ in 0..n {
            chars.next();
        }
    }
    out
}

/// The field name for an Apache directive letter, or `None` for one this
/// doesn't name.
const fn apache_name(directive: char) -> Option<&'static str> {
    Some(match directive {
        'h' => "remote_host",
        'a' => "remote_addr",
        'l' => "remote_logname",
        'u' => "remote_user",
        't' => "time",
        'r' => "request",
        's' => "status",
        'b' | 'B' => "bytes_sent",
        'D' => "duration_us",
        'T' => "duration_s",
        'v' => "server_name",
        'p' => "server_port",
        'm' => "method",
        'U' => "url_path",
        'q' => "query_string",
        'H' => "protocol",
        _ => return None,
    })
}

/// An Apache `LogFormat` string as a dissect pattern.
///
/// `%{Name}i` becomes the request header `name`, lower-cased with `-` as `_`,
/// and an unknown directive is kept as a skipped field.
#[must_use]
pub fn apache_pattern(format: &str) -> String {
    let mut out = String::with_capacity(format.len() + 32);
    let b = format.as_bytes();
    let mut i = 0;
    while i < b.len() {
        if b[i] != b'%' {
            let len = format[i..].chars().next().map_or(1, char::len_utf8);
            out.push_str(&format[i..i + len]);
            i += len;
            continue;
        }
        let mut j = i + 1;
        while matches!(b.get(j), Some(b'>' | b'<')) {
            j += 1;
        }
        if b.get(j) == Some(&b'{')
            && let Some(close) = format[j..].find('}')
        {
            let arg = &format[j + 1..j + close];
            let kind = format[j + close + 1..].chars().next();
            let name = arg.to_ascii_lowercase().replace('-', "_");
            match kind {
                Some('i') => {
                    out.push_str("%{");
                    out.push_str(&name);
                    out.push('}');
                }
                _ => out.push_str("%{}"),
            }
            i = j + close + 1 + kind.map_or(0, char::len_utf8);
            continue;
        }
        match format[j..].chars().next() {
            Some(d) => {
                match apache_name(d) {
                    Some(name) => {
                        out.push_str("%{");
                        out.push_str(name);
                        out.push('}');
                    }
                    None => out.push_str("%{}"),
                }
                i = j + d.len_utf8();
            }
            None => i = j,
        }
    }
    out
}

/// A dissect parser for an nginx `log_format`.
///
/// # Errors
///
/// As [`Dissect::new`] on the translated pattern.
pub fn nginx(format: &str) -> Result<Dissect, DissectError> {
    Dissect::new(&DissectConfig {
        pattern: nginx_pattern(format),
        append_separator: " ".to_owned(),
    })
}

/// A dissect parser for an Apache `LogFormat`.
///
/// # Errors
///
/// As [`Dissect::new`] on the translated pattern.
pub fn apache(format: &str) -> Result<Dissect, DissectError> {
    Dissect::new(&DissectConfig {
        pattern: apache_pattern(format),
        append_separator: " ".to_owned(),
    })
}

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

    const LINE: &str = r#"10.1.2.3 - alice [26/Nov/2026:11:22:33 +1100] "GET /a?b=1 HTTP/1.1" 200 512 "-" "curl/8.0""#;

    fn read(p: &Dissect) -> Vec<(String, String)> {
        let mut out = Fields::new();
        assert_eq!(p.parse(LINE.as_bytes(), &mut out).unwrap(), Parsed::Done);
        out.as_slice()
            .iter()
            .map(|(n, v)| (n.clone(), String::from_utf8_lossy(&v.bytes).into_owned()))
            .collect()
    }

    #[test]
    fn nginx_combined_format() {
        let fmt = r#"$remote_addr - $remote_user [$time_local] "$request" $status $body_bytes_sent "$http_referer" "$http_user_agent""#;
        assert!(nginx_pattern(fmt).starts_with("%{remote_addr} - %{remote_user} [%{time_local}]"));
        let f = read(&nginx(fmt).unwrap());
        assert_eq!(f[0], ("remote_addr".into(), "10.1.2.3".into()));
        assert_eq!(f[3], ("request".into(), "GET /a?b=1 HTTP/1.1".into()));
        assert_eq!(f[7], ("http_user_agent".into(), "curl/8.0".into()));
    }

    #[test]
    fn apache_combined_format() {
        let fmt = r#"%h %l %u [%t] "%r" %>s %b "%{Referer}i" "%{User-agent}i""#;
        assert_eq!(
            apache_pattern(fmt),
            r#"%{remote_host} %{remote_logname} %{remote_user} [%{time}] "%{request}" %{status} %{bytes_sent} "%{referer}" "%{user_agent}""#
        );
        let f = read(&apache(fmt).unwrap());
        assert_eq!(f[5], ("status".into(), "200".into()));
        assert_eq!(f[8], ("user_agent".into(), "curl/8.0".into()));
    }
}