use super::OrFailure;
use crate::error::{Failure, Result};
use mysql_async::prelude::Queryable;
use mysql_async::Conn;
use serde::Serialize;
use serde_json::{json, Value};
use std::sync::atomic::{AtomicU64, Ordering};
pub const MINIMUM_SERVER_VERSION: (u16, u16) = (10, 11);
const PROBE: &str = "SELECT \
@@version, \
@@version_comment, \
@@read_only, \
@@sql_mode, \
@@autocommit, \
DATABASE(), \
CONNECTION_ID(), \
@@max_allowed_packet";
const CEILING_NOT_ANSWERED: u64 = 0;
type ProbeRow = (String, String, i64, String, i64, Option<String>, u64, u64);
#[allow(clippy::struct_excessive_bools)]
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct ServerFacts {
pub version: String,
pub version_parts: (u16, u16, u16),
pub version_comment: String,
pub is_mariadb: bool,
pub read_only: bool,
pub sql_mode: String,
pub autocommit: bool,
pub database: Option<String>,
pub connection_id: u64,
pub max_allowed_packet: u64,
pub meets_minimum_version: bool,
pub capabilities: Capabilities,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
pub struct Capabilities {
pub system_versioning: bool,
pub sequences: bool,
pub checked_documents: bool,
}
impl Capabilities {
#[must_use]
pub const fn derive(parts: (u16, u16, u16), is_mariadb: bool) -> Self {
Self {
system_versioning: is_mariadb && at_least(parts, 10, 3),
sequences: is_mariadb && at_least(parts, 10, 3),
checked_documents: is_mariadb && at_least(parts, 10, 4),
}
}
}
const fn at_least(parts: (u16, u16, u16), major: u16, minor: u16) -> bool {
parts.0 > major || (parts.0 == major && parts.1 >= minor)
}
impl ServerFacts {
#[must_use]
pub fn from_probe(
version: String,
version_comment: String,
read_only: bool,
sql_mode: String,
autocommit: bool,
database: Option<String>,
connection_id: u64,
) -> Self {
let version_parts = parse_version(&version);
let is_mariadb = version.to_ascii_lowercase().contains("mariadb")
|| version_comment.to_ascii_lowercase().contains("mariadb");
Self {
capabilities: Capabilities::derive(version_parts, is_mariadb),
meets_minimum_version: meets_minimum(version_parts),
version,
version_parts,
version_comment,
is_mariadb,
read_only,
sql_mode,
autocommit,
database,
connection_id,
max_allowed_packet: CEILING_NOT_ANSWERED,
}
}
#[must_use]
pub fn as_value(&self) -> Value {
json!({
"version": self.version,
"version_comment": self.version_comment,
"is_mariadb": self.is_mariadb,
"read_only": self.read_only,
"sql_mode": self.sql_mode,
"autocommit": self.autocommit,
"database": self.database,
"connection_id": self.connection_id,
"max_allowed_packet": self.max_allowed_packet,
"meets_minimum_version": self.meets_minimum_version,
"minimum_server_version": format!(
"{}.{}",
MINIMUM_SERVER_VERSION.0, MINIMUM_SERVER_VERSION.1
),
"capabilities": self.capabilities,
})
}
#[must_use]
pub fn version_warning(&self) -> Option<String> {
(!self.meets_minimum_version).then(|| {
format!(
"the server reports version {} and this product is written against {}.{} or newer; \
some commands may find structures this server does not have",
self.version, MINIMUM_SERVER_VERSION.0, MINIMUM_SERVER_VERSION.1
)
})
}
}
pub async fn probe(connection: &mut Conn) -> Result<ServerFacts> {
let row: Option<ProbeRow> = connection.exec_first(PROBE, ()).await.or_failure()?;
let (version, comment, read_only, sql_mode, autocommit, database, connection_id, packet) = row
.ok_or_else(|| {
Failure::server(
"server.silent_handshake",
"the server returned no answer when asked to describe itself",
)
.with_hint("confirm the destination points at a server of the MariaDB family")
})?;
PacketCeiling::observe(packet);
Ok(ServerFacts {
max_allowed_packet: packet,
..ServerFacts::from_probe(
version,
comment,
read_only != 0,
sql_mode,
autocommit != 0,
database,
connection_id,
)
})
}
pub struct PacketCeiling;
static OBSERVED: AtomicU64 = AtomicU64::new(0);
static IN_FORCE: AtomicU64 = AtomicU64::new(0);
impl PacketCeiling {
pub fn observe(bytes: u64) {
if bytes == 0 {
return;
}
let mut known = OBSERVED.load(Ordering::Relaxed);
loop {
if known != 0 && known <= bytes {
return;
}
match OBSERVED.compare_exchange_weak(known, bytes, Ordering::Relaxed, Ordering::Relaxed)
{
Ok(_) => return,
Err(seen) => known = seen,
}
}
}
#[must_use]
pub fn observed() -> Option<usize> {
usize::try_from(OBSERVED.load(Ordering::Relaxed))
.ok()
.filter(|bytes| *bytes > 0)
}
pub fn declare(bytes: Option<usize>) {
let settled = bytes.map_or(0, |bytes| u64::try_from(bytes).unwrap_or(u64::MAX));
IN_FORCE.store(settled, Ordering::Relaxed);
}
#[must_use]
pub fn in_force() -> Option<usize> {
usize::try_from(IN_FORCE.load(Ordering::Relaxed))
.ok()
.filter(|bytes| *bytes > 0)
}
}
fn parse_version(version: &str) -> (u16, u16, u16) {
let mut parts = version
.split(|character: char| !character.is_ascii_digit())
.filter(|part| !part.is_empty())
.map(|part| part.parse::<u16>().unwrap_or_default());
(
parts.next().unwrap_or_default(),
parts.next().unwrap_or_default(),
parts.next().unwrap_or_default(),
)
}
const fn meets_minimum(parts: (u16, u16, u16)) -> bool {
at_least(parts, MINIMUM_SERVER_VERSION.0, MINIMUM_SERVER_VERSION.1)
}
#[cfg(test)]
mod tests {
use super::*;
fn facts(version: &str, comment: &str) -> ServerFacts {
ServerFacts::from_probe(
version.to_owned(),
comment.to_owned(),
false,
"STRICT_TRANS_TABLES".to_owned(),
false,
Some("sales".to_owned()),
42,
)
}
#[test]
fn a_version_is_read_past_its_suffix() {
assert_eq!(
parse_version("11.4.2-MariaDB-1:11.4.2+maria~ubu2404"),
(11, 4, 2)
);
assert_eq!(parse_version("10.11.8-MariaDB"), (10, 11, 8));
assert_eq!(parse_version("nonsense"), (0, 0, 0));
}
#[test]
fn the_minimum_version_is_the_published_one() {
assert!(meets_minimum((10, 11, 0)));
assert!(meets_minimum((11, 0, 0)));
assert!(!meets_minimum((10, 6, 18)));
assert!(!meets_minimum((8, 0, 36)));
}
#[test]
fn an_older_server_is_warned_about_and_not_refused() {
let old = facts("10.6.18-MariaDB", "MariaDB Server");
assert!(!old.meets_minimum_version);
let warning = old.version_warning().expect("a warning is due");
assert!(warning.contains("10.6.18"));
assert!(warning.contains("10.11"));
let current = facts("11.4.2-MariaDB", "MariaDB Server");
assert!(current.meets_minimum_version);
assert!(current.version_warning().is_none());
}
#[test]
fn the_distribution_is_recognised_from_either_field() {
assert!(facts("11.4.2-MariaDB", "").is_mariadb);
assert!(facts("11.4.2", "mariadb.org binary distribution").is_mariadb);
assert!(!facts("8.0.36", "MySQL Community Server").is_mariadb);
}
#[test]
fn optional_abilities_follow_the_server() {
let current = facts("11.4.2-MariaDB", "MariaDB Server").capabilities;
assert!(current.system_versioning);
assert!(current.sequences);
assert!(current.checked_documents);
let other_family = facts("8.0.36", "MySQL Community Server").capabilities;
assert!(!other_family.system_versioning);
assert!(!other_family.sequences);
}
#[test]
fn one_probe_answers_all_four_questions() {
let answered = facts("11.4.2-MariaDB", "MariaDB Server").as_value();
assert!(answered["version"].is_string());
assert!(answered["read_only"].is_boolean());
assert!(answered["sql_mode"].is_string());
assert!(answered["capabilities"].is_object());
}
#[test]
fn the_packet_ceiling_is_part_of_what_the_handshake_answers() {
let answered = ServerFacts {
max_allowed_packet: 4 * 1024 * 1024,
..facts("11.4.2-MariaDB", "MariaDB Server")
};
assert_eq!(answered.as_value()["max_allowed_packet"], 4 * 1024 * 1024);
assert_eq!(
facts("11.4.2-MariaDB", "MariaDB Server").max_allowed_packet,
CEILING_NOT_ANSWERED,
"a record built without a probe states no ceiling of its own"
);
}
#[test]
fn the_smallest_ceiling_observed_is_the_one_kept() {
PacketCeiling::observe(8 * 1024 * 1024);
assert_eq!(PacketCeiling::observed(), Some(8 * 1024 * 1024));
PacketCeiling::observe(1024 * 1024);
assert_eq!(PacketCeiling::observed(), Some(1024 * 1024));
PacketCeiling::observe(16 * 1024 * 1024);
assert_eq!(
PacketCeiling::observed(),
Some(1024 * 1024),
"a more generous destination must never raise the ceiling"
);
}
#[test]
fn a_server_refusing_changes_is_reported() {
let mut facts = facts("11.4.2-MariaDB", "MariaDB Server");
facts.read_only = true;
assert_eq!(facts.as_value()["read_only"], true);
}
}