use crate::cli::globals::{Compress, GlobalFlags, RowCountMode as FlagRowCountMode};
use crate::config::keys::Value;
use crate::config::Config;
use crate::error::{Failure, Result};
use std::time::Duration;
fn no_usable_value(key: &str) -> Failure {
Failure::config(
"config.key_without_a_usable_value",
format!("`{key}` carries no value this build can use"),
)
.with_detail("detail", key)
.with_hint("this is a defect in the setting registry, not in the invocation")
}
pub fn boolean(config: &Config, key: &str) -> Result<bool> {
match config.resolve(key)?.value {
Some(Value::Boolean(value)) => Ok(value),
_ => Err(no_usable_value(key)),
}
}
pub fn integer(config: &Config, key: &str) -> Result<u64> {
match config.resolve(key)?.value {
Some(Value::Integer(value)) => Ok(value),
_ => Err(no_usable_value(key)),
}
}
pub fn count(config: &Config, key: &str) -> Result<usize> {
Ok(usize::try_from(integer(config, key)?).unwrap_or(usize::MAX))
}
pub fn word(config: &Config, key: &str) -> Result<String> {
match config.resolve(key)?.value {
Some(Value::Enumeration(value)) => Ok(value.to_owned()),
Some(Value::Text(value)) => Ok(value),
_ => Err(no_usable_value(key)),
}
}
pub fn seconds(config: &Config, key: &str) -> Result<Duration> {
Ok(Duration::from_secs(integer(config, key)?))
}
#[must_use]
pub fn protocol_floor(
config_dir: Option<&std::path::Path>,
) -> crate::conn::provider::ProtocolFloor {
use crate::conn::provider::ProtocolFloor;
Config::load(config_dir)
.ok()
.and_then(|config| word(&config, "tls.min_version").ok())
.map_or(ProtocolFloor::default(), |value| {
ProtocolFloor::from_word(&value)
})
}
pub fn optional_count(config: &Config, key: &str) -> Result<Option<usize>> {
Ok(match config.resolve(key)?.value {
Some(Value::Integer(value)) => usize::try_from(value).ok(),
_ => None,
})
}
pub fn optional_word(config: &Config, key: &str) -> Result<Option<String>> {
Ok(match config.resolve(key)?.value {
Some(Value::Enumeration(value)) => Some(value.to_owned()),
Some(Value::Text(value)) => Some(value),
_ => None,
})
}
pub fn concurrency(config: &Config, flags: &GlobalFlags) -> Result<usize> {
use crate::runtime::gate;
gate::declare_ceiling(count(config, "limits.max_concurrency_ceiling")?);
if let Some(asked) = flags.limits.max_concurrency {
return gate::admissible(asked);
}
Ok(optional_count(config, "limits.max_concurrency")?
.map_or_else(gate::permits_for_host, |stored| {
stored.clamp(1, gate::ceiling())
}))
}
pub fn row_count_matched(config: &Config, flags: &GlobalFlags) -> Result<bool> {
if let Some(mode) = flags.output.row_count {
return Ok(matches!(mode, FlagRowCountMode::Matched));
}
Ok(word(config, "sql.row_count_mode")? == "matched")
}
pub fn compress(config: &Config, flags: &GlobalFlags) -> Result<bool> {
Ok(match flags.limits.compress {
Some(Compress::Always) => true,
Some(Compress::Never | Compress::Auto) => false,
None => word(config, "conn.compression")? == "always",
})
}
#[must_use]
pub fn no_input(flags: &GlobalFlags) -> bool {
flags.safety.no_input
}
pub fn refuse_a_read_that_would_wait(refuses_to_ask: bool, what: &str) -> Result<()> {
use std::io::IsTerminal as _;
if refuses_to_ask && std::io::stdin().is_terminal() {
return Err(Failure::validation(
"input.refused",
format!("reading {what} would wait for somebody to type, and this invocation refuses to ask"),
)
.with_detail("detail", "stdin")
.with_hint("pipe the value in, or drop --no-input"));
}
Ok(())
}
pub fn operation_timeout(config: &Config, flags: &GlobalFlags) -> Result<Duration> {
match flags.limits.timeout {
Some(secs) => Ok(Duration::from_secs(secs)),
None => seconds(config, "limits.query_timeout_secs"),
}
}
pub fn connect_timeout(config: &Config, flags: &GlobalFlags) -> Result<Duration> {
match flags.limits.connect_timeout {
Some(secs) => Ok(Duration::from_secs(secs)),
None => seconds(config, "limits.connect_timeout_secs"),
}
}
pub fn retry_policy(config: &Config, flags: &GlobalFlags) -> Result<crate::runtime::Backoff> {
let attempts = match flags.limits.retries {
Some(asked) => asked,
None => u32::try_from(integer(config, "limits.retries")?).unwrap_or_default(),
};
let base = Duration::from_millis(integer(config, "limits.retry_base_ms")?);
Ok(crate::runtime::Backoff::new(
attempts,
base,
Duration::from_millis(integer(config, "limits.retry_wait_ceiling_ms")?),
Duration::from_millis(integer(config, "limits.retry_deadline_ms")?),
))
}
pub fn secret_storage(config: &Config) -> Result<crate::config::vault::SecretStorage> {
crate::config::vault::SecretStorage::parse(&word(config, "secret.storage_mode")?)
}
pub fn encryption(config: &Config, flags: &GlobalFlags) -> Result<crate::conn::tls::Encryption> {
use crate::conn::tls::{Encryption, RootStore, Verification};
let verification = Verification::parse(&word(config, "tls.verify")?)?;
if verification.accept_unknown_authority && !flags.safety.accept_unverified_tls {
return Err(Failure::config(
"config.unverified_tls_unacknowledged",
"`tls.verify` is set to trust an unknown authority, which is the \
check that tells the server apart from an impostor",
)
.with_detail("detail", "tls.verify")
.with_hint(
"pass `--accept-unverified-tls` to take that risk for this \
invocation, or set `tls.verify` to full or to ca",
));
}
Ok(Encryption {
demanded: boolean(config, "conn.require_tls")?,
verification,
root_store: RootStore::parse(&word(config, "tls.root_store")?)?,
})
}
pub fn conversion(config: &Config) -> Result<crate::types::Conversion> {
use crate::types::binary::{Content, Policy};
use crate::types::Conversion;
let content = match word(config, "output.binary")?.as_str() {
"summary" => Content::Described,
"full" => Content::Raw {
max_bytes: count(config, "output.max_bytes")?,
},
other => {
return Err(Failure::config(
"config.unknown_binary_shape",
format!("`{other}` is not a shape a byte value can take"),
)
.with_detail("detail", other)
.with_hint("set output.binary to summary or to full"))
}
};
Ok(Conversion {
binary: Policy { content },
})
}
pub fn session_setup(config: &Config) -> Result<Vec<String>> {
Ok(optional_word(config, "conn.session_setup")?
.into_iter()
.flat_map(|stored| {
stored
.split(';')
.map(str::trim)
.filter(|adjustment| !adjustment.is_empty())
.map(ToOwned::to_owned)
.collect::<Vec<_>>()
})
.collect())
}
pub fn read_only(config: &Config, flags: &GlobalFlags) -> Result<bool> {
Ok(flags.safety.read_only || boolean(config, "sql.read_only")?)
}
#[cfg(test)]
mod tests {
use super::*;
use clap::Parser;
fn flags_from(args: &[&str]) -> GlobalFlags {
let command_line: Vec<String> = std::iter::once("mariadb-cli")
.chain(args.iter().copied())
.chain(["meta", "version"])
.map(ToOwned::to_owned)
.collect();
crate::cli::Cli::try_parse_from(command_line)
.expect("the sample invocation parses")
.globals
}
fn empty_config() -> Config {
let scratch = tempfile::tempdir().expect("scratch directory");
Config::load(Some(scratch.path())).expect("an empty location still loads")
}
#[test]
fn a_missing_key_falls_back_to_the_published_default() {
let config = empty_config();
assert_eq!(integer(&config, "limits.retries").expect("resolves"), 2);
assert!(!boolean(&config, "sql.read_only").expect("resolves"));
}
#[test]
fn a_mark_on_the_command_line_beats_the_stored_value() {
let config = empty_config();
let flags = flags_from(&["--timeout", "5"]);
assert_eq!(
operation_timeout(&config, &flags).expect("resolves"),
Duration::from_secs(5)
);
}
#[test]
fn the_refusal_mark_only_ever_tightens() {
let config = empty_config();
let asked = flags_from(&["--read-only"]);
assert!(read_only(&config, &asked).expect("resolves"));
let silent = flags_from(&[]);
assert!(
!read_only(&config, &silent).expect("resolves"),
"nothing but the mark or the key may refuse every change"
);
}
#[test]
fn asking_for_no_repeats_is_honoured() {
let config = empty_config();
assert_eq!(
retry_policy(&config, &flags_from(&["--retries", "0"]))
.expect("resolves")
.extra_attempts,
0
);
assert_eq!(
retry_policy(&config, &flags_from(&["--retries", "4"]))
.expect("resolves")
.extra_attempts,
4
);
}
#[test]
fn the_wait_between_attempts_grows_and_then_stops() {
let policy = retry_policy(&empty_config(), &flags_from(&[])).expect("resolves");
assert_eq!(policy.wait_before(1), Duration::from_millis(200));
assert_eq!(policy.wait_before(2), Duration::from_millis(400));
assert_eq!(policy.wait_before(50), policy.ceiling);
assert!(policy.ceiling <= Duration::from_secs(10));
}
#[test]
fn trusting_an_unknown_authority_is_refused_unless_the_invocation_says_so() {
let config = empty_config()
.with_flag("tls.verify", "none")
.expect("a legal level");
let failure =
encryption(&config, &flags_from(&[])).expect_err("the level alone is not enough");
assert_eq!(failure.code(), "config.unverified_tls_unacknowledged");
assert!(
failure.hint().is_some_and(|hint| hint.contains("full")),
"the way back to a checked channel is named"
);
let acknowledged = encryption(&config, &flags_from(&["--accept-unverified-tls"]))
.expect("the caller said so");
assert!(
acknowledged.verification.accept_unknown_authority,
"the level asked for is the level given"
);
}
#[test]
fn accepting_a_name_mismatch_needs_no_acknowledgement() {
let config = empty_config()
.with_flag("tls.verify", "ca")
.expect("a legal level");
let resolved = encryption(&config, &flags_from(&[])).expect("the chain is still checked");
assert!(resolved.verification.accept_address_mismatch);
assert!(!resolved.verification.accept_unknown_authority);
}
#[test]
fn the_channel_takes_its_published_defaults() {
use crate::conn::provider::ProtocolFloor;
use crate::conn::tls::RootStore;
let resolved = encryption(&empty_config(), &flags_from(&[])).expect("resolves");
assert!(
resolved.demanded,
"an encrypted channel is demanded by default"
);
assert!(resolved.verification.is_strict(), "both checks stay on");
assert_eq!(resolved.root_store, RootStore::System);
let scratch = tempfile::tempdir().expect("scratch directory");
assert_eq!(
protocol_floor(Some(scratch.path())),
ProtocolFloor::Twelve,
"nothing below 1.2 is offered and 1.3 is not demanded by default"
);
}
#[test]
fn asking_for_the_newer_protocol_raises_the_floor() {
use crate::conn::provider::ProtocolFloor;
let scratch = tempfile::tempdir().expect("scratch directory");
let file =
crate::config::paths::config_file(Some(scratch.path())).expect("a settings location");
crate::config::store::store(&file, "tls.min_version", "1.3").expect("legal");
assert_eq!(
protocol_floor(Some(scratch.path())),
ProtocolFloor::Thirteen
);
}
#[test]
fn a_read_is_refused_only_when_it_would_really_wait() {
use std::io::IsTerminal as _;
let on_a_terminal = std::io::stdin().is_terminal();
assert!(
refuse_a_read_that_would_wait(false, "a secret").is_ok(),
"an invocation that never said it refuses must still be able to read"
);
let refused = refuse_a_read_that_would_wait(true, "a secret");
assert_eq!(
refused.is_err(),
on_a_terminal,
"the refusal must follow whether a person could be waiting"
);
if let Err(failure) = refused {
assert_eq!(failure.code(), "input.refused");
assert_eq!(failure.exit_number().code(), 3);
assert!(failure.hint().is_some());
}
}
#[test]
fn a_session_gets_no_adjustment_until_one_is_stored() {
assert!(session_setup(&empty_config()).expect("resolves").is_empty());
}
#[test]
fn a_byte_value_is_described_until_the_content_is_asked_for() {
use crate::types::binary::Content;
let described = conversion(&empty_config()).expect("resolves");
assert_eq!(described.binary.content, Content::Described);
}
#[test]
fn asking_for_the_content_changes_what_a_byte_value_becomes() {
use crate::types::binary::Content;
let scratch = tempfile::tempdir().expect("scratch directory");
let file =
crate::config::paths::config_file(Some(scratch.path())).expect("a settings location");
crate::config::store::store(&file, "output.binary", "full").expect("legal");
let config = Config::load(Some(scratch.path())).expect("the location loads");
assert!(matches!(
conversion(&config).expect("resolves").binary.content,
Content::Raw { .. }
));
}
#[test]
fn a_ceiling_of_zero_on_the_command_line_is_refused() {
let failure = concurrency(&empty_config(), &flags_from(&["--max-concurrency", "0"]))
.expect_err("zero admits no work");
assert_eq!(failure.code(), "concurrency.none_admitted");
assert_eq!(failure.exit_number().code(), 2);
}
#[test]
fn a_ceiling_above_the_declared_one_is_refused_against_the_only_ceiling() {
let above = (crate::runtime::gate::MAX_PERMITS + 1).to_string();
let failure = concurrency(&empty_config(), &flags_from(&["--max-concurrency", &above]))
.expect_err("above the ceiling");
assert_eq!(failure.code(), "concurrency.above_ceiling");
assert_eq!(failure.exit_number().code(), 2);
assert_eq!(
concurrency(
&empty_config(),
&flags_from(&[
"--max-concurrency",
&crate::runtime::gate::MAX_PERMITS.to_string()
])
)
.expect("the ceiling itself is legal"),
crate::runtime::gate::MAX_PERMITS
);
}
#[test]
fn the_host_count_stands_in_when_nothing_was_asked_for() {
let resolved = concurrency(&empty_config(), &flags_from(&[])).expect("resolves");
assert!(resolved >= 1);
assert!(resolved <= crate::runtime::gate::MAX_PERMITS);
}
#[test]
fn the_change_count_defaults_to_the_rows_the_server_altered() {
let config = empty_config();
assert!(!row_count_matched(&config, &flags_from(&[])).expect("resolves"));
assert!(
row_count_matched(&config, &flags_from(&["--row-count", "matched"])).expect("resolves")
);
}
}