use super::{cell, fetch, text_of, ServerSettings};
use crate::cli::server::KillArgs;
use crate::error::{Failure, Result};
use crate::output::{Envelope, Row};
use mysql_async::{params, Conn, Params};
use serde_json::json;
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Target {
pub id: u64,
pub owner: String,
pub is_own_connection: bool,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Decision {
pub statement: String,
pub belongs_to_another_user: bool,
pub warning: String,
}
pub async fn run(
connection: &mut Conn,
args: &KillArgs,
own_connection_id: u64,
settings: &ServerSettings,
) -> Result<Envelope> {
let own_user = read_own_user(connection).await?;
let target = look_up(connection, args.id, own_connection_id).await?;
let decision = decide(&target, &own_user, args, settings)?;
fetch(connection, &decision.statement, Params::Empty).await?;
let still_open = look_up(connection, args.id, own_connection_id)
.await
.is_ok();
Ok(Envelope::new(
"server kill",
json!({
"id": target.id,
"owner": target.owner,
"belongs_to_another_user": decision.belongs_to_another_user,
"statement_only": args.query_only,
"still_open": still_open,
"warning": decision.warning,
}),
))
}
pub fn decide(
target: &Target,
own_user: &str,
args: &KillArgs,
settings: &ServerSettings,
) -> Result<Decision> {
if target.is_own_connection {
return Err(Failure::validation(
"validation.own_connection",
"that identifier is the connection carrying this request",
)
.with_hint("end another connection; ending this one would break the call in progress"));
}
if !settings.confirmed {
return Err(Failure::validation(
"validation.confirmation_missing",
"ending the work of a connection needs confirmation",
)
.with_hint("repeat the call with --yes"));
}
let belongs_to_another_user = target.owner != own_user;
if belongs_to_another_user && settings.kill_foreign_requires_yes && !args.kill_other {
return Err(Failure::validation(
"validation.other_user_not_allowed",
"that connection belongs to another user",
)
.with_hint("repeat the call with --kill-other to end work that is not yours"));
}
Ok(Decision {
statement: statement_for(target.id, args.query_only),
belongs_to_another_user,
warning: warning_for(&target.owner, belongs_to_another_user, args.query_only),
})
}
#[must_use]
pub fn statement_for(id: u64, statement_only: bool) -> String {
if statement_only {
format!("KILL QUERY {id}")
} else {
format!("KILL CONNECTION {id}")
}
}
#[must_use]
pub fn warning_for(owner: &str, belongs_to_another_user: bool, statement_only: bool) -> String {
let what = if statement_only {
"the running statement"
} else {
"the whole connection"
};
if belongs_to_another_user {
format!("{what} of another user, `{owner}`, was ended on request")
} else {
format!("{what} of `{owner}`, your own user, was ended on request")
}
}
async fn read_own_user(connection: &mut Conn) -> Result<String> {
let rows = fetch(
connection,
"SELECT SUBSTRING_INDEX(USER(), '@', 1)",
Params::Empty,
)
.await?;
Ok(rows
.first()
.and_then(|row| row.values().next())
.map(|value| text_of(Some(value)))
.unwrap_or_default())
}
async fn look_up(connection: &mut Conn, id: u64, own_connection_id: u64) -> Result<Target> {
let rows = fetch(
connection,
"SELECT ID, USER FROM information_schema.PROCESSLIST WHERE ID = :id",
params! { "id" => id },
)
.await
.map_err(|failure| super::observation_failure(failure, "PROCESS", "other-connections"))?;
let row: &Row = rows.first().ok_or_else(|| {
Failure::absence(
"absence.unknown_connection",
"no connection on this server carries that identifier",
)
.with_hint("list the open connections first to confirm the identifier")
})?;
Ok(Target {
id,
owner: text_of(cell(row, "USER")),
is_own_connection: id == own_connection_id,
})
}
#[cfg(test)]
mod tests {
use super::*;
fn args(query_only: bool, kill_other: bool) -> KillArgs {
KillArgs {
id: 4711,
query_only,
kill_other,
}
}
fn settings(confirmed: bool) -> ServerSettings {
ServerSettings {
status_interval_secs: 1,
default_top: 100,
confirmed,
observability_visible: true,
kill_foreign_requires_yes: true,
}
}
fn target(owner: &str, is_own: bool) -> Target {
Target {
id: 4711,
owner: owner.to_owned(),
is_own_connection: is_own,
}
}
#[test]
fn another_users_work_is_refused_without_the_mark() {
let failure = decide(
&target("reporting", false),
"app",
&args(true, false),
&settings(true),
)
.expect_err("another user's work must be refused");
assert_eq!(failure.code(), "validation.other_user_not_allowed");
assert_eq!(failure.exit_number().code(), 3);
assert!(failure
.hint()
.is_some_and(|hint| hint.contains("--kill-other")));
}
#[test]
fn another_users_work_goes_through_with_the_mark_and_names_the_owner() {
let decision = decide(
&target("reporting", false),
"app",
&args(true, true),
&settings(true),
)
.expect("the mark allows it");
assert!(decision.belongs_to_another_user);
assert!(decision.warning.contains("reporting"));
assert!(decision.warning.contains("another user"));
}
#[test]
fn your_own_work_needs_only_the_ordinary_confirmation() {
let decision = decide(
&target("app", false),
"app",
&args(true, false),
&settings(true),
)
.expect("own work");
assert!(!decision.belongs_to_another_user);
assert_eq!(decision.statement, "KILL QUERY 4711");
}
#[test]
fn nothing_is_sent_without_the_confirmation() {
let failure = decide(
&target("app", false),
"app",
&args(true, false),
&settings(false),
)
.expect_err("confirmation is required");
assert_eq!(failure.code(), "validation.confirmation_missing");
assert!(failure.hint().is_some_and(|hint| hint.contains("--yes")));
}
#[test]
fn this_invocations_own_connection_is_never_ended() {
let failure = decide(
&target("app", true),
"app",
&args(false, true),
&settings(true),
)
.expect_err("our own connection must be refused");
assert_eq!(failure.code(), "validation.own_connection");
}
#[test]
fn the_extra_mark_for_another_users_work_can_be_turned_off() {
let without_the_extra_mark = ServerSettings {
kill_foreign_requires_yes: false,
..settings(true)
};
let decision = decide(
&target("reporting", false),
"app",
&args(true, false),
&without_the_extra_mark,
)
.expect("the ordinary confirmation is enough now");
assert!(decision.belongs_to_another_user);
assert!(decision.warning.contains("reporting"));
let unconfirmed = ServerSettings {
kill_foreign_requires_yes: false,
..settings(false)
};
assert_eq!(
decide(
&target("reporting", false),
"app",
&args(true, false),
&unconfirmed
)
.expect_err("the ordinary confirmation still stands")
.code(),
"validation.confirmation_missing"
);
}
#[test]
fn ending_a_statement_differs_from_ending_a_connection() {
assert_eq!(statement_for(9, true), "KILL QUERY 9");
assert_eq!(statement_for(9, false), "KILL CONNECTION 9");
assert!(warning_for("app", false, true).contains("statement"));
assert!(warning_for("app", false, false).contains("connection"));
}
}