mariadb-cli 0.1.1

One-shot agent-native command line client for MariaDB servers
Documentation
//! Whether this destination follows another server, and how far behind it is.
//!
//! This changes how every other reading must be understood. A destination that
//! trails another server by two seconds answers questions about the past, and
//! a caller who does not know that will read stale rows as current ones. So a
//! following destination always carries a warning, even when it is healthy.

use super::{fetch, first_cell, number_of, text_of, ServerSettings};
use crate::error::{Failure, Result};
use crate::output::{Envelope, Row};
use mysql_async::{Conn, Params};
use serde_json::{json, Value};

/// The wording newer releases use.
const MODERN: &str = "SHOW REPLICA STATUS";

/// The wording older releases use, kept because the product supports them.
const LEGACY: &str = "SHOW SLAVE STATUS";

/// The names one release or another gives to the seconds this copy trails by.
const LAG: [&str; 2] = ["Seconds_Behind_Master", "Seconds_Behind_Source"];

/// The names for the thread that receives changes.
const RECEIVING: [&str; 2] = ["Slave_IO_Running", "Replica_IO_Running"];

/// The names for the thread that applies changes.
const APPLYING: [&str; 2] = ["Slave_SQL_Running", "Replica_SQL_Running"];

/// The names for the position already applied.
const POSITION: [&str; 2] = ["Exec_Master_Log_Pos", "Exec_Source_Log_Pos"];

/// The names for the file that position belongs to.
const POSITION_FILE: [&str; 2] = ["Relay_Master_Log_File", "Relay_Source_Log_File"];

/// The names for the last condition the copy recorded.
const LAST_ERROR: [&str; 3] = ["Last_Error", "Last_SQL_Error", "Last_IO_Error"];

/// Reports whether this destination follows another server.
///
/// # Errors
///
/// Returns an absence failure when the destination follows nobody, so a
/// standalone server is told apart from a copy with empty fields, and the
/// mapped driver failure when neither wording can be read.
pub async fn run(connection: &mut Conn, _settings: &ServerSettings) -> Result<Envelope> {
    let rows = match fetch(connection, MODERN, Params::Empty).await {
        Ok(rows) => rows,
        Err(failure) if super::is_absent_structure(&failure) => {
            fetch(connection, LEGACY, Params::Empty).await?
        }
        Err(failure) => return Err(failure),
    };

    let row = rows.first().ok_or_else(standalone)?;
    Ok(Envelope::new("server replica", describe(row)))
}

/// The failure a destination that follows nobody produces.
fn standalone() -> Failure {
    Failure::absence(
        "absence.not_a_replica",
        "this destination follows no other server",
    )
    .with_hint("read the replica situation on the destination that does the following")
}

/// Shapes one situation row into the published answer.
///
/// A copy that is not applying changes, or that trails at all, gets a warning
/// of its own, so the caller never has to work the consequence out from the
/// numbers.
#[must_use]
pub fn describe(row: &Row) -> Value {
    let receiving = running(&text_of(first_cell(row, &RECEIVING)));
    let applying = running(&text_of(first_cell(row, &APPLYING)));
    let lag = number_of(first_cell(row, &LAG));
    let last_error = non_empty(text_of(first_cell(row, &LAST_ERROR)));

    json!({
        "following": true,
        "receiving": receiving,
        "applying": applying,
        "active": receiving && applying,
        "seconds_behind": lag,
        "applied_position": first_cell(row, &POSITION).cloned().unwrap_or(Value::Null),
        "applied_position_file": first_cell(row, &POSITION_FILE).cloned().unwrap_or(Value::Null),
        "last_error": last_error,
        "warning": warning(receiving && applying, lag, last_error.is_some()),
    })
}

/// Whether a thread the server describes in words is running.
fn running(state: &str) -> bool {
    state.eq_ignore_ascii_case("yes")
}

/// Drops an empty text, because an empty error is not an error.
fn non_empty(text: String) -> Option<String> {
    (!text.trim().is_empty()).then_some(text)
}

/// The warning this situation deserves.
#[must_use]
pub fn warning(active: bool, lag: Option<i64>, has_error: bool) -> String {
    if !active || has_error {
        return "this destination follows another server and is not applying changes, \
                so every reading here may be arbitrarily old"
            .to_owned();
    }
    match lag {
        Some(0) => "this destination follows another server and is caught up, \
                    so a reading may still miss a change made moments ago"
            .to_owned(),
        Some(seconds) => format!(
            "this destination follows another server and trails it by {seconds} seconds, \
             so every reading here is that old"
        ),
        None => "this destination follows another server and does not report how far \
                 behind it is, so the age of a reading here is unknown"
            .to_owned(),
    }
}

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

    fn situation(io: &str, sql: &str, lag: Value, error: &str) -> Row {
        let mut row = Row::new();
        row.insert("Slave_IO_Running".to_owned(), json!(io));
        row.insert("Slave_SQL_Running".to_owned(), json!(sql));
        row.insert("Seconds_Behind_Master".to_owned(), lag);
        row.insert("Exec_Master_Log_Pos".to_owned(), json!(4711));
        row.insert("Relay_Master_Log_File".to_owned(), json!("bin.000004"));
        row.insert("Last_Error".to_owned(), json!(error));
        row
    }

    /// A healthy copy that trails says how old its answers are, because that
    /// changes what every other reading means.
    #[test]
    fn a_trailing_copy_warns_about_the_age_of_its_answers() {
        let described = describe(&situation("Yes", "Yes", json!(2), ""));
        assert_eq!(described["active"], json!(true));
        assert_eq!(described["seconds_behind"], json!(2));
        assert_eq!(described["last_error"], Value::Null);
        assert!(text_of(Some(&described["warning"])).contains('2'));
    }

    /// A stopped copy warns that its answers may be arbitrarily old, which is
    /// worse than a known delay and must not read as healthy.
    #[test]
    fn a_stopped_copy_warns_that_its_answers_are_of_unknown_age() {
        let described = describe(&situation("Yes", "No", Value::Null, "duplicate key"));
        assert_eq!(described["active"], json!(false));
        assert_eq!(described["last_error"], json!("duplicate key"));
        assert!(text_of(Some(&described["warning"])).contains("arbitrarily old"));
    }

    /// A copy caught up still warns, because caught up is not the same as
    /// current.
    #[test]
    fn a_copy_caught_up_still_warns() {
        let described = describe(&situation("Yes", "Yes", json!(0), ""));
        assert!(!text_of(Some(&described["warning"])).is_empty());
    }

    /// The newer column names are read as readily as the older ones.
    #[test]
    fn either_generation_of_column_names_is_read() {
        let mut row = Row::new();
        row.insert("Replica_IO_Running".to_owned(), json!("Yes"));
        row.insert("Replica_SQL_Running".to_owned(), json!("Yes"));
        row.insert("Seconds_Behind_Source".to_owned(), json!(7));
        let described = describe(&row);
        assert_eq!(described["active"], json!(true));
        assert_eq!(described["seconds_behind"], json!(7));
    }

    /// A destination that follows nobody is an absence rather than a copy with
    /// empty fields.
    #[test]
    fn a_standalone_destination_is_an_absence() {
        assert_eq!(standalone().exit_number().code(), 8);
    }
}