pub mod context;
mod fanout;
pub mod flow;
mod open;
pub mod preflight;
use crate::cli::{Cli, Command};
use crate::commands;
use crate::config::vault::FileVault;
use crate::config::Config;
use crate::conn::store::ProfileStore;
use crate::error::{Failure, Result};
use crate::output::Envelope;
use crate::runtime::Shutdown;
struct Work<'a> {
cli: &'a Cli,
config: &'a Config,
shutdown: &'a Shutdown,
scope: Option<String>,
many: bool,
}
pub async fn serve<W: std::io::Write>(
cli: &Cli,
out: &mut W,
shutdown: &Shutdown,
) -> Result<Option<Envelope>> {
let config_dir = cli.globals.diagnostics.config_dir.as_deref();
let config = match Config::load(config_dir) {
Ok(config) => config,
Err(unreadable) if diagnoses_the_settings(&cli.command) => {
Config::with_nothing_stored(config_dir).map_err(|_| unreadable)?
}
Err(unreadable) => return Err(unreadable),
};
let permits = crate::settings::concurrency(&config, &cli.globals)?;
if let Some(answered) = unconnected(cli, &config, config_dir)? {
return Ok(Some(answered));
}
with_destination(cli, &config, permits, shutdown, out).await
}
pub(crate) fn diagnoses_the_settings(command: &Command) -> bool {
matches!(
command,
Command::Config(crate::cli::config::ConfigCommand::Doctor)
)
}
fn unconnected(
cli: &Cli,
config: &Config,
config_dir: Option<&std::path::Path>,
) -> Result<Option<Envelope>> {
if cli.globals.output.print_schema {
return contract(cli).map(Some);
}
match &cli.command {
Command::Meta(command) => return commands::meta::execute(command, cli).map(Some),
Command::Config(command) => {
return commands::config::execute(command, config_dir, cli.globals.safety.dry_run)
.map(Some)
}
Command::Query(command) => {
let context =
context::query_context(config, cli, tokio_util::sync::CancellationToken::new())?;
preflight::refuse_early(cli, config, &context)?;
if let Some(answered) = commands::query::execute_offline(command, &context) {
return answered.map(Some);
}
}
_ => {}
}
Ok(None)
}
fn contract(cli: &Cli) -> Result<Envelope> {
let asked = crate::cli::meta::MetaCommand::Schema(crate::cli::meta::SchemaArgs {
command: Some(cli.command.published_name().to_owned()),
types: false,
});
commands::meta::execute(&asked, cli)
}
pub fn build_runtime() -> Result<tokio::runtime::Runtime> {
tokio::runtime::Builder::new_current_thread()
.enable_all()
.build()
.map_err(|error| {
Failure::new(
crate::error::Category::Server,
"runtime.unavailable",
"the work runtime could not be started",
)
.with_cause(error.to_string())
})
}
pub async fn under_signals<T, F>(work: F) -> Result<T>
where
F: AsyncFnOnce(&Shutdown) -> Result<T>,
{
let shutdown = Shutdown::new();
let signals = shutdown.watch_signals();
let outcome = work(&shutdown).await;
tokio::task::yield_now().await;
let signalled = shutdown.reason();
shutdown.stop(crate::runtime::StopReason::Terminate);
let _ = signals.await;
under_signal(outcome, signalled)
}
fn under_signal<T>(outcome: Result<T>, signalled: Option<crate::runtime::StopReason>) -> Result<T> {
match (outcome, signalled) {
(Err(failure), _) => Err(failure),
(Ok(answer), None) => Ok(answer),
(Ok(_), Some(_)) => Err(Failure::interrupted(
"interrupted.by_caller",
"the invocation was stopped by the caller",
)),
}
}
async fn with_destination<W: std::io::Write>(
cli: &Cli,
config: &Config,
permits: usize,
shutdown: &Shutdown,
out: &mut W,
) -> Result<Option<Envelope>> {
let directory =
crate::config::paths::config_dir(cli.globals.diagnostics.config_dir.as_deref())?;
let mut store = ProfileStore::open(&directory)?;
let mut vault = FileVault::open_keeping(&directory, crate::settings::secret_storage(config)?)?;
if let Command::Conn(command) = &cli.command {
return open::profiles(cli, config, command, &mut store, &mut vault).await;
}
if cli.globals.destination.all_profiles {
return fanout::across_destinations(cli, config, permits, shutdown, &store, &vault)
.await
.map(Some);
}
let (profile, settings) = open::destination(cli, config, &store, &vault)?;
let target = open::declared_target(&profile, cli);
let session = open::open(&profile, &settings, cli, config, &shutdown.token()).await?;
let work = Work {
cli,
config,
scope: profile.database.clone(),
shutdown,
many: false,
};
open::bounded(&work, session, &profile, &settings, out)
.await
.map(|answer| {
answer
.map(|envelope| envelope.from_destination(target, cli.globals.destination.source()))
})
}
#[cfg(test)]
mod tests {
use super::*;
use clap::Parser;
fn parse(args: &[&str]) -> Cli {
let command_line: Vec<String> = std::iter::once("mariadb-cli")
.chain(args.iter().copied())
.map(ToOwned::to_owned)
.collect();
Cli::try_parse_from(command_line).expect("the sample invocation parses")
}
#[test]
fn an_answer_that_finished_under_a_signal_is_reported_as_the_interruption() {
let answered = under_signal(
Ok(Some(Envelope::new("query run", serde_json::json!({})))),
Some(crate::runtime::StopReason::Interrupt),
);
let failure = answered.expect_err("a signal arrived, so the answer is not the whole one");
assert_eq!(failure.category(), crate::error::Category::Interrupted);
assert_eq!(failure.exit_number().code(), 130);
}
#[test]
fn a_signal_that_arrives_during_the_work_reaches_the_answer() {
let runtime = build_runtime().expect("a runtime starts");
let answered: Result<Option<Envelope>> = runtime.block_on(under_signals(
async |shutdown: &crate::runtime::Shutdown| {
shutdown.stop(crate::runtime::StopReason::Interrupt);
Ok(Some(Envelope::new("meta version", serde_json::json!({}))))
},
));
let failure = answered.expect_err("the invocation was stopped while it worked");
assert_eq!(failure.exit_number().code(), 130);
}
#[test]
fn an_invocation_nobody_signalled_answers_normally() {
let runtime = build_runtime().expect("a runtime starts");
let answered: Result<Option<Envelope>> = runtime.block_on(under_signals(
async |_shutdown: &crate::runtime::Shutdown| {
Ok(Some(Envelope::new("meta version", serde_json::json!({}))))
},
));
assert!(answered.expect("nothing stopped this").is_some());
}
#[test]
fn an_answer_nobody_interrupted_is_the_answer() {
let answered = under_signal(
Ok(Some(Envelope::new("query run", serde_json::json!({})))),
None,
);
assert!(answered.expect("nothing stopped this").is_some());
}
#[test]
fn a_failure_of_its_own_survives_the_signal() {
let answered = under_signal::<Option<Envelope>>(
Err(Failure::usage("usage.invalid_arguments", "malformed")),
Some(crate::runtime::StopReason::Terminate),
);
let failure = answered.expect_err("the work failed");
assert_eq!(failure.code(), "usage.invalid_arguments");
}
fn scratch() -> (tempfile::TempDir, Config) {
let directory = tempfile::tempdir().expect("scratch directory");
let config = Config::load(Some(directory.path())).expect("loads");
(directory, config)
}
#[test]
fn the_contract_is_answered_without_reaching_a_server() {
let (directory, config) = scratch();
let cli = parse(&["--print-schema", "query", "run", "SELECT 1"]);
let answered = unconnected(&cli, &config, Some(directory.path()))
.expect("answers")
.expect("without a server");
assert_eq!(answered.data["command"], "query run");
}
#[test]
fn every_family_answers_its_own_contract_offline() {
let (directory, config) = scratch();
for command in [
vec!["schema", "tables"],
vec!["server", "status"],
vec!["data", "export", "--table", "t"],
vec!["history", "tables"],
vec!["conn", "list"],
] {
let argv: Vec<&str> = std::iter::once("--print-schema").chain(command).collect();
let cli = parse(&argv);
assert!(
unconnected(&cli, &config, Some(directory.path()))
.expect("answers")
.is_some(),
"`{argv:?}` must answer its contract without a server"
);
}
}
#[test]
fn tracing_a_column_to_its_source_costs_no_connection() {
let (directory, config) = scratch();
let cli = parse(&["query", "lineage", "SELECT p.a FROM t AS p"]);
let answered = unconnected(&cli, &config, Some(directory.path()))
.expect("answers")
.expect("without a server");
assert_eq!(answered.command, "query lineage");
assert_eq!(answered.data["rows"][0]["sources"][0]["table"], "t");
}
#[test]
fn the_statement_catalogue_costs_no_connection() {
let (directory, config) = scratch();
let location = directory.path();
let saved = parse(&[
"--config-dir",
location.to_str().expect("utf8 path"),
"query",
"named",
"save",
"pedidos",
"SELECT * FROM pedidos",
]);
assert_eq!(
unconnected(&saved, &config, Some(location))
.expect("answers")
.expect("without a server")
.data["stored"],
true
);
for action in [vec!["list"], vec!["remove", "pedidos"]] {
let argv: Vec<&str> = vec![
"--config-dir",
location.to_str().expect("utf8 path"),
"query",
"named",
]
.into_iter()
.chain(action.iter().copied())
.collect();
assert!(
unconnected(&parse(&argv), &config, Some(location))
.expect("answers")
.is_some(),
"`{argv:?}` must be served without a connection"
);
}
}
#[test]
fn running_a_kept_statement_still_needs_the_server() {
let (directory, config) = scratch();
let mut catalogue =
crate::exec::named::Catalogue::open(directory.path()).expect("the catalogue opens");
catalogue.put(
"pedidos",
crate::exec::named::Stored {
statement: "SELECT 1".to_owned(),
params: Vec::new(),
max_rows: None,
},
);
catalogue.save().expect("the catalogue saves");
let cli = parse(&[
"--config-dir",
directory.path().to_str().expect("a utf8 path"),
"--profile",
"producao",
"query",
"named",
"run",
"pedidos",
]);
assert!(unconnected(&cli, &config, Some(directory.path()))
.expect("resolves")
.is_none());
}
#[test]
fn a_refused_statement_never_reaches_the_destination() {
let (directory, config) = scratch();
let cli = parse(&["query", "run", "SELECT 1; DROP TABLE users"]);
let failure = unconnected(&cli, &config, Some(directory.path())).expect_err("must refuse");
assert_eq!(failure.category(), crate::error::Category::Validation);
}
#[test]
fn a_command_that_needs_a_server_is_not_answered_here() {
let (directory, config) = scratch();
for command in [
vec!["schema", "tables"],
vec!["query", "run", "SELECT 1"],
vec!["server", "status"],
] {
assert!(
unconnected(&parse(&command), &config, Some(directory.path()))
.expect("resolves")
.is_none(),
"`{command:?}` must be left to the connected path"
);
}
}
}