mariadb-cli 0.1.1

One-shot agent-native command line client for MariaDB servers
Documentation
//! Serialising a failure onto the auxiliary channel.
//!
//! A failure never reaches the primary channel: that channel carries data only.
//! The shape below is stable and is what a caller parses to decide its next
//! step.

use super::Failure;
use crate::i18n::Messages;
use serde::Serialize;
use std::borrow::Cow;

/// The wire shape of a failure, nested under a single `error` key.
#[derive(Debug, Serialize)]
pub struct FailureEnvelope<'a> {
    error: FailureBody<'a>,
}

/// The fields of a failure as emitted.
///
/// Optional fields are omitted rather than emitted as an empty value, so the
/// caller never has to tell "absent" from "present but null".
#[derive(Debug, Serialize)]
struct FailureBody<'a> {
    /// One of the thirteen published categories.
    category: &'static str,
    /// Stable identifier, safe to branch on.
    code: &'static str,
    /// Human prose; never used as an identifier.
    message: Cow<'a, str>,
    /// Concrete next action, when one exists.
    #[serde(skip_serializing_if = "Option::is_none")]
    hint: Option<Cow<'a, str>>,
    /// Whether repeating may succeed without changing the input.
    retryable: bool,
    /// The exit number this failure produces.
    exit: u8,
    /// Cause chain, outermost first: diagnosis only, never branched on.
    ///
    /// Each entry is the sentence some other library wrote — the argument
    /// parser, the driver, the encryption layer — carried through untouched.
    /// So it is the one field that stays in the language of its origin while
    /// `message` and `hint` follow the reader, and the one field whose text is
    /// not this product's to keep stable. A caller that branches on it is
    /// branching on a dependency's prose.
    #[serde(skip_serializing_if = "<[String]>::is_empty")]
    causes: &'a [String],
    /// Server conditions beyond the first.
    #[serde(skip_serializing_if = "<[String]>::is_empty")]
    conditions: &'a [String],
}

impl<'a> FailureEnvelope<'a> {
    /// Wraps a failure in its wire shape, in the language the source wrote it.
    #[must_use]
    pub fn new(failure: &'a Failure) -> Self {
        Self::localised(failure, None)
    }

    /// Wraps a failure in its wire shape, in the language of the reader.
    ///
    /// Only `message` and `hint` change with the language, because they are
    /// prose written for a person. `code`, `category`, `exit`, `retryable` and
    /// `conditions` are what a caller branches on, so they read the same on
    /// every host.
    ///
    /// `causes` also reads the same on every host, and for the opposite reason:
    /// it is not this product's prose to translate. It is a dependency's own
    /// sentence, kept verbatim for diagnosis, and calling it something a caller
    /// branches on — as this comment did — invited exactly the branch that
    /// breaks the day a dependency rewords itself.
    ///
    /// A code the messages do not name keeps the sentence the source built,
    /// because a missing translation must never cost the reader a diagnosis.
    #[must_use]
    pub fn localised(failure: &'a Failure, messages: Option<&Messages>) -> Self {
        let details = failure.details();
        let message = messages
            .and_then(|carried| carried.failure_message(failure.code(), details))
            .map_or(Cow::Borrowed(failure.message()), Cow::Owned);
        let hint = failure.hint().map(|hint| {
            messages
                .and_then(|carried| carried.failure_hint(failure.code(), details))
                .map_or(Cow::Borrowed(hint), Cow::Owned)
        });

        Self {
            error: FailureBody {
                category: failure.category().as_str(),
                code: failure.code(),
                message,
                hint,
                retryable: failure.is_retryable(),
                exit: failure.exit_number().code(),
                causes: failure.causes(),
                conditions: failure.extra_conditions(),
            },
        }
    }
}

/// Writes a failure to the auxiliary channel as one compact line.
///
/// The language is the one settled for this invocation, read from the process
/// rather than passed in: a failure is raised wherever it is discovered, and
/// carrying a translation argument down every call path so that the deepest one
/// could report itself would put translation on functions that have nothing to
/// do with it. A failure raised before the language was settled is served by
/// the host's own language rather than by none.
///
/// # Errors
///
/// Returns the underlying write error. A failure to report a failure is not
/// retried and not escalated: the exit number still carries the outcome.
pub fn write_failure<W: std::io::Write>(writer: &mut W, failure: &Failure) -> std::io::Result<()> {
    let messages = crate::i18n::active();
    write_failure_localised(writer, failure, Some(messages.as_ref()))
}

/// Writes a failure to the auxiliary channel in the language of the reader.
///
/// The messages are optional because a failure may be reported before the
/// language of the invocation has been settled, and a failure raised that
/// early still has to reach the caller.
///
/// # Errors
///
/// Returns the underlying write error. A failure to report a failure is not
/// retried and not escalated: the exit number still carries the outcome.
pub fn write_failure_localised<W: std::io::Write>(
    writer: &mut W,
    failure: &Failure,
    messages: Option<&Messages>,
) -> std::io::Result<()> {
    let envelope = FailureEnvelope::localised(failure, messages);
    // Serialisation of this shape cannot fail: every field is a plain scalar or
    // a string slice. Falling back to the message keeps the caller informed if
    // that assumption is ever broken.
    match serde_json::to_string(&envelope) {
        Ok(line) => writeln!(writer, "{line}"),
        Err(_) => writeln!(writer, r#"{{"error":{{"code":"{}"}}}}"#, failure.code()),
    }
}

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

    #[test]
    fn absent_fields_are_omitted_rather_than_emitted_empty() {
        let failure = Failure::usage("usage.unknown_value", "value out of domain");
        let line = serde_json::to_string(&FailureEnvelope::new(&failure)).expect("serialises");
        assert!(
            !line.contains("hint"),
            "absent hint must not appear: {line}"
        );
        assert!(!line.contains("causes"), "empty causes must not appear");
        assert!(
            !line.contains("conditions"),
            "empty conditions must not appear"
        );
    }

    #[test]
    fn every_failure_carries_the_mandatory_fields() {
        let failure = Failure::new(Category::Conflict, "conflict.deadlock", "deadlock found")
            .with_hint("repeat the transaction");
        let line = serde_json::to_string(&FailureEnvelope::new(&failure)).expect("serialises");
        for field in ["category", "code", "message", "retryable", "exit", "hint"] {
            assert!(line.contains(field), "missing {field} in {line}");
        }
        assert!(line.contains(r#""retryable":true"#));
        assert!(line.contains(r#""exit":9"#));
    }

    #[test]
    fn the_written_line_is_valid_and_newline_terminated() {
        let failure = Failure::absence("absence.table", "table not found");
        let mut buffer = Vec::new();
        write_failure(&mut buffer, &failure).expect("writes");
        let text = String::from_utf8(buffer).expect("utf8");
        assert!(text.ends_with('\n'));
        let parsed: serde_json::Value = serde_json::from_str(text.trim_end()).expect("valid json");
        assert_eq!(parsed["error"]["category"], "absence");
        assert_eq!(parsed["error"]["exit"], 8);
    }

    /// Writes one failure in one language and reads the wire shape back.
    fn written(failure: &Failure, tag: &str) -> serde_json::Value {
        let language = crate::i18n::negotiate::parse(tag).expect("a language");
        let messages = crate::i18n::Messages::load(language).expect("carried by this build");
        let mut buffer = Vec::new();
        write_failure_localised(&mut buffer, failure, Some(&messages)).expect("writes");
        let text = String::from_utf8(buffer).expect("utf8");
        serde_json::from_str(text.trim_end()).expect("valid json")
    }

    /// The reader's language decides the prose and nothing else: a caller that
    /// branches on the code, the category or the exit number reads the same
    /// answer on every host.
    #[test]
    fn the_language_changes_the_prose_and_never_the_identifiers() {
        let failure = Failure::validation(
            "sql.multiple_statements",
            "the text carries more than one statement",
        )
        .with_hint("send one statement per call");
        let english = written(&failure, "en");
        let portuguese = written(&failure, "pt-BR");

        assert_ne!(english["error"]["message"], portuguese["error"]["message"]);
        assert_ne!(english["error"]["hint"], portuguese["error"]["hint"]);
        for field in ["code", "category", "exit", "retryable"] {
            assert_eq!(
                english["error"][field], portuguese["error"][field],
                "`{field}` must not change with the language"
            );
        }
    }

    /// A code no catalogue names still reports, in the words the source built.
    #[test]
    fn an_untranslated_code_never_costs_the_reader_a_diagnosis() {
        let failure = Failure::server("server.condition", "column `b` has no default");
        let portuguese = written(&failure, "pt-BR");
        assert_eq!(portuguese["error"]["message"], "column `b` has no default");
        assert_eq!(portuguese["error"]["code"], "server.condition");
    }
}