mariadb-cli 0.1.1

One-shot agent-native command line client for MariaDB servers
Documentation
//! What the server is doing right now.
//!
//! The eight commands in this module stay on the published surface whatever
//! the credential can see. Nothing here probes the credential's rights when
//! the session opens: that would cost an extra round trip on every invocation
//! and would make the command tree differ between destinations, which would
//! destroy the one guarantee the surface map gives, that what is published is
//! what exists. A credential without the observation right is told so when it
//! asks, by a permission failure naming the right that is missing.

pub mod capabilities;
pub mod kill;
pub mod locks;
pub mod processes;
pub mod queries;
pub mod replica;
pub mod status;
pub mod variables;

use crate::conn::OrFailure;
use crate::error::{Category, Failure, Result};
use crate::output::Row;
use crate::types::value;
use indexmap::IndexMap;
use mysql_async::{Conn, Params, Row as DriverRow, Value as Wire};
use serde_json::Value;
use std::time::Duration;
use tokio_util::sync::CancellationToken;

/// The settings these commands need, resolved by the caller.
///
/// No ceiling, interval or count is written into this module: every one of
/// them arrives here already decided by a flag or by a stored setting, so the
/// answer can always say which number it used.
#[derive(Debug, Clone, Copy)]
pub struct ServerSettings {
    /// Seconds between the two counter readings, from `server.status_interval_secs`.
    pub status_interval_secs: u64,
    /// How many rows a ranking returns when the caller names no number.
    pub default_top: usize,
    /// Whether the caller confirmed a destructive operation.
    pub confirmed: bool,
    /// Whether the two commands that observe other connections are offered.
    ///
    /// They are, by default, whatever the credential can see: a surface that
    /// changed shape with the credential would destroy the one guarantee the
    /// surface map gives. A host that would rather not offer them at all says
    /// so once, for every credential, from `server.observability_visible`.
    pub observability_visible: bool,
    /// Whether ending another user's work needs its own mark on top of the
    /// ordinary confirmation.
    ///
    /// Taking away work that is not yours is a different act from taking away
    /// your own, and the person losing it never knew this tool ran. A host
    /// where that distinction is noise turns the extra mark off from
    /// `server.kill_foreign_requires_yes`; the ordinary confirmation stays
    /// required either way.
    pub kill_foreign_requires_yes: bool,
}

/// Runs one statement and shapes every cell through the published type map.
///
/// # Errors
///
/// Returns the mapped driver failure when the server refuses the statement,
/// and a limit failure when one cell exceeds the ceiling for raw content.
pub async fn fetch(connection: &mut Conn, sql: &str, params: Params) -> Result<Vec<Row>> {
    use mysql_async::prelude::Queryable;

    let raw: Vec<DriverRow> = connection.exec(sql, params).await.or_failure()?;
    raw.iter().map(shape).collect()
}

/// Turns one driver row into the ordered shape the output pipeline reads.
fn shape(row: &DriverRow) -> Result<Row> {
    let columns = row.columns();
    let mut shaped = Row::new();
    for (index, column) in columns.iter().enumerate() {
        let wire = row.as_ref(index).cloned().unwrap_or(Wire::NULL);
        shaped.insert(
            column.name_str().into_owned(),
            // Server status readings carry no byte column, so the published
            // output settings have nothing to apply to. See the note on
            // `Conversion::stable`.
            value::convert(&wire, column, &crate::types::Conversion::stable())?,
        );
    }
    Ok(shaped)
}

/// Borrows one cell by name, ignoring the case the server chose.
///
/// Column names differ in case and in wording between releases, so a lookup
/// that insisted on one spelling would break on the next server.
#[must_use]
pub fn cell<'row>(row: &'row Row, name: &str) -> Option<&'row Value> {
    row.iter()
        .find(|(key, _)| key.eq_ignore_ascii_case(name))
        .map(|(_, value)| value)
}

/// Borrows the first cell whose name appears in the candidate list.
#[must_use]
pub fn first_cell<'row>(row: &'row Row, names: &[&str]) -> Option<&'row Value> {
    names.iter().find_map(|name| cell(row, name))
}

/// Renders one cell as plain text, whatever shape it arrived in.
#[must_use]
pub fn text_of(value: Option<&Value>) -> String {
    match value {
        None | Some(Value::Null) => String::new(),
        Some(Value::String(text)) => text.clone(),
        Some(other) => other.to_string(),
    }
}

/// Reads one cell as a whole number, when it is one.
#[must_use]
pub fn number_of(value: Option<&Value>) -> Option<i64> {
    match value {
        Some(Value::Number(number)) => number.as_i64(),
        Some(Value::String(text)) => text.trim().parse().ok(),
        _ => None,
    }
}

/// Collapses a two column name and value listing into an ordered map.
///
/// The server's own order is kept, so the same server always produces the same
/// bytes.
#[must_use]
pub fn pairs(rows: &[Row]) -> IndexMap<String, String> {
    let mut collected = IndexMap::with_capacity(rows.len());
    for row in rows {
        let mut cells = row.values();
        let (name, value) = (cells.next(), cells.next());
        if let Some(Value::String(name)) = name {
            collected.insert(name.clone(), text_of(value));
        }
    }
    collected
}

/// The failure a credential without the observation right is told.
///
/// The right that is missing is named, because a caller told only that
/// something was refused has to guess which grant to ask for.
///
/// `subject` is the stable identifier of what was being observed rather than a
/// sentence about it, so the catalogue of the reader's language words it.
#[must_use]
pub fn missing_observation(privilege: &str, subject: &str) -> Failure {
    Failure::permission("permission.observation_denied", subject.to_owned())
        .with_detail("detail", subject.to_owned())
        .with_detail("privilege", privilege.to_owned())
        .with_hint(format!(
            "grant the {privilege} right to this credential, or use one that already has it"
        ))
}

/// Whether this failure means the credential lacks a right.
#[must_use]
pub fn is_permission(failure: &Failure) -> bool {
    failure.category() == Category::Permission
}

/// Renames a refusal to the right that was missing, and passes anything else on.
///
/// Every reading in this family that touches another connection's work has to
/// make this same distinction: a refusal means the credential lacks a grant and
/// the caller needs to be told which one, while anything else is the server's
/// own condition and must travel unchanged. The decision was written five
/// times — inlined in three readings and extracted under the same local name in
/// two more — with only the pair of words naming the grant differing between
/// them.
///
/// Five copies of one decision is five places to change when it changes, and
/// the fifth is the one that gets missed. It is stated once here, and what
/// actually differs between the readings is what they pass in.
#[must_use]
pub fn observation_failure(failure: Failure, privilege: &str, subject: &str) -> Failure {
    if is_permission(&failure) {
        return missing_observation(privilege, subject);
    }
    failure
}

/// Whether this failure means the structure asked for is not on this server.
///
/// The observation structures differ between releases, so a structure that is
/// simply absent is a declared gap rather than a failure.
#[must_use]
pub fn is_absent_structure(failure: &Failure) -> bool {
    failure.category() == Category::Absence || failure.category() == Category::Server
}

/// Waits the declared interval, or gives up when the caller stops the work.
///
/// A signal must never leave the process asleep, so the wait and the stop
/// signal race each other and the stop always wins.
///
/// # Errors
///
/// Returns an interrupted failure when the caller stopped the work before the
/// interval elapsed.
pub async fn wait_interval(seconds: u64, token: &CancellationToken) -> Result<()> {
    tokio::select! {
        () = token.cancelled() => Err(Failure::interrupted(
            "interrupted.during_interval",
            "the work was stopped while waiting between two readings",
        )
        .with_hint("run again once the destination is free")),
        () = tokio::time::sleep(Duration::from_secs(seconds)) => Ok(()),
    }
}

/// Whether a name matches a pattern in the server's own wildcard form.
///
/// `%` stands for any run of characters and `_` for exactly one. Matching
/// happens here rather than on the server so the caller's pattern never has to
/// be pasted into a statement.
#[must_use]
pub fn matches_pattern(pattern: &str, name: &str) -> bool {
    let subject: Vec<char> = name.to_lowercase().chars().collect();
    let wanted: Vec<char> = pattern.to_lowercase().chars().collect();
    let (mut at, mut want, mut star, mut resume) = (0_usize, 0_usize, None, 0_usize);

    while at < subject.len() {
        match wanted.get(want) {
            Some('%') => {
                star = Some(want);
                resume = at;
                want += 1;
            }
            Some('_') => {
                at += 1;
                want += 1;
            }
            Some(character) if *character == subject[at] => {
                at += 1;
                want += 1;
            }
            _ => match star {
                Some(position) => {
                    want = position + 1;
                    resume += 1;
                    at = resume;
                }
                None => return false,
            },
        }
    }
    wanted[want..].iter().all(|character| *character == '%')
}

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

    #[test]
    fn a_pattern_matches_the_way_the_server_would() {
        assert!(matches_pattern("max_%", "max_connections"));
        assert!(matches_pattern("%connections%", "Max_Connections"));
        assert!(matches_pattern(
            "innodb_buffer_pool_size",
            "innodb_buffer_pool_size"
        ));
        assert!(matches_pattern("max_connection_", "max_connections"));
        assert!(!matches_pattern("max_%", "min_connections"));
        assert!(!matches_pattern("absent_%", "max_connections"));
    }

    #[test]
    fn a_cell_is_found_whatever_case_the_server_chose() {
        let mut row = Row::new();
        row.insert("Seconds_Behind_Master".to_owned(), json!(2));
        assert_eq!(number_of(cell(&row, "seconds_behind_master")), Some(2));
        assert_eq!(
            number_of(first_cell(
                &row,
                &["Seconds_Behind_Source", "Seconds_Behind_Master"]
            )),
            Some(2)
        );
        assert!(cell(&row, "absent").is_none());
    }

    #[test]
    fn a_missing_right_names_the_right_that_is_missing() {
        let failure = missing_observation("PROCESS", "other-connections");
        assert!(is_permission(&failure));
        assert_eq!(failure.exit_number().code(), 7);
        assert!(failure.hint().is_some_and(|hint| hint.contains("PROCESS")));
    }

    #[tokio::test]
    async fn a_stopped_caller_never_leaves_the_process_asleep() {
        let token = CancellationToken::new();
        token.cancel();
        let failure = wait_interval(3600, &token)
            .await
            .expect_err("a stopped caller must not wait");
        assert_eq!(failure.category(), Category::Interrupted);
    }
}