hyperlane-plugin-logger 23.1.0

A logging plugin for the Hyperlane framework, writing the log of a server to the console, to a file, or to both.
Documentation
use super::*;

/// Resolves a [`Method`] to a borrowed string slice without allocating.
///
/// # Arguments
///
/// - `&Method` - Incoming HTTP request method.
///
/// # Returns
///
/// - `&str` - Canonical method string, or [`METHOD_UNKNOWN`] when empty.
#[inline(always)]
pub(crate) fn request_method_str(method: &Method) -> &str {
    match method {
        Method::Get => GET,
        Method::Post => POST,
        Method::Put => PUT,
        Method::Delete => DELETE,
        Method::Patch => PATCH,
        Method::Head => HEAD,
        Method::Options => OPTIONS,
        Method::Connect => CONNECT,
        Method::Trace => TRACE,
        Method::Unknown(custom) => {
            if custom.is_empty() {
                METHOD_UNKNOWN
            } else {
                custom.as_str()
            }
        }
    }
}

/// Returns the prebuilt JSON prefix `{"level":"<LEVEL>","target":"` for `level`.
///
/// # Arguments
///
/// - `Level` - Record severity level.
///
/// # Returns
///
/// - `&'static str` - Pre-formatted JSON prefix.
#[inline(always)]
pub(crate) fn json_level_prefix(level: Level) -> &'static str {
    match level {
        Level::Error => JSON_PREFIX_ERROR,
        Level::Warn => JSON_PREFIX_WARN,
        Level::Info => JSON_PREFIX_INFO,
        Level::Debug => JSON_PREFIX_DEBUG,
        Level::Trace => JSON_PREFIX_TRACE,
    }
}

/// Returns the prebuilt plain-text level prefix (`"INFO "`, etc.) for `level`.
///
/// # Arguments
///
/// - `Level` - Record severity level.
///
/// # Returns
///
/// - `&'static str` - Pre-formatted plain level prefix.
#[inline(always)]
pub(crate) fn plain_level_prefix(level: Level) -> &'static str {
    match level {
        Level::Error => PLAIN_PREFIX_ERROR,
        Level::Warn => PLAIN_PREFIX_WARN,
        Level::Info => PLAIN_PREFIX_INFO,
        Level::Debug => PLAIN_PREFIX_DEBUG,
        Level::Trace => PLAIN_PREFIX_TRACE,
    }
}

/// Finds the first byte offset in `bytes` that requires plain-text log sanitization using 8-byte SWAR.
///
/// # Arguments
///
/// - `&[u8]` - Raw UTF-8 input bytes.
///
/// # Returns
///
/// - `Option<usize>` - First byte index requiring sanitization, or `None` when clean.
#[inline]
pub(crate) fn find_first_plain_unsafe(bytes: &[u8]) -> Option<usize> {
    let (chunks, rem): (&[[u8; 8]], &[u8]) = bytes.as_chunks::<8>();
    for (idx, chunk) in chunks.iter().enumerate() {
        let word: u64 = u64::from_ne_bytes(*chunk);
        let non_ascii: u64 = word & SWAR_HIGH_BITS;
        let below_space: u64 = word.wrapping_sub(SWAR_SPACE_BROADCAST) & SWAR_HIGH_BITS;
        let is_del: u64 = word.wrapping_add(SWAR_ONES_BROADCAST) & SWAR_HIGH_BITS;
        let mask: u64 = (non_ascii | below_space) | is_del;
        if mask != 0 {
            let base: usize = idx * 8;
            for (j, &b) in chunk.iter().enumerate() {
                if (b < 0x20 && b != b'\t') || b == 0x7f {
                    return Some(base + j);
                }
            }
        }
    }
    let base: usize = chunks.len() * 8;
    for (j, &b) in rem.iter().enumerate() {
        if (b < 0x20 && b != b'\t') || b == 0x7f {
            return Some(base + j);
        }
    }
    None
}

/// Finds the first byte offset in `bytes` that requires JSON log escaping using 8-byte SWAR.
///
/// # Arguments
///
/// - `&[u8]` - Raw UTF-8 input bytes.
///
/// # Returns
///
/// - `Option<usize>` - First byte index requiring JSON escaping, or `None` when clean.
#[inline]
pub(crate) fn find_first_json_unsafe(bytes: &[u8]) -> Option<usize> {
    let (chunks, rem): (&[[u8; 8]], &[u8]) = bytes.as_chunks::<8>();
    for (idx, chunk) in chunks.iter().enumerate() {
        let word: u64 = u64::from_ne_bytes(*chunk);
        let non_ascii: u64 = word & SWAR_HIGH_BITS;
        let below_space: u64 = word.wrapping_sub(SWAR_SPACE_BROADCAST) & SWAR_HIGH_BITS;
        let is_del: u64 = word.wrapping_add(SWAR_ONES_BROADCAST) & SWAR_HIGH_BITS;
        let xq: u64 = word ^ SWAR_QUOTE_BROADCAST;
        let is_quote: u64 = xq.wrapping_sub(SWAR_ONES_BROADCAST) & !xq & SWAR_HIGH_BITS;
        let xb: u64 = word ^ SWAR_BACKSLASH_BROADCAST;
        let is_bs: u64 = xb.wrapping_sub(SWAR_ONES_BROADCAST) & !xb & SWAR_HIGH_BITS;
        let mask: u64 = ((non_ascii | below_space) | is_del) | (is_quote | is_bs);
        if mask != 0 {
            let base: usize = idx * 8;
            for (j, &b) in chunk.iter().enumerate() {
                if b < 0x20 || b == ASCII_QUOTE || b == ASCII_BACKSLASH || b == 0x7f {
                    return Some(base + j);
                }
            }
        }
    }
    let base: usize = chunks.len() * 8;
    for (j, &b) in rem.iter().enumerate() {
        if b < 0x20 || b == ASCII_QUOTE || b == ASCII_BACKSLASH || b == 0x7f {
            return Some(base + j);
        }
    }
    None
}

/// Appends sanitized plain-text characters from `input` starting at known unsafe byte index `start`.
///
/// # Arguments
///
/// - `&str` - Raw input text.
/// - `usize` - Byte offset of the first control character requiring replacement.
/// - `&mut String` - Destination buffer receiving sanitized text.
#[inline]
pub(crate) fn push_sanitized_plain_from(input: &str, start: usize, out: &mut String) {
    out.push_str(&input[..start]);
    let bytes: &[u8] = input.as_bytes();
    let len: usize = bytes.len();
    let mut safe_start: usize = start;
    let mut idx: usize = start;
    while idx < len {
        let b: u8 = bytes[idx];
        if b < 0x80 {
            if (b < 0x20 && b != b'\t') || b == 0x7f {
                if safe_start < idx {
                    out.push_str(&input[safe_start..idx]);
                }
                let esc: &str = match b {
                    b'\r' => ESCAPED_CR,
                    b'\n' => ESCAPED_LF,
                    0x1b => ESCAPED_ESC,
                    _ => " ",
                };
                out.push_str(esc);
                safe_start = idx + 1;
            }
            idx += 1;
        } else if let Some(ch) = input[idx..].chars().next() {
            let ch_len: usize = ch.len_utf8();
            if ch.is_control() {
                if safe_start < idx {
                    out.push_str(&input[safe_start..idx]);
                }
                out.push(' ');
                safe_start = idx + ch_len;
            }
            idx += ch_len;
        } else {
            break;
        }
    }
    if safe_start < len {
        out.push_str(&input[safe_start..]);
    }
}

/// Appends sanitized plain-text characters from `input` into `out` with zero-copy fast path for clean text.
///
/// # Arguments
///
/// - `&str` - Raw input text.
/// - `&mut String` - Destination buffer receiving sanitized text.
#[inline]
pub(crate) fn push_sanitized_plain(input: &str, out: &mut String) {
    let Some(start) = find_first_plain_unsafe(input.as_bytes()) else {
        out.push_str(input);
        return;
    };
    push_sanitized_plain_from(input, start, out);
}

/// Appends JSON-escaped and control-sanitized text from `input` into `out` with zero-copy fast path.
///
/// # Arguments
///
/// - `&str` - Raw text to embed inside a JSON string literal.
/// - `&mut String` - Destination buffer receiving escaped characters.
#[inline]
pub(crate) fn push_sanitized_json(input: &str, out: &mut String) {
    let bytes: &[u8] = input.as_bytes();
    let Some(start) = find_first_json_unsafe(bytes) else {
        out.push_str(input);
        return;
    };
    out.push_str(&input[..start]);
    let len: usize = bytes.len();
    let mut safe_start: usize = start;
    let mut idx: usize = start;
    while idx < len {
        let b: u8 = bytes[idx];
        if b < 0x80 {
            if b < 0x20 || b == ASCII_QUOTE || b == ASCII_BACKSLASH || b == 0x7f {
                if safe_start < idx {
                    out.push_str(&input[safe_start..idx]);
                }
                let esc: &str = match b {
                    ASCII_QUOTE => ESCAPED_QUOTE,
                    ASCII_BACKSLASH => ESCAPED_BACKSLASH,
                    b'\r' => ESCAPED_CR,
                    b'\n' => ESCAPED_LF,
                    b'\t' => ESCAPED_TAB,
                    0x1b => ESCAPED_ESC,
                    _ => " ",
                };
                out.push_str(esc);
                safe_start = idx + 1;
            }
            idx += 1;
        } else if let Some(ch) = input[idx..].chars().next() {
            let ch_len: usize = ch.len_utf8();
            if ch.is_control() {
                if safe_start < idx {
                    out.push_str(&input[safe_start..idx]);
                }
                out.push(' ');
                safe_start = idx + ch_len;
            }
            idx += ch_len;
        } else {
            break;
        }
    }
    if safe_start < len {
        out.push_str(&input[safe_start..]);
    }
}

/// Formats one [`Record`] directly into `out` without intermediate message allocations.
///
/// # Arguments
///
/// - `&Record<'_>` - Incoming log record.
/// - `LogFormat` - Output wire format.
/// - `&mut String` - Reusable destination line buffer.
#[inline]
pub(crate) fn format_log_record_into(record: &Record<'_>, format: LogFormat, out: &mut String) {
    match format {
        LogFormat::Plain => {
            out.push_str(plain_level_prefix(record.level()));
            if let Some(literal) = record.args().as_str() {
                push_sanitized_plain(literal, out);
            } else {
                let mut writer: PlainSanitizingWriter<'_> = PlainSanitizingWriter { out };
                let _: fmt::Result = fmt::write(&mut writer, *record.args());
            }
        }
        LogFormat::Json => {
            out.push_str(json_level_prefix(record.level()));
            push_sanitized_json(record.target(), out);
            out.push_str(JSON_SEP_MESSAGE);
            if let Some(literal) = record.args().as_str() {
                push_sanitized_json(literal, out);
            } else {
                let mut writer: JsonSanitizingWriter<'_> = JsonSanitizingWriter { out };
                let _: fmt::Result = fmt::write(&mut writer, *record.args());
            }
            out.push_str(JSON_SUFFIX);
        }
    }
}

/// Spawns the dedicated background buffered file writer thread.
///
/// # Arguments
///
/// - `File` - Opened append-mode log file handle.
/// - `usize` - Bounded channel capacity before backpressure drops records.
///
/// # Returns
///
/// - `Result<SyncSender<WriterCommand>, String>` - Non-blocking sender handle or spawn error.
pub(crate) fn spawn_file_writer(
    file: File,
    capacity: usize,
) -> Result<SyncSender<WriterCommand>, String> {
    let (tx, rx): (SyncSender<WriterCommand>, Receiver<WriterCommand>) =
        sync_channel(capacity.max(1));
    let _: JoinHandle<()> = Builder::new()
        .name(LOGGER_WRITER_THREAD_NAME.to_owned())
        .spawn(move || {
            let mut writer: BufWriter<File> =
                BufWriter::with_capacity(LOGGER_FILE_BUFFER_BYTES, file);
            while let Ok(cmd) = rx.recv() {
                match cmd {
                    WriterCommand::Line(line) => {
                        let _: io::Result<()> = writer.write_all(line.as_bytes());
                        let _: io::Result<()> = writer.write_all(b"\n");
                        while let Ok(next_cmd) = rx.try_recv() {
                            match next_cmd {
                                WriterCommand::Line(next_line) => {
                                    let _: io::Result<()> = writer.write_all(next_line.as_bytes());
                                    let _: io::Result<()> = writer.write_all(b"\n");
                                }
                                WriterCommand::Flush(ack) => {
                                    let _: io::Result<()> = writer.flush();
                                    let _: Result<(), TrySendError<()>> = ack.try_send(());
                                }
                            }
                        }
                        let _: io::Result<()> = writer.flush();
                    }
                    WriterCommand::Flush(ack) => {
                        let _: io::Result<()> = writer.flush();
                        let _: Result<(), TrySendError<()>> = ack.try_send(());
                    }
                }
            }
            let _: io::Result<()> = writer.flush();
        })
        .map_err(|err: io::Error| format!("failed to spawn logger writer thread: {err}"))?;
    Ok(tx)
}