mariadb-cli 0.1.1

One-shot agent-native command line client for MariaDB servers
Documentation
//! Reaching the destination, and running the work the session serves.

use super::{context, flow, Work};
use crate::cli::{Cli, Command};
use crate::commands;
use crate::config::vault::FileVault;
use crate::config::Config;
use crate::conn::profile::{Profile, SecretRef};
use crate::conn::{options, session::Session, store::ProfileStore, ConnectionSettings};
use crate::error::Result;
use crate::output::Envelope;
use crate::runtime::timeout::{self, Phase};
use crate::runtime::Backoff;

/// Resolves the destination and everything the connection layer needs for it.
pub(super) fn destination(
    cli: &Cli,
    config: &Config,
    store: &ProfileStore,
    vault: &FileVault,
) -> Result<(Profile, ConnectionSettings)> {
    let (profile, secret) = context::destination(config, cli, store, vault)?;
    let profile = targeted(profile, cli);
    let settings = context::connection(config, cli, Some(&profile), secret)?;
    Ok((profile, settings))
}

/// The destination with the database this invocation names pinned onto it.
///
/// The database has to be pinned here, on the destination itself, because the
/// session is opened from it: a bare name inside the caller's own statement is
/// resolved by the server against the database the session was born in, and
/// nothing later can move it. Pinning it only as the scope the commands fall
/// back to left a listing looking right while a statement beside it read — and
/// would write — in the destination's own database instead.
///
/// A destination that fixed its own database is left alone here, so its pinned
/// name survives to be quoted in the refusal [`open`] raises. Overwriting it
/// first and refusing afterwards would leave the refusal naming the database
/// the caller passed twice, and the one it was supposed to protect nowhere.
pub(super) fn targeted(mut profile: Profile, cli: &Cli) -> Profile {
    if profile.pin_database {
        return profile;
    }
    if let Some(database) = cli.globals.destination.database.clone() {
        profile.database = Some(database);
    }
    profile
}

/// The destination this invocation reached, and how it was chosen.
///
/// Written once and read from both ends of the answer. The whole-answer path
/// hangs it on the envelope it returns; a continuous flow has no envelope, so it
/// puts the same value in the record that closes the flow (FR-143). Two ways of
/// building this would be two ways of describing one destination, and the one
/// that got forgotten would be the one nobody was reading.
pub(super) fn declared_target(profile: &Profile, cli: &Cli) -> crate::output::envelope::Target {
    crate::output::envelope::Target {
        profile: (cli.globals.destination.dsn.is_none()).then(|| profile.name.clone()),
        host: profile.host.clone(),
        port: profile.port,
        socket: profile
            .socket
            .as_ref()
            .map(|path| path.to_string_lossy().into_owned()),
        database: cli
            .globals
            .destination
            .database
            .clone()
            .or_else(|| profile.database.clone()),
    }
}

/// Serves profile management, which performs its own connection or none.
pub(super) async fn profiles(
    cli: &Cli,
    config: &Config,
    command: &crate::cli::conn::ConnCommand,
    store: &mut ProfileStore,
    vault: &mut FileVault,
) -> Result<Option<Envelope>> {
    // The check performs its own connection, and needs the secret of the
    // destination it is about to reach.
    let under_test = match command {
        crate::cli::conn::ConnCommand::Test(args) => store
            .resolve(
                args.name
                    .as_deref()
                    .or(cli.globals.destination.profile.as_deref()),
                context::stored_default(config)?.as_deref(),
            )
            .ok()
            .cloned(),
        _ => None,
    };
    let secret = match &under_test {
        Some(profile) => {
            crate::conn::profile::SecretVault::load(vault, &SecretRef::for_profile(&profile.name))?
        }
        None => None,
    };
    let settings = context::connection(config, cli, under_test.as_ref(), secret)?;
    commands::conn::execute(command, config, cli, store, vault, &settings)
        .await
        .map(Some)
}

/// Reaches the server, within the budget and repeating while that may help.
///
/// The driver has no option of its own for how long reaching the server may
/// take, so the budget can only be applied from here.
///
/// The pinned database is checked here rather than beside the override it
/// refuses, because this is the one point both the single destination and the
/// run across every destination pass through: put at the override, the refusal
/// would have to be written twice, and the second copy is the one that gets
/// forgotten.
/// # What the auxiliary channel is told, and why here
///
/// Reaching the destination is timed from here and declared on the auxiliary
/// channel apart from the time the command then takes (FR-138). This is the
/// only place that can measure it: the budget, the repetitions and the waits
/// between them all live inside this call, so a reading taken outside it would
/// be the cost of the whole invocation with the two halves already added
/// together — which is exactly the number that tells a caller nothing about
/// whether to make one large invocation or several small ones.
///
/// The reading is taken before the outcome is inspected, so an opening that
/// never succeeded still declares what it cost. Measuring after the `?` would
/// have declared the cost on every path except the expensive one.
pub(super) async fn open(
    profile: &Profile,
    settings: &ConnectionSettings,
    cli: &Cli,
    config: &Config,
    token: &tokio_util::sync::CancellationToken,
) -> Result<Session> {
    profile.ensure_accepts_a_named_database(cli.globals.destination.database.as_deref())?;
    let options = options::build(profile, settings)?;
    let budget = crate::settings::connect_timeout(config, &cli.globals)?;
    let policy: Backoff = crate::settings::retry_policy(config, &cli.globals)?;

    crate::i18n::report::channel_opening(&profile.name);
    let reaching = std::time::Instant::now();
    let opened = crate::runtime::retry(&policy, token, move |_attempt| {
        let options = options.clone();
        async move { timeout::within(Phase::Connect, budget, Session::open(options)).await }
    })
    .await;
    let cost = reaching.elapsed().as_millis();

    match &opened {
        Ok(session) => crate::i18n::report::channel_opened(&session.facts().version, cost),
        Err(_) => crate::i18n::report::channel_open_failed(cost),
    }
    opened
}

/// Runs the work under the time budget, asking the server to stop if it runs out.
///
/// The server was already asked, as the connection opened, to stop any
/// statement that outruns the budget on its own. This covers what that cannot
/// reach, which is work running inside a stored routine.
///
/// This is also where the command's own time is measured, because the session
/// is already open when this is entered and is closed before it returns: what
/// elapses between the two is the command and nothing else. Declared apart
/// from the time reaching the destination took, so the two can be compared
/// rather than only summed (FR-138). It is declared whichever way the command
/// went, since a command that failed still spent the time it spent.
pub(super) async fn bounded<W: std::io::Write>(
    work: &Work<'_>,
    mut session: Session,
    profile: &Profile,
    settings: &ConnectionSettings,
    out: &mut W,
) -> Result<Option<Envelope>> {
    let budget = crate::settings::operation_timeout(work.config, &work.cli.globals)?;
    let aborter = crate::conn::SecondConnection::prepare(profile, settings)?;
    let named = u64::from(session.connection().id());

    let running = std::time::Instant::now();
    // The signal reaches the server through the same second connection the
    // budget uses. An invocation waiting on the destination has no local loop to
    // watch the marker with, so without this the caller's cancellation was seen
    // and then waited out (G-030).
    let stopping = work.shutdown.token();
    let outcome = timeout::within_aborting_or_stopped(
        Phase::Query,
        budget,
        named,
        &aborter,
        &stopping,
        on_session(work, session, profile, out),
    )
    .await;
    crate::i18n::report::channel_closing(running.elapsed().as_millis());
    outcome
}

/// Whether the work stopped because the reader shut the primary channel.
///
/// Asked of the category and never of the stable code, because the category is
/// what the product publishes for branching on and the code is free to gain
/// siblings. The thirteenth category exists so this question has an answer.
fn closed_by_the_reader<T>(outcome: &Result<T>) -> bool {
    matches!(outcome, Err(failure)
        if failure.category() == crate::error::Category::ChannelClosed)
}

/// Dispatches to the family that serves this command, then closes the session.
async fn on_session<W: std::io::Write>(
    work: &Work<'_>,
    mut session: Session,
    profile: &Profile,
    out: &mut W,
) -> Result<Option<Envelope>> {
    let (cli, config) = (work.cli, work.config);

    // A continuous flow writes as it reads, so it never builds an envelope.
    // Across destinations there is no single flow to write, so the whole-answer
    // path serves them all.
    if flow::applies(cli, config) && !work.many {
        let mut context = context::query_context(config, cli, work.shutdown.token())?;
        // The destination travels into the flow because a flow builds no
        // envelope to carry it, and the record that closes one still has to
        // declare where the rows came from (FR-143). It is read through the
        // same function the whole-answer path reads it through, so the two
        // paths can never describe one destination differently.
        let target = declared_target(profile, cli);
        let flowed = flow::run(cli, config, &mut session, &mut context, out, &target).await;
        if closed_by_the_reader(&flowed) {
            // Dropped rather than closed, and this is the correction of G-031.
            //
            // Closing politely means telling the driver to disconnect, and it
            // cannot disconnect until the result set still arriving has been
            // consumed. So a flow the reader walked away from went on pulling
            // every remaining row for nobody: measured, on a hundred thousand
            // rows, 30 651 ms against the 957 ms the same query costs when a
            // ceiling stops it. The cost was linear in the rows LEFT, which is
            // what named the cause.
            //
            // The channel being closed is exactly the case where the rest of
            // the set has no reader, so consuming it buys nothing. Dropping
            // shuts the socket, the server meets that on its very next write —
            // and it is mid-send, so that is immediate — and the work ends
            // there too. Measured: 495 ms, and the server has nothing left one
            // second later (FR-049).
            return flowed.map(|_| None);
        }
        return session.close_after(flowed).await.map(|_| None);
    }

    let outcome = match &cli.command {
        Command::Schema(command) => {
            let target = context::schema_target(config, cli, work.scope.clone())?;
            commands::schema::execute(command, &mut session, &target).await
        }
        Command::Query(command) => {
            let mut ctx = context::query_context(config, cli, work.shutdown.token())?;
            commands::query::execute(command, &mut session, &mut ctx).await
        }
        Command::Server(command) => {
            let settings = context::server_settings(config, cli)?;
            commands::server::execute(command, &mut session, &settings, &work.shutdown.token())
                .await
        }
        Command::History(command) => {
            commands::history::execute(
                command,
                &mut session,
                cli.globals.destination.database.as_deref(),
            )
            .await
        }
        Command::Data(command) => {
            let settings = context::data_settings(config, cli)?;
            commands::data::execute(command, &mut session, &settings, &work.shutdown.token()).await
        }
        // The unconnected families answered before this point.
        Command::Conn(_) | Command::Config(_) | Command::Meta(_) => {
            Err(commands::not_yet_served(&cli.command))
        }
    };

    // The connection is released before the answer leaves, so nothing survives
    // the invocation.
    session.close_after(outcome).await.map(Some)
}