mariadb-cli 0.1.1

One-shot agent-native command line client for MariaDB servers
Documentation
//! The single place that writes to the primary channel.
//!
//! Nothing outside this module touches the process output. A closed reader is
//! not an error of the work: it is the caller saying it has read enough.

use crate::error::{Failure, Result};
use std::io::Write;

/// Serialises an envelope and writes it as one line.
///
/// # Errors
///
/// Returns a limit failure when the reader closed the channel, so the caller
/// sees the published number for a broken pipe instead of a generic write
/// error.
pub fn write_line<W: Write>(writer: &mut W, value: &impl serde::Serialize) -> Result<()> {
    let text = serde_json::to_string(value).map_err(|error| {
        Failure::new(
            crate::error::Category::Server,
            "output.not_serialisable",
            "the answer could not be serialised",
        )
        .with_cause(error.to_string())
    })?;
    writeln!(writer, "{text}").map_err(|error| classify_write(&error))
}

/// Turns a write error into the published failure for a closed channel.
///
/// The decision itself lives in [`crate::output::format::classify`] and is read
/// from there rather than repeated. It was written out twice for most of this
/// product's life, and the two copies drifted: this one was corrected to give a
/// closed reader its own category, and the copy every shaped writer used was
/// not, so the same event answered with two different categories and two
/// different exit numbers depending on which path reached it.
fn classify_write(error: &std::io::Error) -> Failure {
    crate::output::format::classify(error)
}

/// The same mapping, reachable from the proof that the two doors agree.
///
/// Exists only so that agreement can be asserted rather than assumed. It was
/// assumed for as long as the mapping was written twice, and the two spellings
/// of it disagreed the whole time.
#[cfg(test)]
pub(crate) fn classify_for_proof(error: &std::io::Error) -> Failure {
    classify_write(error)
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::output::Envelope;
    use serde_json::json;

    #[test]
    fn an_envelope_writes_as_one_newline_terminated_line() {
        let envelope = Envelope::new("meta version", json!({"version": "0.1.0"}));
        let mut buffer = Vec::new();
        write_line(&mut buffer, &envelope).expect("writes");
        let text = String::from_utf8(buffer).expect("utf8");
        assert_eq!(text.matches('\n').count(), 1);
        assert!(text.ends_with('\n'));
    }

    #[test]
    fn a_closed_reader_carries_its_own_category_and_number() {
        struct ClosedReader;
        impl Write for ClosedReader {
            fn write(&mut self, _: &[u8]) -> std::io::Result<usize> {
                Err(std::io::Error::new(
                    std::io::ErrorKind::BrokenPipe,
                    "closed",
                ))
            }
            fn flush(&mut self) -> std::io::Result<()> {
                Ok(())
            }
        }
        let envelope = Envelope::new("query run", json!({"rows": []}));
        let failure = write_line(&mut ClosedReader, &envelope).expect_err("must fail");
        assert_eq!(failure.code(), "output.broken_pipe");
        // The category is what a caller branches on, and it has to be enough on
        // its own. Reading the code to tell a closed channel from a ceiling is
        // exactly what the thirteenth category removed.
        assert_eq!(failure.category(), crate::error::Category::ChannelClosed);
        assert_ne!(failure.category(), crate::error::Category::Limit);
        // And the ordinary mapping answers the published number, with no
        // special case anywhere on the way out.
        assert_eq!(failure.exit_number().code(), 141);
    }
}