mariadb-cli 0.1.1

One-shot agent-native command line client for MariaDB servers
Documentation
//! Asking the server to stop work this process has given up on.
//!
//! # Why a second connection
//!
//! The connection that is waiting for an answer cannot carry the ask to stop
//! waiting: it is busy. So the ask needs a connection of its own. Opening one on
//! every invocation would double the sessions this product creates for the sake
//! of a case that usually never happens, so the second connection is opened at
//! the moment the budget runs out and closed before the answer is reported.
//!
//! # Why this is the second line and not the first
//!
//! The server is asked, at connection time, to stop any statement that outruns
//! the budget on its own. That covers nearly everything and costs nothing. What
//! it does not cover is work running inside a stored routine, which the server's
//! own limit leaves alone. This is what covers the rest.

use super::options::ConnectionSettings;
use super::profile::Profile;
use super::OrFailure;
use crate::error::Result;
use crate::runtime::timeout::{AbortFuture, AbortOutcome, ServerAbort};
use mysql_async::prelude::Queryable;
use mysql_async::{Conn, Opts};

/// The server condition for a thread that is no longer there.
///
/// Work that finished between giving up and asking is work that stopped, so
/// this condition confirms the outcome rather than reporting a failure.
const UNKNOWN_THREAD: u16 = 1094;

/// Opens one connection, asks the server to stop a statement, and closes.
///
/// Built from the same destination the busy connection uses, so the ask reaches
/// the server the work is running on and never a different one.
#[derive(Debug, Clone)]
pub struct SecondConnection {
    options: Opts,
}

impl SecondConnection {
    /// Prepares the ask without opening anything.
    ///
    /// Nothing reaches the network here. A caller whose budget never runs out
    /// pays only for building these options.
    ///
    /// # Errors
    ///
    /// Returns a configuration failure when the destination cannot be turned
    /// into driver options.
    pub fn prepare(profile: &Profile, settings: &ConnectionSettings) -> Result<Self> {
        // The block that refuses change would refuse nothing here and would
        // leave a transaction open on a connection whose only job is one
        // administrative statement.
        let mut plain = settings.clone();
        plain.refuse_change = false;
        plain.statement_budget = None;
        Ok(Self {
            options: super::options::build(profile, &plain)?,
        })
    }

    /// Sends the ask, reads what became of it, and tells the reader either way.
    ///
    /// The reader is told the outcome even when the round trip failed, because
    /// an ask that never arrived leaves work running on the server and that is
    /// the one case a person has to act on.
    async fn ask(&self, session: u64) -> Result<AbortOutcome> {
        crate::i18n::report::budget_abort_requested();
        let asked = self.round_trip(session).await;
        match &asked {
            Ok(AbortOutcome::Confirmed) => crate::i18n::report::budget_abort_confirmed(),
            Ok(AbortOutcome::NotReached) | Err(_) => {
                crate::i18n::report::budget_abort_unconfirmed();
            }
        }
        asked
    }

    /// Opens the second connection, asks, confirms, and closes.
    async fn round_trip(&self, session: u64) -> Result<AbortOutcome> {
        // The other of the two openings: this second connection is being made
        // now, so bytes that never arrive mean it never opened.
        let mut conn = Conn::new(self.options.clone())
            .await
            .map_err(|failed| super::map_driver_error_in(super::Channel::Opening, &failed))?;

        let outcome = stop(&mut conn, session).await;

        // The second connection is closed whatever the outcome, so an ask that
        // failed never leaves a session behind on the server.
        let closed = conn.disconnect().await;
        let outcome = outcome?;
        closed.or_failure()?;
        Ok(outcome)
    }
}

/// Asks the server to stop the statement of one session, and confirms it.
///
/// The statement is named rather than the session, so the connection itself
/// survives: killing the connection would be a heavier act than the caller
/// asked for, and would lose whatever the session still holds.
async fn stop(conn: &mut Conn, session: u64) -> Result<AbortOutcome> {
    match conn.query_drop(format!("KILL QUERY {session}")).await {
        Ok(()) => confirm(conn, session).await,
        Err(error) => {
            if is_unknown_thread(&error) {
                return Ok(AbortOutcome::Confirmed);
            }
            Err(super::map_driver_error(&error))
        }
    }
}

/// Reads back whether the statement really stopped.
///
/// The ask is accepted asynchronously, so accepting it is not the same as it
/// having taken effect. A caller that must not leave heavy work behind needs
/// the difference, and guessing would be the one answer worse than either.
async fn confirm(conn: &mut Conn, session: u64) -> Result<AbortOutcome> {
    let still_running: Option<u64> = conn
        .exec_first(
            "SELECT COUNT(*) FROM information_schema.PROCESSLIST \
             WHERE ID = ? AND COMMAND <> 'Sleep'",
            (session,),
        )
        .await
        .or_failure()?;

    // An unreadable process list is not a confirmation. Reporting one would
    // tell the caller the work stopped when nothing here knows that.
    Ok(match still_running {
        Some(0) => AbortOutcome::Confirmed,
        _ => AbortOutcome::NotReached,
    })
}

/// Whether the server answered that the thread is no longer there.
fn is_unknown_thread(error: &mysql_async::Error) -> bool {
    matches!(error, mysql_async::Error::Server(condition) if condition.code == UNKNOWN_THREAD)
}

impl ServerAbort for SecondConnection {
    fn abort(&self, session: u64) -> AbortFuture<'_> {
        Box::pin(self.ask(session))
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::conn::tls::Verification;
    use std::collections::HashMap;

    fn settings() -> ConnectionSettings {
        ConnectionSettings {
            secret: None,
            default_port: 3306,
            prefer_socket: true,
            compress: false,
            max_allowed_packet: None,
            wait_timeout: None,
            tcp_keepalive: None,
            stmt_cache_size: 1,
            count_matched_rows: false,
            verification: Verification::default(),
            encryption: crate::conn::tls::Encryption::default(),
            timezone: None,
            charset: None,
            session_setup: Vec::new(),
            local_file_read: false,
            readable_local_files: Vec::new(),
            connect_attributes: HashMap::new(),
            refuse_change: true,
            statement_budget: Some(std::time::Duration::from_secs(5)),
        }
    }

    fn profile() -> Profile {
        Profile {
            host: Some("db.example".to_owned()),
            user: Some("reader".to_owned()),
            ..Profile::named("main")
        }
    }

    /// Preparing must reach nothing: an invocation that never runs out of time
    /// must not pay for a connection it never uses.
    #[test]
    fn preparing_the_ask_opens_nothing() {
        SecondConnection::prepare(&profile(), &settings()).expect("prepares");
    }

    /// The connection that carries the ask must not inherit the read-only
    /// block, or it would sit inside a transaction it has no use for.
    #[test]
    fn the_second_connection_carries_no_block_and_no_budget() {
        let prepared = SecondConnection::prepare(&profile(), &settings()).expect("prepares");
        let setup = prepared.options.setup();
        assert!(!setup
            .iter()
            .any(|line| line == crate::conn::options::READ_ONLY_BLOCK));
        assert!(!setup.iter().any(|line| line.contains("max_statement_time")));
    }

    /// The ask reaches the same destination as the work it is about.
    #[test]
    fn the_ask_reaches_the_destination_of_the_work() {
        let prepared = SecondConnection::prepare(&profile(), &settings()).expect("prepares");
        assert_eq!(prepared.options.ip_or_hostname(), "db.example");
        assert_eq!(prepared.options.user(), Some("reader"));
    }

    /// A destination naming no server is refused while nothing is open.
    #[test]
    fn a_destination_naming_no_server_is_refused_before_anything_opens() {
        let failure = SecondConnection::prepare(&Profile::named("empty"), &settings())
            .expect_err("must refuse");
        assert_eq!(failure.code(), "profile.no_destination");
    }

    /// Work that ended between giving up and asking is work that stopped, so
    /// the caller must be told it stopped rather than told the ask failed.
    #[test]
    fn a_thread_that_is_already_gone_confirms_the_outcome() {
        let gone = mysql_async::Error::Server(mysql_async::ServerError {
            code: UNKNOWN_THREAD,
            message: "Unknown thread id".to_owned(),
            state: "HY000".to_owned(),
        });
        assert!(is_unknown_thread(&gone));

        let other = mysql_async::Error::Server(mysql_async::ServerError {
            code: 1045,
            message: "Access denied".to_owned(),
            state: "28000".to_owned(),
        });
        assert!(!is_unknown_thread(&other));
    }
}