mariadb-cli 0.1.1

One-shot agent-native command line client for MariaDB servers
Documentation
//! The eight commands that report what the server is doing.
//!
//! This file only routes. Every rule, every refusal and every shape lives in
//! [`crate::serverinfo`], where it can be proved without a server.
//!
//! The whole family stays on the published surface whatever the credential can
//! see, so the command tree is the same against every destination. A
//! credential without the right to observe other connections learns that when
//! it asks, from a permission failure that names the right it needs.
//!
//! The one thing that can withdraw the two observing commands is the host
//! itself, from `server.observability_visible`, and it withdraws them for
//! every credential at once rather than for the ones that cannot use them.

use crate::cli::server::{KillArgs, ServerCommand};
use crate::conn::session::Session;
use crate::error::{Failure, Result};
use crate::output::Envelope;
use crate::serverinfo::{
    capabilities, kill, locks, processes, queries, replica, status, variables, ServerSettings,
};
use tokio_util::sync::CancellationToken;

/// Serves one server command.
///
/// # Errors
///
/// Returns a permission failure when the credential may not observe what was
/// asked, a validation failure when a destructive request lacks its
/// confirmation, an absence failure when the object asked about does not
/// exist, and the mapped driver failure for any other server condition.
pub async fn execute(
    command: &ServerCommand,
    session: &mut Session,
    settings: &ServerSettings,
    token: &CancellationToken,
) -> Result<Envelope> {
    // The facts were read once when the connection opened, so they are copied
    // out before the connection is borrowed for the work.
    let facts = session.facts().clone();
    let connection = session.connection();

    match command {
        ServerCommand::Status(args) => status::run(connection, args, settings, token).await,
        ServerCommand::Variables(args) => variables::run(connection, args, settings).await,
        ServerCommand::Processes(args) => {
            processes::run(connection, args, facts.connection_id, settings).await
        }
        ServerCommand::Replica => replica::run(connection, settings).await,
        ServerCommand::Kill(args) => {
            named_connection(args)?;
            kill::run(connection, args, facts.connection_id, settings).await
        }
        ServerCommand::Capabilities => Ok(capabilities::run(&facts)),
        ServerCommand::Queries(args) => {
            offered("server queries", settings)?;
            queries::run(connection, args, facts.database.as_deref(), settings).await
        }
        ServerCommand::Locks => {
            offered("server locks", settings)?;
            locks::run(connection, settings).await
        }
    }
}

/// Refuses a command the host chose not to offer.
///
/// The two commands that observe other connections stay on the surface by
/// default whatever the credential can see, because a surface that changed
/// shape with the credential would leave a caller unable to tell a command
/// that does not exist from one it may not use. A host that would rather not
/// offer them at all withdraws them once, for every credential, and the
/// refusal says which setting withdrew them so the caller is never left
/// guessing whether the build is simply older.
///
/// # Errors
///
/// Returns a usage failure naming the command and the setting that withdrew
/// it.
pub fn offered(name: &'static str, settings: &ServerSettings) -> Result<()> {
    if settings.observability_visible {
        return Ok(());
    }
    Err(Failure::usage(
        "usage.command_withdrawn",
        format!("`{name}` is not offered by this host"),
    )
    .with_detail("detail", name)
    .with_hint("set server.observability_visible to true to offer it again"))
}

/// Demands the connection the argument layer is allowed to leave out.
///
/// # Errors
///
/// Returns a usage failure when no connection was named. The argument layer
/// accepts the command without one so that publishing the contract costs
/// nothing, and no server hands out a connection numbered zero, so that is what
/// absence looks like by the time the work is about to be done.
fn named_connection(args: &KillArgs) -> Result<u64> {
    if args.id == 0 {
        return Err(Failure::usage(
            "server.connection_missing",
            "ending work needs the connection whose work is to end",
        )
        .with_hint(
            "name one with --id, as in `server kill --id 42`; `server processes` lists them",
        ));
    }
    Ok(args.id)
}

#[cfg(test)]
mod tests {
    use crate::cli::server::ServerCommand;
    use crate::cli::Cli;
    use clap::Parser;

    fn parse(args: &[&str]) -> ServerCommand {
        let command_line: Vec<String> = std::iter::once("mariadb-cli")
            .chain(args.iter().copied())
            .map(ToOwned::to_owned)
            .collect();
        match Cli::try_parse_from(command_line)
            .expect("accepted form")
            .command
        {
            crate::cli::Command::Server(command) => command,
            other => panic!("expected a server command, got {other:?}"),
        }
    }

    /// The interval is a mark the caller may give, and its absence is what
    /// hands the decision to the stored setting rather than to a number
    /// written into the code.
    #[test]
    fn the_interval_comes_from_the_caller_or_from_the_stored_setting() {
        let ServerCommand::Status(args) = parse(&["server", "status", "--interval", "5"]) else {
            panic!("expected status");
        };
        assert_eq!(args.interval, Some(5));

        let ServerCommand::Status(args) = parse(&["server", "status"]) else {
            panic!("expected status");
        };
        assert_eq!(args.interval, None);
    }

    /// Ending work of another user needs its own mark, and that mark is off
    /// unless the caller writes it.
    #[test]
    fn the_mark_for_another_users_work_is_off_unless_written() {
        let ServerCommand::Kill(args) = parse(&["server", "kill", "--id", "4711"]) else {
            panic!("expected kill");
        };
        assert!(!args.kill_other);
        assert!(!args.query_only);

        let ServerCommand::Kill(args) = parse(&[
            "server",
            "kill",
            "--id",
            "4711",
            "--query-only",
            "--kill-other",
        ]) else {
            panic!("expected kill");
        };
        assert!(args.kill_other);
        assert!(args.query_only);
    }

    /// Publishing the contract must cost nothing, so the argument layer accepts
    /// the command with no connection named. That moves the requirement here,
    /// where ending work without saying whose work has to be refused with a
    /// code and told which flag carries it.
    #[test]
    fn ending_work_without_a_connection_is_refused_with_a_code() {
        let ServerCommand::Kill(args) = parse(&["server", "kill"]) else {
            panic!("expected kill");
        };
        let failure = super::named_connection(&args).expect_err("must refuse");

        assert_eq!(failure.code(), "server.connection_missing");
        assert_eq!(failure.exit_number().code(), 2);
        assert!(
            failure.hint().is_some_and(|hint| hint.contains("--id")),
            "the refusal names the flag that carries the connection"
        );

        let ServerCommand::Kill(named) = parse(&["server", "kill", "--id", "4711"]) else {
            panic!("expected kill");
        };
        assert_eq!(super::named_connection(&named).expect("named"), 4711);
    }

    /// The two commands that need a right on the server are on the surface
    /// with no argument at all, so they never disappear from the tree.
    #[test]
    fn the_observation_commands_are_always_on_the_surface() {
        assert!(matches!(parse(&["server", "locks"]), ServerCommand::Locks));
        assert!(matches!(
            parse(&["server", "queries"]),
            ServerCommand::Queries(_)
        ));
    }
}