use super::{fetch, first_cell, number_of, text_of, ServerSettings};
use crate::error::{Failure, Result};
use crate::output::{Envelope, Row};
use mysql_async::{Conn, Params};
use serde_json::{json, Value};
const MODERN: &str = "SHOW REPLICA STATUS";
const LEGACY: &str = "SHOW SLAVE STATUS";
const LAG: [&str; 2] = ["Seconds_Behind_Master", "Seconds_Behind_Source"];
const RECEIVING: [&str; 2] = ["Slave_IO_Running", "Replica_IO_Running"];
const APPLYING: [&str; 2] = ["Slave_SQL_Running", "Replica_SQL_Running"];
const POSITION: [&str; 2] = ["Exec_Master_Log_Pos", "Exec_Source_Log_Pos"];
const POSITION_FILE: [&str; 2] = ["Relay_Master_Log_File", "Relay_Source_Log_File"];
const LAST_ERROR: [&str; 3] = ["Last_Error", "Last_SQL_Error", "Last_IO_Error"];
pub async fn run(connection: &mut Conn, _settings: &ServerSettings) -> Result<Envelope> {
let rows = match fetch(connection, MODERN, Params::Empty).await {
Ok(rows) => rows,
Err(failure) if super::is_absent_structure(&failure) => {
fetch(connection, LEGACY, Params::Empty).await?
}
Err(failure) => return Err(failure),
};
let row = rows.first().ok_or_else(standalone)?;
Ok(Envelope::new("server replica", describe(row)))
}
fn standalone() -> Failure {
Failure::absence(
"absence.not_a_replica",
"this destination follows no other server",
)
.with_hint("read the replica situation on the destination that does the following")
}
#[must_use]
pub fn describe(row: &Row) -> Value {
let receiving = running(&text_of(first_cell(row, &RECEIVING)));
let applying = running(&text_of(first_cell(row, &APPLYING)));
let lag = number_of(first_cell(row, &LAG));
let last_error = non_empty(text_of(first_cell(row, &LAST_ERROR)));
json!({
"following": true,
"receiving": receiving,
"applying": applying,
"active": receiving && applying,
"seconds_behind": lag,
"applied_position": first_cell(row, &POSITION).cloned().unwrap_or(Value::Null),
"applied_position_file": first_cell(row, &POSITION_FILE).cloned().unwrap_or(Value::Null),
"last_error": last_error,
"warning": warning(receiving && applying, lag, last_error.is_some()),
})
}
fn running(state: &str) -> bool {
state.eq_ignore_ascii_case("yes")
}
fn non_empty(text: String) -> Option<String> {
(!text.trim().is_empty()).then_some(text)
}
#[must_use]
pub fn warning(active: bool, lag: Option<i64>, has_error: bool) -> String {
if !active || has_error {
return "this destination follows another server and is not applying changes, \
so every reading here may be arbitrarily old"
.to_owned();
}
match lag {
Some(0) => "this destination follows another server and is caught up, \
so a reading may still miss a change made moments ago"
.to_owned(),
Some(seconds) => format!(
"this destination follows another server and trails it by {seconds} seconds, \
so every reading here is that old"
),
None => "this destination follows another server and does not report how far \
behind it is, so the age of a reading here is unknown"
.to_owned(),
}
}
#[cfg(test)]
mod tests {
use super::*;
fn situation(io: &str, sql: &str, lag: Value, error: &str) -> Row {
let mut row = Row::new();
row.insert("Slave_IO_Running".to_owned(), json!(io));
row.insert("Slave_SQL_Running".to_owned(), json!(sql));
row.insert("Seconds_Behind_Master".to_owned(), lag);
row.insert("Exec_Master_Log_Pos".to_owned(), json!(4711));
row.insert("Relay_Master_Log_File".to_owned(), json!("bin.000004"));
row.insert("Last_Error".to_owned(), json!(error));
row
}
#[test]
fn a_trailing_copy_warns_about_the_age_of_its_answers() {
let described = describe(&situation("Yes", "Yes", json!(2), ""));
assert_eq!(described["active"], json!(true));
assert_eq!(described["seconds_behind"], json!(2));
assert_eq!(described["last_error"], Value::Null);
assert!(text_of(Some(&described["warning"])).contains('2'));
}
#[test]
fn a_stopped_copy_warns_that_its_answers_are_of_unknown_age() {
let described = describe(&situation("Yes", "No", Value::Null, "duplicate key"));
assert_eq!(described["active"], json!(false));
assert_eq!(described["last_error"], json!("duplicate key"));
assert!(text_of(Some(&described["warning"])).contains("arbitrarily old"));
}
#[test]
fn a_copy_caught_up_still_warns() {
let described = describe(&situation("Yes", "Yes", json!(0), ""));
assert!(!text_of(Some(&described["warning"])).is_empty());
}
#[test]
fn either_generation_of_column_names_is_read() {
let mut row = Row::new();
row.insert("Replica_IO_Running".to_owned(), json!("Yes"));
row.insert("Replica_SQL_Running".to_owned(), json!("Yes"));
row.insert("Seconds_Behind_Source".to_owned(), json!(7));
let described = describe(&row);
assert_eq!(described["active"], json!(true));
assert_eq!(described["seconds_behind"], json!(7));
}
#[test]
fn a_standalone_destination_is_an_absence() {
assert_eq!(standalone().exit_number().code(), 8);
}
}