mariadb-cli 0.1.1

One-shot agent-native command line client for MariaDB servers
Documentation
//! Reading a whole input without agreeing to hold whatever arrives.
//!
//! Three entry points used to take a file or the standard input into memory
//! with `read_to_string` and only then measure what they had read. Every
//! ceiling this product publishes applied AFTER that point: a statement was
//! checked against `limits.max_statement_bytes` once it was already resident,
//! so a two gigabyte file cost two gigabytes of memory before anything existed
//! to refuse it.
//!
//! The ceiling here is a different question from that one, which is why it is a
//! different key. `limits.max_statement_bytes` asks how large a single
//! statement may BE; `limits.max_input_bytes` asks how much this product will
//! READ before it has judged anything. A script of many small statements is
//! legitimate and its total is not a statement, so one number answering both
//! questions would have to refuse correct input to do its job.
//!
//! Refusal is a `Limit` failure, which is the same category and the same exit
//! number the product already uses for the volume ceiling on the way out. A
//! caller meeting a ceiling on the way in and a ceiling on the way out reads
//! one kind of answer, not two.

use crate::error::{Failure, Result};
use std::io::Read;
use std::path::Path;

/// The whole of a file, provided it is no larger than the ceiling.
///
/// The size is taken from the directory entry and not from the bytes, so a file
/// past the ceiling is refused without being read at all. That is the entire
/// point: measuring after reading would have already paid the cost the ceiling
/// exists to avoid.
///
/// # Errors
///
/// Returns a limit failure when the file is larger than the ceiling, and
/// `absence.file` when it cannot be read.
///
/// The code is written here rather than taken as a parameter. It was a
/// parameter for one draft, and two proofs refused that immediately: the scan
/// that pairs a catalogue frame with the call site supplying its `$detail`
/// works on the literal, so moving the literal to the caller broke the pairing
/// for `err-absence-file`. Each of these readers raises exactly one code, so the
/// parameter bought nothing and cost the pairing.
pub fn file_within(path: &Path, ceiling: usize) -> Result<String> {
    let unreadable = |cause: std::io::Error| {
        Failure::absence(
            "absence.file",
            format!("`{}` could not be read", path.display()),
        )
        .with_detail("detail", path.display().to_string())
        .with_cause(cause.to_string())
    };

    let size = std::fs::metadata(path).map_err(unreadable)?.len();
    if size > ceiling as u64 {
        return Err(too_much(size, ceiling));
    }

    std::fs::read_to_string(path).map_err(unreadable)
}

/// The whole of the standard input, provided it stops before the ceiling.
///
/// A stream has no size to ask for ahead of time, so it is read through a
/// reader that stops one byte past the ceiling. Reading one more than is
/// allowed is what makes "exactly at the ceiling" and "over it" tell apart;
/// stopping AT the ceiling would silently truncate the input that just fits.
///
/// # Errors
///
/// Returns a limit failure when the stream carries more than the ceiling, and
/// `config.stdin_unreadable` when it cannot be read.
pub fn standard_input_within(ceiling: usize) -> Result<String> {
    let mut text = String::new();
    let read = std::io::stdin()
        .lock()
        .take(ceiling as u64 + 1)
        .read_to_string(&mut text)
        .map_err(|cause| {
            Failure::config(
                "config.stdin_unreadable",
                "the standard input could not be read",
            )
            .with_cause(cause.to_string())
        })?;

    if read > ceiling {
        return Err(too_much(read as u64, ceiling));
    }
    Ok(text)
}

/// The one refusal both readers raise, so both say the same thing.
///
/// The measured pair travels as `detail` because the catalogue frame names it,
/// and a frame naming a value nobody supplies shows the reader an empty
/// parenthesis.
fn too_much(size: u64, ceiling: usize) -> Failure {
    Failure::limit(
        "limit.input_bytes",
        format!("the input has {size} bytes and the reading ceiling is {ceiling}"),
    )
    .with_detail("detail", format!("{size} > {ceiling}"))
    .with_hint("read less, or raise limits.max_input_bytes")
}

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

    #[test]
    fn a_file_within_the_ceiling_is_read_whole() {
        let file = tempfile::NamedTempFile::new().expect("a temporary file");
        std::fs::write(file.path(), "select 1").expect("writes");

        let text = file_within(file.path(), 1024).expect("reads");
        assert_eq!(text, "select 1");
    }

    #[test]
    fn a_file_past_the_ceiling_is_refused_without_being_read() {
        let file = tempfile::NamedTempFile::new().expect("a temporary file");
        std::fs::write(file.path(), "select 1").expect("writes");

        let failure = file_within(file.path(), 3).expect_err("refuses");
        assert_eq!(failure.code(), "limit.input_bytes");
    }

    #[test]
    fn a_file_exactly_at_the_ceiling_is_still_read() {
        let file = tempfile::NamedTempFile::new().expect("a temporary file");
        std::fs::write(file.path(), "select 1").expect("writes");

        let text = file_within(file.path(), 8).expect("reads");
        assert_eq!(text, "select 1");
    }

    #[test]
    fn the_refusal_names_the_key_that_raises_the_ceiling() {
        let failure = too_much(9, 8);
        assert_eq!(failure.code(), "limit.input_bytes");
        assert!(failure
            .hint()
            .is_some_and(|hint| hint.contains("limits.max_input_bytes")));
    }
}