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};
const UNKNOWN_THREAD: u16 = 1094;
#[derive(Debug, Clone)]
pub struct SecondConnection {
options: Opts,
}
impl SecondConnection {
pub fn prepare(profile: &Profile, settings: &ConnectionSettings) -> Result<Self> {
let mut plain = settings.clone();
plain.refuse_change = false;
plain.statement_budget = None;
Ok(Self {
options: super::options::build(profile, &plain)?,
})
}
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
}
async fn round_trip(&self, session: u64) -> Result<AbortOutcome> {
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;
let closed = conn.disconnect().await;
let outcome = outcome?;
closed.or_failure()?;
Ok(outcome)
}
}
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))
}
}
}
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()?;
Ok(match still_running {
Some(0) => AbortOutcome::Confirmed,
_ => AbortOutcome::NotReached,
})
}
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")
}
}
#[test]
fn preparing_the_ask_opens_nothing() {
SecondConnection::prepare(&profile(), &settings()).expect("prepares");
}
#[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")));
}
#[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"));
}
#[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");
}
#[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));
}
}