mirror of
https://github.com/Corfirean/coa-server-manager.git
synced 2026-11-22 03:25:56 +00:00
Merge pull request #33 from Corfirean/feat/diagnostics-routing
One-click diagnostics and report routing to Manager, Companions and SQUID
This commit is contained in:
20 files changed
+637
-58
No files matched your search
+261
-5
@@ -172,19 +172,158 @@ pub fn squash_repeated_config_warnings(text: &str) -> String {
|
||||
s
|
||||
}
|
||||
|
||||
const SENSITIVE: [&str; 7] = ["password", "passwd", "secret", "token", "apikey", "api_key", "databaseinfo"];
|
||||
|
||||
/// Remove things that must never leave the machine from log text.
|
||||
pub fn redact(text: &str) -> String {
|
||||
let mut out = Vec::new();
|
||||
for line in text.lines() {
|
||||
let l = line.to_lowercase();
|
||||
let sensitive = ["password", "passwd", "secret", "token", "apikey", "api_key", "databaseinfo"].iter().any(|k| l.contains(k));
|
||||
let sensitive = SENSITIVE.iter().any(|k| l.contains(k));
|
||||
out.push(if sensitive { "[line removed: may contain a secret]".to_string() } else { line.to_string() });
|
||||
}
|
||||
out.join("\n")
|
||||
}
|
||||
|
||||
/// The same for JSON: values under a sensitive key and strings that look like `password=...` are replaced, and the
|
||||
/// result stays valid JSON (removing a whole line would break the file for whoever reads it). Text that is not JSON
|
||||
/// falls back to the line rule.
|
||||
pub fn redact_json(text: &str) -> String {
|
||||
fn scrub(v: &mut serde_json::Value) {
|
||||
use serde_json::Value;
|
||||
match v {
|
||||
Value::Object(map) => {
|
||||
for (key, value) in map.iter_mut() {
|
||||
let k = key.to_lowercase();
|
||||
if SENSITIVE.iter().any(|s| k.contains(s)) && !value.is_object() && !value.is_array() {
|
||||
*value = Value::String("[redacted]".into());
|
||||
} else {
|
||||
scrub(value);
|
||||
}
|
||||
}
|
||||
}
|
||||
Value::Array(items) => items.iter_mut().for_each(scrub),
|
||||
Value::String(s) => {
|
||||
let l = s.to_lowercase();
|
||||
if ["password=", "passwd=", "secret=", "token=", "apikey=", "api_key=", "password:"].iter().any(|k| l.contains(k)) {
|
||||
*s = "[redacted]".into();
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
match serde_json::from_str::<serde_json::Value>(text) {
|
||||
Ok(mut v) => {
|
||||
scrub(&mut v);
|
||||
serde_json::to_string_pretty(&v).unwrap_or_else(|_| redact(text))
|
||||
}
|
||||
Err(_) => redact(text),
|
||||
}
|
||||
}
|
||||
|
||||
/// Keep the events of a `wevtutil ... /f:text` listing that mention one of `needles` (compared without case), in the
|
||||
/// order listed, at most `max` of them.
|
||||
pub fn filter_event_blocks(listing: &str, needles: &[&str], max: usize) -> String {
|
||||
let mut blocks: Vec<Vec<&str>> = Vec::new();
|
||||
for line in listing.lines() {
|
||||
if line.starts_with("Event[") || blocks.is_empty() {
|
||||
blocks.push(Vec::new());
|
||||
}
|
||||
if let Some(b) = blocks.last_mut() { b.push(line); }
|
||||
}
|
||||
blocks
|
||||
.into_iter()
|
||||
.map(|b| b.join("\n"))
|
||||
.filter(|b| { let l = b.to_lowercase(); needles.iter().any(|n| l.contains(n)) })
|
||||
.take(max)
|
||||
.collect::<Vec<_>>()
|
||||
.join("\n\n")
|
||||
}
|
||||
|
||||
/// Drop the lines of an event listing that name the person or the computer.
|
||||
pub fn drop_identity_lines(listing: &str) -> String {
|
||||
listing
|
||||
.lines()
|
||||
.filter(|l| { let t = l.trim_start(); !(t.starts_with("User:") || t.starts_with("User Name:") || t.starts_with("Computer:")) })
|
||||
.collect::<Vec<_>>()
|
||||
.join("\n")
|
||||
}
|
||||
|
||||
/// `wevtutil /uni:true` writes UTF-16 with a byte order mark; anything else is read as UTF-8 (lossy).
|
||||
fn decode_console_output(bytes: &[u8]) -> String {
|
||||
if bytes.starts_with(&[0xFF, 0xFE]) {
|
||||
let units: Vec<u16> = bytes[2..].chunks_exact(2).map(|c| u16::from_le_bytes([c[0], c[1]])).collect();
|
||||
String::from_utf16_lossy(&units)
|
||||
} else {
|
||||
String::from_utf8_lossy(bytes).into_owned()
|
||||
}
|
||||
}
|
||||
|
||||
/// Crashes and hangs Windows recorded for the server programs in the last two weeks. This is the only trace of a crash
|
||||
/// that ends the process without the server's own crash report (a stack buffer overrun, for example). The lines that
|
||||
/// name the user and the computer are left out.
|
||||
#[cfg(windows)]
|
||||
fn windows_events() -> String {
|
||||
use std::os::windows::process::CommandExt;
|
||||
let query = "*[System[(Provider[@Name='Application Error' or @Name='Windows Error Reporting' or @Name='Application Hang']) and TimeCreated[timediff(@SystemTime) <= 1209600000]]]";
|
||||
let out = std::process::Command::new("wevtutil")
|
||||
.args(["qe", "Application", &format!("/q:{query}"), "/c:300", "/rd:true", "/f:text", "/uni:true"])
|
||||
.creation_flags(0x0800_0000)
|
||||
.output();
|
||||
match out {
|
||||
Ok(o) if o.status.success() => {
|
||||
let text = filter_event_blocks(&decode_console_output(&o.stdout), &["worldserver", "authserver", "mysqld", "coa server manager", "coa-server-manager"], 40);
|
||||
if text.is_empty() { "No crash or hang of the server programs was recorded by Windows in the last 14 days.".into() } else { drop_identity_lines(&text) }
|
||||
}
|
||||
Ok(o) => format!("Windows event log could not be read: {}", decode_console_output(&o.stderr).trim()),
|
||||
Err(e) => format!("Windows event log could not be read: {e}"),
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(not(windows))]
|
||||
fn windows_events() -> String {
|
||||
String::new()
|
||||
}
|
||||
|
||||
/// Newest files of a folder with the given extension (compared without case): path, size, modified time.
|
||||
fn newest_files(dir: &Path, ext: &str, limit: usize) -> Vec<(PathBuf, u64, std::time::SystemTime)> {
|
||||
let Ok(rd) = fs::read_dir(dir) else { return Vec::new() };
|
||||
let mut v: Vec<_> = rd
|
||||
.flatten()
|
||||
.filter(|e| e.path().extension().is_some_and(|x| x.eq_ignore_ascii_case(ext)))
|
||||
.filter_map(|e| { let m = e.metadata().ok()?; m.is_file().then(|| (e.path(), m.len(), m.modified().unwrap_or(std::time::UNIX_EPOCH))) })
|
||||
.collect();
|
||||
v.sort_by(|a, b| b.2.cmp(&a.2));
|
||||
v.truncate(limit);
|
||||
v
|
||||
}
|
||||
|
||||
/// Which server programs run right now and from where, next to what the Manager made of it. A program started from a
|
||||
/// folder or a copy the Manager does not know shows up here even when the Manager reports "port in use".
|
||||
fn processes_report(root: &Path, ports: &layout::Ports) -> String {
|
||||
let here = root.to_string_lossy().to_lowercase().replace('/', "\\");
|
||||
let listen = process::listeners_detailed();
|
||||
let mut out = String::from("Server programs running now (any folder):\n");
|
||||
let found = process::find_by_file_names(&["worldserver.exe", "authserver.exe", "mysqld.exe"]);
|
||||
if found.is_empty() { out.push_str(" none\n"); }
|
||||
for p in found {
|
||||
let ports_of: Vec<String> = listen.iter().filter(|l| l.pid == p.pid).map(|l| l.port.to_string()).collect();
|
||||
let inside = p.exe.to_lowercase().replace('/', "\\").starts_with(&here);
|
||||
out.push_str(&format!(" pid {} {} | listening on: {} | {}\n", p.pid, p.exe, if ports_of.is_empty() { "-".into() } else { ports_of.join(", ") }, if inside { "inside this server folder" } else { "OUTSIDE this server folder" }));
|
||||
}
|
||||
let o = process::observe(root, ports);
|
||||
out.push_str("\nThe Manager's view:\n");
|
||||
for s in [Some(&o.mysql), Some(&o.auth), Some(&o.world), o.secondary_world.as_ref()].into_iter().flatten() {
|
||||
out.push_str(&format!(" {:<16} {:?} port {} {}{}\n", s.name, s.state, s.port, s.pid.map(|p| format!("pid {p}")).unwrap_or_default(), s.conflict.as_ref().map(|c| format!(" | port held by pid {} {}", c.pid, c.exe.clone().unwrap_or_default())).unwrap_or_default()));
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Zip with what a maintainer needs to debug a problem, with secrets removed. Returns the number of files inside.
|
||||
/// One call collects everything: the Manager's and the server's logs, crash reports and small crash dumps, Windows'
|
||||
/// own record of crashes, the update journals, the running server programs and the settings the client depends on.
|
||||
pub fn export_package(root: &Path, meta_dir: &Path, manager_log: &Path, meta: &InstallMeta, report: &Report, out_zip: &Path) -> Result<usize> {
|
||||
const DUMP_FILE_MAX: u64 = 30 * 1024 * 1024;
|
||||
let file = fs::File::create(out_zip)?;
|
||||
let mut zip = zip::ZipWriter::new(file);
|
||||
let opts = zip::write::SimpleFileOptions::default().compression_method(zip::CompressionMethod::Deflated);
|
||||
@@ -195,8 +334,10 @@ pub fn export_package(root: &Path, meta_dir: &Path, manager_log: &Path, meta: &I
|
||||
n += 1;
|
||||
Ok(())
|
||||
};
|
||||
let ports = layout::read_ports(root);
|
||||
let summary = serde_json::json!({
|
||||
"manager": crate::MANAGER_VERSION,
|
||||
"exported_utc": chrono::Utc::now().to_rfc3339(),
|
||||
"core": meta.core,
|
||||
"bots": meta.bots,
|
||||
"squid_bots": crate::squid::release(root),
|
||||
@@ -206,7 +347,25 @@ pub fn export_package(root: &Path, meta_dir: &Path, manager_log: &Path, meta: &I
|
||||
"wow_client_set": meta.client_path.is_some(),
|
||||
});
|
||||
add("summary.json", serde_json::to_string_pretty(&summary)?.as_bytes())?;
|
||||
for (name, path) in [("manager.log", manager_log.to_path_buf()), ("manager-install.log", meta_dir.join("logs/manager.log")), ("Server.log.tail", root.join("Core/Logs/Server.log")), ("Errors.log.tail", root.join("Core/Logs/Errors.log")), ("Auth.log.tail", root.join("Core/Logs/Auth.log")), ("world-console.log.tail", root.join("Core/Logs/world-console.log")), ("mysql-error.log.tail", root.join("mysql/logs/mysql-error.log"))] {
|
||||
|
||||
// Logs. The newest update logs of the repack's own updater are added under their own names.
|
||||
let mut logs: Vec<(String, PathBuf)> = vec![
|
||||
("manager.log".into(), manager_log.to_path_buf()),
|
||||
("manager-install.log".into(), meta_dir.join("logs/manager.log")),
|
||||
("Server.log.tail".into(), root.join("Core/Logs/Server.log")),
|
||||
("Errors.log.tail".into(), root.join("Core/Logs/Errors.log")),
|
||||
("Auth.log.tail".into(), root.join("Core/Logs/Auth.log")),
|
||||
("world-console.log.tail".into(), root.join("Core/Logs/world-console.log")),
|
||||
("CoaBots.log.tail".into(), root.join("Core/Logs/CoaBots.log")),
|
||||
("Playerbots.log.tail".into(), root.join("Core/Logs/Playerbots.log")),
|
||||
("supervisor.log.tail".into(), root.join("Core/Logs/supervisor.log")),
|
||||
("mysql-error.log.tail".into(), root.join("mysql/logs/mysql-error.log")),
|
||||
];
|
||||
let updater_logs = newest_files(&root.join("Core/Logs"), "log", usize::MAX).into_iter().filter(|(p, _, _)| p.file_name().is_some_and(|f| f.to_string_lossy().to_lowercase().starts_with("update-")));
|
||||
for (p, _, _) in updater_logs.take(2) {
|
||||
logs.push((format!("{}.tail", p.file_name().unwrap_or_default().to_string_lossy()), p));
|
||||
}
|
||||
for (name, path) in logs {
|
||||
// A module that reads a missing setting on every tick fills a log with one warning, thousands of times; read far
|
||||
// enough back to see past that, fold the repeats, then keep the last part.
|
||||
let bytes = tail(&path, 8 * 1024 * 1024);
|
||||
@@ -214,9 +373,44 @@ pub fn export_package(root: &Path, meta_dir: &Path, manager_log: &Path, meta: &I
|
||||
let text = squash_repeated_config_warnings(&String::from_utf8_lossy(&bytes));
|
||||
let keep = text.len().saturating_sub(512 * 1024);
|
||||
let start = (keep..text.len()).find(|i| text.is_char_boundary(*i)).unwrap_or(text.len());
|
||||
add(name, redact(&text[start..]).as_bytes())?;
|
||||
add(&name, redact(&text[start..]).as_bytes())?;
|
||||
}
|
||||
}
|
||||
|
||||
// Crash reports of the server (text, and the small dumps next to them), and what Windows recorded for the programs.
|
||||
let crashes = root.join("Core/Crashes");
|
||||
let mut listing = String::new();
|
||||
for (p, len, _) in newest_files(&crashes, "txt", 10) {
|
||||
let name = p.file_name().unwrap_or_default().to_string_lossy().into_owned();
|
||||
listing.push_str(&format!("{name} ({len} bytes)\n"));
|
||||
let text = String::from_utf8_lossy(&tail(&p, 1024 * 1024)).into_owned();
|
||||
add(&format!("crashes/{name}"), redact(&text).as_bytes())?;
|
||||
}
|
||||
for (p, len, _) in newest_files(&crashes, "dmp", 3) {
|
||||
let name = p.file_name().unwrap_or_default().to_string_lossy().into_owned();
|
||||
if len > DUMP_FILE_MAX {
|
||||
listing.push_str(&format!("{name} ({len} bytes) not included: larger than {} MB\n", DUMP_FILE_MAX >> 20));
|
||||
} else if let Ok(bytes) = fs::read(&p) {
|
||||
listing.push_str(&format!("{name} ({len} bytes) included\n"));
|
||||
add(&format!("crashes/{name}"), &bytes)?;
|
||||
}
|
||||
}
|
||||
add("crashes.txt", if listing.is_empty() { "No crash reports in Core/Crashes.".to_string() } else { listing }.as_bytes())?;
|
||||
let events = windows_events();
|
||||
if !events.is_empty() { add("windows-events.txt", events.as_bytes())?; }
|
||||
add("processes.txt", processes_report(root, &ports).as_bytes())?;
|
||||
|
||||
// The newest update journals: the state of each update and the reason it failed.
|
||||
let mut journals: Vec<_> = fs::read_dir(meta_dir.join("updates")).into_iter().flatten().flatten()
|
||||
.filter(|e| e.file_type().is_ok_and(|t| t.is_dir()) && e.file_name().to_string_lossy().chars().all(|c| c.is_ascii_alphanumeric() || matches!(c, '-' | '_')))
|
||||
.collect();
|
||||
journals.sort_by_key(|e| std::cmp::Reverse(e.file_name()));
|
||||
for e in journals.into_iter().take(5) {
|
||||
if let Ok(text) = fs::read_to_string(e.path().join("txn.json")) {
|
||||
add(&format!("updates/{}-txn.json", e.file_name().to_string_lossy()), redact_json(&text).as_bytes())?;
|
||||
}
|
||||
}
|
||||
|
||||
// Which files the server's own configuration folders hold, and the two CoA switches that decide whether the game
|
||||
// client can talk to the world server at all.
|
||||
let mut present = String::new();
|
||||
@@ -244,10 +438,10 @@ pub fn export_package(root: &Path, meta_dir: &Path, manager_log: &Path, meta: &I
|
||||
}
|
||||
}
|
||||
if let Ok(b) = fs::read(root.join("RELEASE.json")) {
|
||||
add("RELEASE.json", redact(&String::from_utf8_lossy(&b)).as_bytes())?;
|
||||
add("RELEASE.json", redact_json(&String::from_utf8_lossy(&b)).as_bytes())?;
|
||||
}
|
||||
if let Ok(b) = fs::read(meta_dir.join("logs/database-checks.json")) {
|
||||
add("database-checks.json", redact(&String::from_utf8_lossy(&b)).as_bytes())?;
|
||||
add("database-checks.json", redact_json(&String::from_utf8_lossy(&b)).as_bytes())?;
|
||||
}
|
||||
zip.finish().map_err(|e| Error::Invalid(e.to_string()))?;
|
||||
Ok(n)
|
||||
@@ -289,6 +483,68 @@ real error
|
||||
assert!(!t.contains("PASS") && !t.contains("abc"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn json_redaction_keeps_the_file_valid_and_hides_the_secrets() {
|
||||
let t = redact_json(r#"{"id":"rev_20261006_token_cache","password":"hunter2","nested":{"apiKey":"k","note":"login with password=abc"},"list":[{"secret":1},"ok"]}"#);
|
||||
let v: serde_json::Value = serde_json::from_str(&t).expect("still JSON");
|
||||
assert_eq!(v["id"], "rev_20261006_token_cache", "an id that merely contains a word is kept");
|
||||
assert_eq!(v["password"], "[redacted]");
|
||||
assert_eq!(v["nested"]["apiKey"], "[redacted]");
|
||||
assert_eq!(v["nested"]["note"], "[redacted]");
|
||||
assert_eq!(v["list"][0]["secret"], "[redacted]");
|
||||
assert_eq!(v["list"][1], "ok");
|
||||
assert!(!t.contains("hunter2") && !t.contains("abc"));
|
||||
assert!(redact_json("not json\nPassword=1").contains("[line removed"), "text falls back to the line rule");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn windows_events_are_filtered_to_the_server_programs() {
|
||||
let listing = "Event[0]:\n Provider Name: Application Error\n Description: Faulting application name: worldserver.exe, version: 0.0.0.0\n\nEvent[1]:\n Provider Name: Application Error\n Description: Faulting application name: notepad.exe\n\nEvent[2]:\n Description: Faulting application name: MYSQLD.EXE\n";
|
||||
let out = filter_event_blocks(listing, &["worldserver", "mysqld"], 10);
|
||||
assert!(out.contains("worldserver.exe") && out.contains("MYSQLD.EXE") && !out.contains("notepad"));
|
||||
assert_eq!(filter_event_blocks(listing, &["worldserver", "mysqld"], 1).matches("Event[").count(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn event_text_loses_the_user_and_computer_lines_and_reads_utf16() {
|
||||
let out = drop_identity_lines("Event[0]\n Source: Application Error\n User: S-1-5-21-1\n User Name: PC\\Dion\n Computer: PC\n Description: worldserver.exe");
|
||||
assert!(out.contains("Source") && out.contains("worldserver.exe"));
|
||||
assert!(!out.contains("S-1-5") && !out.contains("Dion") && !out.contains("Computer"));
|
||||
let mut bytes = vec![0xFF, 0xFE];
|
||||
for u in "Сбой worldserver".encode_utf16() { bytes.extend_from_slice(&u.to_le_bytes()); }
|
||||
assert_eq!(decode_console_output(&bytes), "Сбой worldserver");
|
||||
assert_eq!(decode_console_output(b"plain"), "plain");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_package_carries_crash_reports_update_journals_and_the_process_view() {
|
||||
let d = tempfile::tempdir().unwrap();
|
||||
let root = d.path().join("srv");
|
||||
layout::testkit::fake_repack(&root);
|
||||
fs::create_dir_all(root.join("Core/Crashes")).unwrap();
|
||||
fs::write(root.join("Core/Crashes/567e_worldserver.exe_[4-10_21-25-31].txt"), "Exception code: C0000005\nRCX:0\n").unwrap();
|
||||
fs::write(root.join("Core/Crashes/567e_worldserver.exe_[4-10_21-25-31].dmp"), b"MDMP-small").unwrap();
|
||||
fs::write(root.join("Core/Logs/CoaBots.log"), "bot line\n").unwrap();
|
||||
fs::write(root.join("Core/Logs/update-1.8-20261005.log"), "updater line\n").unwrap();
|
||||
let meta_dir = d.path().join("srv.manager");
|
||||
fs::create_dir_all(meta_dir.join("updates/20261006-082021-0_261006_1-abc")).unwrap();
|
||||
fs::write(meta_dir.join("updates/20261006-082021-0_261006_1-abc/txn.json"), r#"{"state":"rolled-back","message":"Database update 2026_02_24_00 failed: duplicate column"}"#).unwrap();
|
||||
fs::create_dir_all(meta_dir.join("updates/not a journal!")).unwrap();
|
||||
let meta = InstallMeta::new(InstallKind::Imported, &root);
|
||||
let report = run(&root, &meta);
|
||||
let zip_path = d.path().join("diag.zip");
|
||||
export_package(&root, &meta_dir, &d.path().join("none.log"), &meta, &report, &zip_path).unwrap();
|
||||
let mut z = zip::ZipArchive::new(fs::File::open(&zip_path).unwrap()).unwrap();
|
||||
let names: Vec<String> = (0..z.len()).map(|i| z.by_index(i).unwrap().name().to_string()).collect();
|
||||
for want in ["crashes.txt", "processes.txt", "CoaBots.log.tail", "update-1.8-20261005.log.tail", "updates/20261006-082021-0_261006_1-abc-txn.json", "crashes/567e_worldserver.exe_[4-10_21-25-31].txt", "crashes/567e_worldserver.exe_[4-10_21-25-31].dmp"] {
|
||||
assert!(names.iter().any(|n| n == want), "{want} is in the package: {names:?}");
|
||||
}
|
||||
assert!(!names.iter().any(|n| n.contains("not a journal")));
|
||||
let mut listing = String::new();
|
||||
z.by_name("crashes.txt").unwrap().read_to_string(&mut listing).unwrap();
|
||||
assert!(listing.contains("included"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn verify_reports_missing_and_changed_managed_files_only() {
|
||||
let d = tempfile::tempdir().unwrap();
|
||||
|
||||
@@ -37,6 +37,7 @@ pub mod realmlist;
|
||||
pub mod realms;
|
||||
pub mod registry;
|
||||
pub mod release;
|
||||
pub mod report;
|
||||
pub mod release_schema;
|
||||
pub mod update;
|
||||
pub mod upnp;
|
||||
|
||||
@@ -250,6 +250,19 @@ pub fn is_alive(record: &ProcessIdentity) -> bool {
|
||||
identity(record.pid).map(|cur| cur.same_as(record)).unwrap_or(false)
|
||||
}
|
||||
|
||||
/// Every running process whose image file is named one of `names` (compared without case), wherever it lives. Only for
|
||||
/// diagnostics: a process found this way is not trusted to belong to any installation.
|
||||
pub fn find_by_file_names(names: &[&str]) -> Vec<ProcessIdentity> {
|
||||
sys::all_pids()
|
||||
.into_iter()
|
||||
.filter_map(identity)
|
||||
.filter(|p| {
|
||||
let file = p.exe.rsplit(['\\', '/']).next().unwrap_or("");
|
||||
names.iter().any(|n| file.eq_ignore_ascii_case(n))
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Every running process whose image is exactly `exe`.
|
||||
pub fn find_by_exe(exe: &Path) -> Vec<ProcessIdentity> {
|
||||
let want = exe.to_string_lossy().to_lowercase().replace('/', "\\");
|
||||
|
||||
@@ -0,0 +1,116 @@
|
||||
//! Where a problem report goes. A report about the bots goes to the repository of the bot system in question, anything
|
||||
//! else to the Manager's own. The repositories come from the module catalog, so there is one list to keep right.
|
||||
|
||||
use std::path::Path;
|
||||
|
||||
use serde::Serialize;
|
||||
|
||||
pub const MANAGER_REPO: &str = "Corfirean/coa-server-manager";
|
||||
|
||||
/// One place a report can be filed. `id` is what the page sends back; `repo` is `owner/name` on GitHub.
|
||||
#[derive(Debug, Clone, Serialize, PartialEq, Eq)]
|
||||
pub struct Target {
|
||||
pub id: &'static str,
|
||||
pub repo: String,
|
||||
/// The report form asks for the Manager's labels only where we own the repository.
|
||||
pub ours: bool,
|
||||
}
|
||||
|
||||
/// `https://github.com/owner/name/tree/main/x` -> `owner/name`.
|
||||
fn repo_of(url: &str) -> Option<String> {
|
||||
let rest = url.strip_prefix("https://github.com/")?;
|
||||
let mut parts = rest.split('/');
|
||||
let (owner, name) = (parts.next()?, parts.next()?);
|
||||
let ok = |s: &str| !s.is_empty() && s.chars().all(|c| c.is_ascii_alphanumeric() || "._-".contains(c));
|
||||
(ok(owner) && ok(name)).then(|| format!("{owner}/{name}"))
|
||||
}
|
||||
|
||||
fn catalog_repo(id: &str) -> Option<String> {
|
||||
crate::modules::catalog().into_iter().find(|e| e.id == id).and_then(|e| repo_of(&e.repo))
|
||||
}
|
||||
|
||||
/// The three places, in the order the page lists them. A bot system whose repository is unknown falls back to the Manager's.
|
||||
pub fn targets() -> Vec<Target> {
|
||||
let mut v = vec![Target { id: "manager", repo: MANAGER_REPO.into(), ours: true }];
|
||||
for (id, module) in [("companions", "companions"), ("squid", "playerbots")] {
|
||||
if let Some(repo) = catalog_repo(module) {
|
||||
v.push(Target { id, repo: repo.clone(), ours: repo.starts_with("Corfirean/") });
|
||||
}
|
||||
}
|
||||
v
|
||||
}
|
||||
|
||||
pub fn target(id: &str) -> Option<Target> {
|
||||
targets().into_iter().find(|t| t.id == id)
|
||||
}
|
||||
|
||||
/// True for the "new issue" page of one of the targets: exactly that page, optionally with a query.
|
||||
pub fn is_new_issue_url(url: &str) -> bool {
|
||||
targets().iter().any(|t| {
|
||||
let base = format!("https://github.com/{}/issues/new", t.repo);
|
||||
url == base || url.starts_with(&format!("{base}?"))
|
||||
})
|
||||
}
|
||||
|
||||
/// What the report form fills in about the bot systems of this server.
|
||||
#[derive(Debug, Clone, Serialize, PartialEq, Eq)]
|
||||
pub struct Bots {
|
||||
/// The target the form should start with: the bot system that is switched on, else the Manager.
|
||||
pub suggested: &'static str,
|
||||
/// The release of SQUID Playerbots, when it is the one switched on.
|
||||
pub squid_version: Option<String>,
|
||||
}
|
||||
|
||||
pub fn bots(root: &Path) -> Bots {
|
||||
let list = crate::modules::list(root);
|
||||
let on = |id: &str| list.iter().find(|m| m.id == id).filter(|m| m.installed && m.enabled);
|
||||
let squid = on("playerbots");
|
||||
Bots {
|
||||
suggested: if squid.is_some() { "squid" } else if on("companions").is_some() { "companions" } else { "manager" },
|
||||
squid_version: squid.and_then(|m| m.version.clone()).filter(|v| !v.is_empty()),
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn the_three_targets_come_from_the_catalog() {
|
||||
let t = targets();
|
||||
let repo = |id: &str| t.iter().find(|x| x.id == id).map(|x| x.repo.clone());
|
||||
assert_eq!(repo("manager").as_deref(), Some("Corfirean/coa-server-manager"));
|
||||
assert_eq!(repo("companions").as_deref(), Some("Corfirean/mod-coa-playerbots"));
|
||||
assert_eq!(repo("squid").as_deref(), Some("Zyth45/mod-playerbots"));
|
||||
assert!(t.iter().find(|x| x.id == "squid").is_some_and(|x| !x.ours));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn repository_names_are_read_from_module_links() {
|
||||
assert_eq!(repo_of("https://github.com/Corfirean/azerothcore-wotlk-coa/tree/coa-bots/modules/x").as_deref(), Some("Corfirean/azerothcore-wotlk-coa"));
|
||||
assert_eq!(repo_of("https://github.com/Zyth45/mod-playerbots").as_deref(), Some("Zyth45/mod-playerbots"));
|
||||
assert_eq!(repo_of("https://example.com/a/b"), None);
|
||||
assert_eq!(repo_of("https://github.com/a"), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn only_the_new_issue_pages_of_the_targets_are_allowed() {
|
||||
assert!(is_new_issue_url("https://github.com/Zyth45/mod-playerbots/issues/new"));
|
||||
assert!(is_new_issue_url("https://github.com/Corfirean/mod-coa-playerbots/issues/new?title=a&body=b"));
|
||||
assert!(!is_new_issue_url("https://github.com/Zyth45/mod-playerbots/issues/newer"));
|
||||
assert!(!is_new_issue_url("https://github.com/Zyth45/other/issues/new"));
|
||||
assert!(!is_new_issue_url("https://evil.example/Corfirean/coa-server-manager/issues/new"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_suggested_target_follows_the_bot_system_that_is_on() {
|
||||
let d = tempfile::tempdir().unwrap();
|
||||
let root = d.path().join("srv");
|
||||
crate::layout::testkit::fake_repack(&root);
|
||||
let conf = root.join("Core/configs/modules");
|
||||
std::fs::write(conf.join("mod_coa_playerbots.conf"), "CoaBots.Enable = 1\n").unwrap();
|
||||
assert_eq!(bots(&root).suggested, "companions");
|
||||
std::fs::write(conf.join("mod_coa_playerbots.conf"), "CoaBots.Enable = 0\n").unwrap();
|
||||
assert_eq!(bots(&root).suggested, "manager");
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user