From 30d2f56997930605f1fd782f8333646f4215fdf7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=94=D0=BC=D0=B8=D1=82=D1=80=D0=B8=D0=B9?= Date: Fri, 30 Oct 2026 14:04:18 +0500 Subject: [PATCH] Stabilize server lifecycle, client settings and release qualification --- Cargo.lock | 23 +- Cargo.toml | 2 +- .../20261030-account-console-confirmation.md | 7 + .../20261030-close-abandoned-relay-sockets.md | 7 + .../20261030-disabled-client-renderers.md | 7 + .../20261030-force-stop-unresponsive-world.md | 7 + changelog.d/20261030-native-crash-reports.md | 7 + .../20261030-playerbots-overview-count.md | 7 + ...20261030-public-server-browsing-control.md | 7 + ...1030-stop-does-not-trigger-auto-restart.md | 7 + ...261030-wait-for-world-console-readiness.md | 7 + changelog.d/20261030-window-lifecycle.md | 7 + .../coa-core/examples/account_console_e2e.rs | 154 +++++++++++++ .../examples/actual_crash_history_e2e.rs | 11 + .../coa-core/examples/companion_login_e2e.rs | 91 ++++++++ crates/coa-core/examples/crash_history_e2e.rs | 12 + .../examples/force_stop_native_e2e.rs | 90 ++++++++ .../examples/legacy_start_data_e2e.rs | 199 ++++++++++++++++ .../examples/stabilization_schema_probe.rs | 8 + .../examples/stabilization_schema_sync_e2e.rs | 132 +++++++++++ .../examples/stabilization_success_e2e.rs | 166 ++++++++++++++ .../coa-core/examples/update_recovery_e2e.rs | 43 +++- crates/coa-core/src/accounts.rs | 67 ++++++ crates/coa-core/src/client_graphics.rs | 134 +++++++++++ crates/coa-core/src/clientdl.rs | 54 +++++ crates/coa-core/src/control/relay_link.rs | 82 +++++-- crates/coa-core/src/crashes.rs | 79 ++++++- crates/coa-core/src/driver.rs | 73 +++++- crates/coa-core/src/launcher_bridge.py | 50 ++-- crates/coa-core/src/lib.rs | 1 + crates/coa-core/src/migrations.rs | 102 ++++++++- crates/coa-core/src/release.rs | 99 +++++--- crates/coa-core/src/release_schema.rs | 156 ++++++++++++- crates/coa-release/src/main.rs | 3 +- package-lock.json | 4 +- package.json | 2 +- src-tauri/Cargo.toml | 1 + src-tauri/src/browse_preferences.rs | 52 +++++ src-tauri/src/lib.rs | 216 +++++++++++++++--- src-tauri/src/window_preferences.rs | 13 ++ src-tauri/tauri.conf.json | 2 +- src/data/README.md | 8 +- src/data/latest-note-translations.json | 90 +++++++- src/data/server-history.json | 133 +++++++++++ src/dev/mock.ts | 7 + src/i18n/locales/de.ts | 17 ++ src/i18n/locales/en.ts | 16 ++ src/i18n/locales/es.ts | 17 ++ src/i18n/locales/fr.ts | 17 ++ src/i18n/locales/ru.ts | 17 ++ src/i18n/locales/zh.ts | 17 ++ src/lib/api.ts | 3 + src/lib/browse.ts | 2 + src/lib/selfUpdate.ts | 16 +- src/lib/serverLifecycle.ts | 38 +++ src/lib/serverUpdate.ts | 8 + src/screens/BrowsePage.tsx | 18 +- src/screens/ClientCard.tsx | 2 + src/screens/ClientGraphics.tsx | 24 ++ src/screens/ForceStopDialog.tsx | 28 +++ src/screens/Overview.tsx | 42 ++-- src/screens/PlayersPage.tsx | 2 +- src/screens/PublicServerSettings.tsx | 24 ++ src/screens/RemoteClient.tsx | 4 +- src/screens/SettingsHome.tsx | 4 +- src/screens/WindowSettings.tsx | 24 ++ tools/overview-update-error.test.mjs | 5 +- tools/self-update-close.test.mjs | 62 +++++ tools/server-lifecycle.test.mjs | 64 ++++++ tools/server-update-refresh.test.mjs | 1 + tools/test_launcher_bridge.py | 52 +++++ 71 files changed, 2785 insertions(+), 168 deletions(-) create mode 100644 changelog.d/20261030-account-console-confirmation.md create mode 100644 changelog.d/20261030-close-abandoned-relay-sockets.md create mode 100644 changelog.d/20261030-disabled-client-renderers.md create mode 100644 changelog.d/20261030-force-stop-unresponsive-world.md create mode 100644 changelog.d/20261030-native-crash-reports.md create mode 100644 changelog.d/20261030-playerbots-overview-count.md create mode 100644 changelog.d/20261030-public-server-browsing-control.md create mode 100644 changelog.d/20261030-stop-does-not-trigger-auto-restart.md create mode 100644 changelog.d/20261030-wait-for-world-console-readiness.md create mode 100644 changelog.d/20261030-window-lifecycle.md create mode 100644 crates/coa-core/examples/account_console_e2e.rs create mode 100644 crates/coa-core/examples/actual_crash_history_e2e.rs create mode 100644 crates/coa-core/examples/companion_login_e2e.rs create mode 100644 crates/coa-core/examples/crash_history_e2e.rs create mode 100644 crates/coa-core/examples/force_stop_native_e2e.rs create mode 100644 crates/coa-core/examples/legacy_start_data_e2e.rs create mode 100644 crates/coa-core/examples/stabilization_schema_probe.rs create mode 100644 crates/coa-core/examples/stabilization_schema_sync_e2e.rs create mode 100644 crates/coa-core/examples/stabilization_success_e2e.rs create mode 100644 crates/coa-core/src/client_graphics.rs create mode 100644 src-tauri/src/browse_preferences.rs create mode 100644 src-tauri/src/window_preferences.rs create mode 100644 src/lib/serverLifecycle.ts create mode 100644 src/screens/ClientGraphics.tsx create mode 100644 src/screens/ForceStopDialog.tsx create mode 100644 src/screens/PublicServerSettings.tsx create mode 100644 src/screens/WindowSettings.tsx create mode 100644 tools/self-update-close.test.mjs create mode 100644 tools/server-lifecycle.test.mjs diff --git a/Cargo.lock b/Cargo.lock index 9d5dd5b..be35d78 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -586,7 +586,7 @@ dependencies = [ [[package]] name = "coa-core" -version = "0.9.4" +version = "0.9.5" dependencies = [ "base64 0.22.1", "chrono", @@ -634,7 +634,7 @@ dependencies = [ [[package]] name = "coa-release" -version = "0.9.4" +version = "0.9.5" dependencies = [ "chrono", "coa-core", @@ -643,7 +643,7 @@ dependencies = [ [[package]] name = "coa-server-manager" -version = "0.9.4" +version = "0.9.5" dependencies = [ "coa-control-proto", "coa-core", @@ -655,6 +655,7 @@ dependencies = [ "tauri-plugin-dialog", "tauri-plugin-opener", "tauri-plugin-process", + "tauri-plugin-single-instance", "tauri-plugin-updater", "tracing", ] @@ -4606,6 +4607,22 @@ dependencies = [ "tauri-plugin", ] +[[package]] +name = "tauri-plugin-single-instance" +version = "2.5.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "726b6da0dd5bd1344f84f4108a622c07d01923baacb5c803a605189672c5352f" +dependencies = [ + "serde", + "serde_json", + "tauri", + "thiserror 2.0.21", + "tokio", + "tracing", + "windows-sys 0.61.2", + "zbus", +] + [[package]] name = "tauri-plugin-updater" version = "2.13.1" diff --git a/Cargo.toml b/Cargo.toml index 87e7963..1f333c7 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -4,7 +4,7 @@ members = ["crates/coa-core", "crates/coa-release", "crates/coa-registry-proto", exclude = ["services/coa-registry", "services/coa-registry-e2e", "services/coa-coordinator", "services/coa-relay"] [workspace.package] -version = "0.9.4" +version = "0.9.5" edition = "2021" license = "AGPL-3.0-only" diff --git a/changelog.d/20261030-account-console-confirmation.md b/changelog.d/20261030-account-console-confirmation.md new file mode 100644 index 0000000..90fd492 --- /dev/null +++ b/changelog.d/20261030-account-console-confirmation.md @@ -0,0 +1,7 @@ +--- +area: manager +type: fixed +audience: admins +title: Account creation verifies a lost console reply against the requested login +--- +Confirm the requested credentials after a lost reply, block creation during another server action, and explicitly report accounts whose administrator access could not be confirmed. diff --git a/changelog.d/20261030-close-abandoned-relay-sockets.md b/changelog.d/20261030-close-abandoned-relay-sockets.md new file mode 100644 index 0000000..52744ec --- /dev/null +++ b/changelog.d/20261030-close-abandoned-relay-sockets.md @@ -0,0 +1,7 @@ +--- +area: manager +type: fixed +audience: admins +title: Abandoned game relay tunnels close their local connection immediately +--- +Dropping a tunnel shuts down its shared socket directly instead of relying only on a background message, releasing its local read and write connection. diff --git a/changelog.d/20261030-disabled-client-renderers.md b/changelog.d/20261030-disabled-client-renderers.md new file mode 100644 index 0000000..e4d27a5 --- /dev/null +++ b/changelog.d/20261030-disabled-client-renderers.md @@ -0,0 +1,7 @@ +--- +area: manager +type: fixed +audience: admins +title: Keep disabled graphics components disabled during client updates +--- +Client settings can disable DXVK and graphics enhancements. Existing launcher DISABLED files are respected. diff --git a/changelog.d/20261030-force-stop-unresponsive-world.md b/changelog.d/20261030-force-stop-unresponsive-world.md new file mode 100644 index 0000000..ff0a4d2 --- /dev/null +++ b/changelog.d/20261030-force-stop-unresponsive-world.md @@ -0,0 +1,7 @@ +--- +area: manager +type: added +audience: admins +title: Force-stop an unresponsive world after a failed normal shutdown +--- +Confirm the risk of unsaved progress before stopping verified server processes. Shared databases stay running until every owned world has stopped. diff --git a/changelog.d/20261030-native-crash-reports.md b/changelog.d/20261030-native-crash-reports.md new file mode 100644 index 0000000..40c863d --- /dev/null +++ b/changelog.d/20261030-native-crash-reports.md @@ -0,0 +1,7 @@ +--- +area: manager +type: fixed +audience: admins +title: Crash history includes reports from every world and Windows text files +--- +Create and verify the crash report folder before native startup, and include reports from simultaneous worlds and files containing Windows ANSI text. diff --git a/changelog.d/20261030-playerbots-overview-count.md b/changelog.d/20261030-playerbots-overview-count.md new file mode 100644 index 0000000..c2f98e3 --- /dev/null +++ b/changelog.d/20261030-playerbots-overview-count.md @@ -0,0 +1,7 @@ +--- +area: manager +type: fixed +audience: admins +title: Show the online bot count for Playerbots on the overview +--- +The overview displays bot population for both supported bot systems. diff --git a/changelog.d/20261030-public-server-browsing-control.md b/changelog.d/20261030-public-server-browsing-control.md new file mode 100644 index 0000000..720b4ac --- /dev/null +++ b/changelog.d/20261030-public-server-browsing-control.md @@ -0,0 +1,7 @@ +--- +area: manager +type: added +audience: admins +title: Disable public server browsing in Settings +--- +Turn off public server browsing to block catalog list and detail requests. When browsing is enabled, load the list with Refresh. diff --git a/changelog.d/20261030-stop-does-not-trigger-auto-restart.md b/changelog.d/20261030-stop-does-not-trigger-auto-restart.md new file mode 100644 index 0000000..85a1f9a --- /dev/null +++ b/changelog.d/20261030-stop-does-not-trigger-auto-restart.md @@ -0,0 +1,7 @@ +--- +area: manager +type: fixed +audience: admins +title: Keep deliberate stops and update shutdowns from triggering crash restart +--- +Status checks no longer forget a stop request while the world is still shutting down. Update validation and recovery do not trigger automatic crash restarts. diff --git a/changelog.d/20261030-wait-for-world-console-readiness.md b/changelog.d/20261030-wait-for-world-console-readiness.md new file mode 100644 index 0000000..c4b022d --- /dev/null +++ b/changelog.d/20261030-wait-for-world-console-readiness.md @@ -0,0 +1,7 @@ +--- +area: manager +type: fixed +audience: admins +title: Server startup waits for a responsive console before reporting success +--- +An open port no longer marks a loading world as ready. Account creation checks that the console processes commands before sending a create request. diff --git a/changelog.d/20261030-window-lifecycle.md b/changelog.d/20261030-window-lifecycle.md new file mode 100644 index 0000000..6e95463 --- /dev/null +++ b/changelog.d/20261030-window-lifecycle.md @@ -0,0 +1,7 @@ +--- +area: manager +type: fixed +audience: admins +title: Restore the existing Manager window when launching it again +--- +Choose whether closing the window exits the Manager or minimizes it to the tray. Tray actions restore the window on the UI thread. diff --git a/crates/coa-core/examples/account_console_e2e.rs b/crates/coa-core/examples/account_console_e2e.rs new file mode 100644 index 0000000..45a62cd --- /dev/null +++ b/crates/coa-core/examples/account_console_e2e.rs @@ -0,0 +1,154 @@ +use coa_core::{ + db::{Account, Db}, + driver::{self, Verb}, + ra::Ra, + Result, +}; +use std::path::PathBuf; +fn main() -> Result<()> { + let root = PathBuf::from(std::env::args().nth(1).expect("disposable fixture")); + assert!(root + .file_name() + .unwrap() + .to_string_lossy() + .starts_with("coa-update-recovery-fixture-")); + assert!(root.join("recovery-e2e-started").is_file()); + let result = std::panic::catch_unwind(|| -> Result<()> { + let started = driver::run(&root, Verb::StartAll)?; + assert!(started.ok, "{}", started.output); + assert!(root.join("Core/Crashes").is_dir()); + let db = Db::from_repack(&root, Account::Admin)?; + println!("Account acceptance: server started, connecting to RA"); + let mut ra = Ra::connect(&root)?; + println!("Account acceptance: RA authenticated"); + let name = "STABILITYACCT2"; + assert_eq!( + db.query("SELECT COUNT(*) FROM acore_auth.account WHERE username='STABILITYACCT2';")? + .trim(), + "0" + ); + println!("Account acceptance: sending create command"); + coa_core::accounts::create(&root, name, "PrivateTest773", true)?; + println!("Account acceptance: created"); + assert_eq!(db.query("SELECT COUNT(*) FROM acore_auth.account WHERE username='STABILITYACCT2' AND LENGTH(salt)=32 AND LENGTH(verifier)=32;")?.trim(), "1"); + assert!(ra + .create_account(name, "PrivateTest773") + .unwrap_err() + .to_string() + .contains("already taken")); + ra.set_account_password(name, "PrivateTest774")?; + ra.set_account_access(name, 3)?; + assert_eq!(db.query("SELECT gmlevel FROM acore_auth.account_access WHERE id=(SELECT id FROM acore_auth.account WHERE username='STABILITYACCT2');")?.trim(), "3"); + ra.delete_account(name)?; + assert_eq!( + db.query("SELECT COUNT(*) FROM acore_auth.account WHERE username='STABILITYACCT2';")? + .trim(), + "0" + ); + lost_reply(&root, &db)?; + println!("PASS: native RA account create, SRP salt/verifier, duplicate refusal, password change, administrator access and deletion"); + Ok(()) + }); + let stopped = driver::run(&root, Verb::StopAll)?; + assert!(stopped.ok, "{}", stopped.output); + result.map_err(|_| { + coa_core::Error::Invalid("Native account acceptance failed; fixture stopped".into()) + })? +} + +fn lost_reply(root: &std::path::Path, db: &Db) -> Result<()> { + use std::io::{Read, Write}; + use std::net::{TcpListener, TcpStream}; + let path = root.join("Settings/repack.json"); + let original = std::fs::read(&path)?; + struct Restore(std::path::PathBuf, Vec); + impl Drop for Restore { + fn drop(&mut self) { + std::fs::write(&self.0, &self.1).expect("restore disposable fixture settings"); + } + } + let restore = Restore(path.clone(), original.clone()); + let actual = coa_core::layout::read_ports(root).ra; + for (name, forward, ready) in [ + ("STABLOSTREPLY", true, true), + ("STABNOTCREATED", false, true), + ("STABNOTREADY", false, false), + ] { + assert_eq!( + db.query(&format!( + "SELECT COUNT(*) FROM acore_auth.account WHERE username='{name}';" + ))? + .trim(), + "0" + ); + let listener = TcpListener::bind(("127.0.0.1", 0))?; + let mut config: serde_json::Value = serde_json::from_slice(&original)?; + config["raPort"] = listener.local_addr()?.port().into(); + coa_core::fsx::atomic_write_json(&path, &config)?; + let proxy = std::thread::spawn(move || { + fn until(s: &mut TcpStream, marker: &[u8]) -> Vec { + s.set_read_timeout(Some(std::time::Duration::from_secs(30))) + .unwrap(); + let mut bytes = Vec::new(); + let mut byte = [0]; + while !bytes.ends_with(marker) { + s.read_exact(&mut byte).unwrap(); + bytes.push(byte[0]); + } + bytes + } + let (mut client, _) = listener.accept().unwrap(); + let mut server = TcpStream::connect(("127.0.0.1", actual)).unwrap(); + for marker in [b"Username: ".as_slice(), b"Password: ".as_slice()] { + client.write_all(&until(&mut server, marker)).unwrap(); + server.write_all(&until(&mut client, b"\r\n")).unwrap(); + } + client.write_all(&until(&mut server, b"AC>")).unwrap(); + let readiness = until(&mut client, b"\r\n"); + assert_eq!(readiness, b"server info\r\n"); + if !ready { + return; + } + server.write_all(&readiness).unwrap(); + client.write_all(&until(&mut server, b"AC>")).unwrap(); + let command = until(&mut client, b"\r\n"); + if forward { + server.write_all(&command).unwrap(); + let _ = until(&mut server, b"AC>"); + } + }); + let outcome = coa_core::accounts::create(root, name, "PrivateTest773", false); + proxy.join().unwrap(); + std::fs::write(&path, &original)?; + if forward { + outcome?; + assert_eq!( + db.query(&format!( + "SELECT COUNT(*) FROM acore_auth.account WHERE username='{name}';" + ))? + .trim(), + "1" + ); + assert!(coa_core::accounts::create(root, name, "DifferentPass77", false).is_err()); + Ra::connect(root)?.delete_account(name)?; + } else { + assert!(outcome.is_err()); + if !ready { + assert!(outcome + .unwrap_err() + .to_string() + .contains("No create command was sent")); + } + assert_eq!( + db.query(&format!( + "SELECT COUNT(*) FROM acore_auth.account WHERE username='{name}';" + ))? + .trim(), + "0" + ); + } + } + drop(restore); + println!("PASS: a lost native console reply is reconciled by exact SRP credentials; a command that was never executed is rejected"); + Ok(()) +} diff --git a/crates/coa-core/examples/actual_crash_history_e2e.rs b/crates/coa-core/examples/actual_crash_history_e2e.rs new file mode 100644 index 0000000..f690bcb --- /dev/null +++ b/crates/coa-core/examples/actual_crash_history_e2e.rs @@ -0,0 +1,11 @@ +use coa_core::{crashes, Result}; +fn main()->Result<()> { + let root=std::path::PathBuf::from(std::env::args().nth(1).expect("marked native fixture")); + assert!(root.join("recovery-e2e-started").is_file()); + let reports=crashes::list(&root,30)?; + let matching:Vec<_>=reports.iter().filter(|r|r.full_log.contains("AllowableRaces")).collect(); + assert!(!matching.is_empty()); + assert!(matching.iter().all(|r|r.exception_code.as_deref()==Some("C0000420"))); + println!("PASS: Manager discovered {} actual worldserver SQL assertion reports from Core/Crashes, including Windows ANSI text",matching.len()); + Ok(()) +} diff --git a/crates/coa-core/examples/companion_login_e2e.rs b/crates/coa-core/examples/companion_login_e2e.rs new file mode 100644 index 0000000..acc114b --- /dev/null +++ b/crates/coa-core/examples/companion_login_e2e.rs @@ -0,0 +1,91 @@ +use coa_core::{ + db::{Account, Db}, + driver::{self, Verb}, + ra::Ra, + Result, +}; +use std::{ + path::PathBuf, + time::{Duration, Instant}, +}; +fn main() -> Result<()> { + let root = PathBuf::from( + std::env::args() + .nth(1) + .expect("disposable recovery fixture"), + ); + assert!(root + .file_name() + .unwrap() + .to_string_lossy() + .starts_with("coa-update-recovery-fixture-")); + assert!(root.join("recovery-e2e-started").is_file()); + let result = std::panic::catch_unwind(|| -> Result<()> { + let start = driver::run(&root, Verb::StartAll)?; + assert!(start.ok, "{}", start.output); + let db = Db::from_repack(&root, Account::Admin)?; + coa_core::companions::ensure_templates(&db)?; + let mut ra = Ra::connect(&root)?; + let before = coa_core::population::query(&root)?; + assert_eq!(before.bots_online, 0); + let rejected = db.query("SELECT name, at_login FROM acore_characters.characters WHERE guid=3030 AND account IN (SELECT id FROM acore_auth.account WHERE username LIKE 'COABOTHOST%');")?; + assert!(rejected.contains("Christian Shadowheart")); + assert_eq!(rejected.split_whitespace().last(), Some("1")); + println!("Repair reply: {}", ra.run("botcmd spawnbot 3030")?); + let repair_deadline = Instant::now() + Duration::from_secs(60); + loop { + let row = db.query( + "SELECT name, at_login, online FROM acore_characters.characters WHERE guid=3030;", + )?; + if row.trim().ends_with("0\t1") { + assert!(!row.contains("Christian Shadowheart")); + println!("PASS: the exact previously rejected companion was renamed by server validation and logged in"); + break; + } + assert!( + Instant::now() < repair_deadline, + "previously rejected companion logged in" + ); + std::thread::sleep(Duration::from_secs(1)); + } + let _ = ra.despawn_all()?; + let clear_deadline = Instant::now() + Duration::from_secs(30); + while coa_core::population::query(&root)?.bots_online > 0 { + assert!(Instant::now() < clear_deadline); + std::thread::sleep(Duration::from_secs(1)); + } + println!("Spawn reply: {}", ra.spawn_bots(21)?); + let deadline = Instant::now() + Duration::from_secs(180); + loop { + let pop = coa_core::population::query(&root)?; + if pop.bots_online >= 21 { + println!( + "PASS: {} companions logged in; real players={}", + pop.bots_online, pop.players_online + ); + break; + } + if Instant::now() > deadline { + return Err(coa_core::Error::Invalid(format!( + "Only {} of 21 companion logins completed", + pop.bots_online + ))); + } + std::thread::sleep(Duration::from_secs(2)); + } + let _ = ra.cancel_spawning()?; + let _ = ra.despawn_all()?; + let deadline = Instant::now() + Duration::from_secs(30); + while coa_core::population::query(&root)?.bots_online > 0 { + assert!(Instant::now() < deadline, "companions despawned"); + std::thread::sleep(Duration::from_secs(1)); + } + println!("PASS: companion despawn completed"); + Ok(()) + }); + let stopped = driver::run(&root, Verb::StopAll)?; + assert!(stopped.ok, "{}", stopped.output); + result.map_err(|_| { + coa_core::Error::Invalid("Companion native acceptance panicked; fixture stopped".into()) + })? +} diff --git a/crates/coa-core/examples/crash_history_e2e.rs b/crates/coa-core/examples/crash_history_e2e.rs new file mode 100644 index 0000000..f141cbb --- /dev/null +++ b/crates/coa-core/examples/crash_history_e2e.rs @@ -0,0 +1,12 @@ +use coa_core::{crashes, Result}; +fn main() -> Result<()> { + let root = std::path::PathBuf::from(std::env::args().nth(1).expect("native crash evidence")); + assert!(root.join(".crash-report-evidence").is_file()); + let reports = crashes::list(&root, 10)?; + assert_eq!(reports.len(), 1); + assert_eq!(reports[0].exception_code.as_deref(), Some("C0000005")); + assert_eq!(reports[0].category, "access_violation"); + assert!(!reports[0].full_log.is_empty()); + println!("PASS: Manager crash history discovers and classifies the actual native handler report from Core/Crashes"); + Ok(()) +} diff --git a/crates/coa-core/examples/force_stop_native_e2e.rs b/crates/coa-core/examples/force_stop_native_e2e.rs new file mode 100644 index 0000000..c401e71 --- /dev/null +++ b/crates/coa-core/examples/force_stop_native_e2e.rs @@ -0,0 +1,90 @@ +use coa_core::{driver, fsx, process, Result}; +#[cfg(windows)] +use std::os::windows::process::CommandExt; +use std::{ + path::Path, + process::{Child, Command, Stdio}, +}; + +struct OwnedChild(Child); +impl Drop for OwnedChild { + fn drop(&mut self) { + let _ = self.0.kill(); + let _ = self.0.wait(); + } +} +fn copy_tree(source: &Path, target: &Path) -> Result<()> { + std::fs::create_dir_all(target)?; + for entry in std::fs::read_dir(source)? { + let entry = entry?; + let destination = target.join(entry.file_name()); + if entry.file_type()?.is_dir() { + copy_tree(&entry.path(), &destination)?; + } else { + std::fs::copy(entry.path(), destination)?; + } + } + Ok(()) +} +fn spawn(path: &Path) -> OwnedChild { + let mut cmd = Command::new(path); + cmd.args(["-t", "127.0.0.1"]) + .stdin(Stdio::null()) + .stdout(Stdio::null()) + .stderr(Stdio::null()); + #[cfg(windows)] + cmd.creation_flags(0x0800_0000); + OwnedChild(cmd.spawn().unwrap()) +} +fn main() -> Result<()> { + assert!(cfg!(windows)); + let source = std::path::PathBuf::from( + std::env::args() + .nth(1) + .expect("marked disposable runtime source"), + ); + assert_eq!( + std::fs::read(source.join(".release-schema-fixture"))?, + b"disposable release-schema fixture" + ); + let temp = tempfile::tempdir()?; + let root = temp.path(); + copy_tree(&source.join("Runtime"), &root.join("Runtime"))?; + std::fs::create_dir_all(root.join("Core"))?; + std::fs::create_dir_all(root.join("Scripts"))?; + let system = + std::path::PathBuf::from(std::env::var_os("SystemRoot").unwrap()).join("System32/ping.exe"); + std::fs::copy(&system, root.join("Core/worldserver.exe"))?; + std::fs::copy(&system, root.join("foreign.exe"))?; + let mut ports = Vec::new(); + let mut listeners = Vec::new(); + for _ in 0..4 { + let listener = std::net::TcpListener::bind("127.0.0.1:0")?; + ports.push(listener.local_addr()?.port()); + listeners.push(listener); + } + let config = serde_json::json!({"mysqlPort":ports[0],"authPort":ports[1],"worldPort":ports[2],"raPort":ports[3],"raUsername":"fixture","raPassword":"fixture"}); + fsx::atomic_write_json(&root.join("Settings/repack.json"), &config)?; + drop(listeners); + let mut launcher = std::fs::read_to_string(source.join("Scripts/manage.py"))?; + launcher.push_str("\nfrom contextlib import nullcontext\ndef control_lock(): return nullcontext()\ndef stop_all(config):\n assert not process('world'), 'world must stop before database'\n (ROOT/'database-stage').write_text('safe')\n"); + fsx::atomic_write(&root.join("Scripts/manage.py"), launcher.as_bytes())?; + let mut foreign = spawn(&root.join("foreign.exe")); + let foreign_identity = process::identity(foreign.0.id()).unwrap(); + fsx::atomic_write_json(&root.join(".state/world.json"), &foreign_identity)?; + let rejected = driver::force_stop(root)?; + assert!(!rejected.ok, "a foreign world record must be rejected"); + assert!(!root.join("database-stage").exists()); + assert!(foreign.0.try_wait()?.is_none()); + let mut owned = spawn(&root.join("Core/worldserver.exe")); + let stopped = driver::force_stop(root)?; + assert!(stopped.ok, "{}", stopped.output); + assert!(owned.0.try_wait()?.is_some()); + assert!( + foreign.0.try_wait()?.is_none(), + "foreign process was untouched" + ); + assert_eq!(std::fs::read(root.join("database-stage"))?, b"safe"); + println!("PASS: native Windows forced-stop rejects foreign records, recovers the exact owned world identity, stops it before the database stage, and leaves the foreign process alive"); + Ok(()) +} diff --git a/crates/coa-core/examples/legacy_start_data_e2e.rs b/crates/coa-core/examples/legacy_start_data_e2e.rs new file mode 100644 index 0000000..2542795 --- /dev/null +++ b/crates/coa-core/examples/legacy_start_data_e2e.rs @@ -0,0 +1,199 @@ +use base64::{engine::general_purpose::STANDARD, Engine}; +use coa_core::{ + backup, + db::Db, + driver::{self, Verb}, + fsx, + manifest::{Kind, Migration}, + package::{self, BuildOptions}, + pkgsource::Source, + registry::MetaDir, + update::{self, RepackEnv}, + Result, +}; +use ed25519_dalek::{Signer, SigningKey}; +use std::{collections::BTreeMap, path::PathBuf}; +fn main() -> Result<()> { + let root = PathBuf::from( + std::env::args() + .nth(1) + .expect("qualified disposable fixture"), + ); + let sql = std::fs::read(std::env::args().nth(2).expect("corrective SQL"))?; + assert_eq!( + root.file_name().unwrap(), + "coa-schema-fixture-stability-upgrade-76-85-20261030" + ); + assert!(root.join(".release-schema-fixture").is_file()); + assert!(!root.join("legacy-start-data-e2e-started").exists()); + fsx::atomic_write( + &root.join("legacy-start-data-e2e-started"), + b"disposable regression test", + )?; + let result = std::panic::catch_unwind(|| -> Result<()> { + let meta = coa_core::registry::metadata_dir_for(&root)?; + let mut identities = String::new(); + let mut custom = String::new(); + backup::with_database(&root, |db| { + assert_eq!( + db.query( + "SELECT COUNT(*) FROM acore_world.playercreateinfo WHERE race IN (33,45);" + )? + .trim(), + "0" + ); + let base: u32 = db + .query("SELECT MAX(guid)+100 FROM acore_characters.characters;")? + .trim() + .parse() + .unwrap(); + clone_character(db, base, 33, 12, "Thinprobe")?; + clone_character(db, base + 1, 45, 30, "Leperprobe")?; + identities = db.query(&format!( + "SELECT * FROM acore_characters.characters WHERE guid IN ({base},{});", + base + 1 + ))?; + let missing = coa_core::character_start_check::missing(db)?; + assert!(missing + .iter() + .any(|c| c.guid == base && c.race == 33 && c.class == 12)); + assert!(missing + .iter() + .any(|c| c.guid == base + 1 && c.race == 45 && c.class == 30)); + db.query("INSERT INTO acore_world.playercreateinfo SELECT 33,class,map,zone,position_x+0.125,position_y,position_z,orientation FROM acore_world.playercreateinfo WHERE race=1 AND class=32;")?; + custom = + db.query("SELECT * FROM acore_world.playercreateinfo WHERE race=33 AND class=32;")?; + fsx::atomic_write( + &root.join("legacy-probe-guids.json"), + serde_json::to_string(&[base, base + 1])?.as_bytes(), + )?; + println!("PASS: reproduced missing starting data for existing race 33/class 12 and race 45/class 30 characters"); + Ok(()) + })?; + let source = root.join("legacy-start-data-source"); + let pkg = root.join("legacy-start-data-package"); + fsx::atomic_write( + &source.join("Core/legacy-start-data-proof.txt"), + b"corrective migration acceptance", + )?; + fsx::atomic_write( + &source.join("_migrations/world/stabilization_legacy_starts.sql"), + &sql, + )?; + let manifest = package::build( + &source, + &pkg, + &BuildOptions { + kind: Kind::Update, + version: "2.0.0".into(), + core_commit: None, + bots_commit: None, + built_at: "private regression acceptance".into(), + part_size: 1 << 20, + migrations: vec![Migration { + id: "stabilization_legacy_starts".into(), + db: "world".into(), + sha256: fsx::sha256_bytes(&sql), + compatible_sha256: vec![], + destructive: false, + }], + }, + &|_| {}, + )?; + let key = SigningKey::generate(&mut rand_core::OsRng); + fsx::atomic_write( + &pkg.join("manifest.json.sig"), + STANDARD + .encode( + key.sign(&std::fs::read(pkg.join("manifest.json"))?) + .to_bytes(), + ) + .as_bytes(), + )?; + let trusted = STANDARD.encode(key.verifying_key().to_bytes()); + let env = RepackEnv { + root: &root, + meta_dir: &meta, + }; + let out = update::apply( + &update::Params { + root: &root, + meta_dir: &meta, + source: Source::Dir(pkg), + trusted_key: &trusted, + cancel: Default::default(), + resolutions: BTreeMap::new(), + env: &env, + fail_after_ops: None, + }, + &|step, pct| println!("{pct}% {step}"), + )?; + assert_eq!(out.txn.state, update::State::Committed); + assert_eq!( + MetaDir::open(&meta)?.1.core.version.as_deref(), + Some("2.0.0") + ); + backup::with_database(&root, |db| { + let guids: Vec = + serde_json::from_slice(&std::fs::read(root.join("legacy-probe-guids.json"))?)?; + assert_eq!( + db.query(&format!( + "SELECT * FROM acore_characters.characters WHERE guid IN ({},{});", + guids[0], guids[1] + ))?, + identities + ); + assert!(coa_core::character_start_check::missing(db)? + .iter() + .all(|c| !guids.contains(&c.guid))); + assert_eq!( + db.query("SELECT * FROM acore_world.playercreateinfo WHERE race=33 AND class=32;")?, + custom + ); + assert!(coa_core::migrations::status(db, &manifest.migrations)? + .iter() + .all(|m| m.status == coa_core::migrations::Status::Applied)); + let before = counts(db)?; + db.query(&format!( + "USE acore_world; {}", + String::from_utf8_lossy(&sql) + ))?; + assert_eq!(counts(db)?, before); + assert_eq!( + db.query("SELECT * FROM acore_world.playercreateinfo WHERE race=33 AND class=32;")?, + custom + ); + println!("PASS: signed Manager update restored legacy starts, preserved complete character rows and custom starts, and remained idempotent on a second SQL execution"); + Ok(()) + })?; + Ok(()) + }); + let stopped = driver::run(&root, Verb::StopAll)?; + assert!(stopped.ok, "{}", stopped.output); + result.map_err(|_| { + coa_core::Error::Invalid("Legacy start regression failed; fixture stopped".into()) + })? +} +fn counts(db: &Db) -> Result { + db.query("SELECT COUNT(*) FROM acore_world.playercreateinfo WHERE race IN (33,45); SELECT COUNT(*) FROM acore_world.playercreateinfo_item WHERE race IN (33,45); SELECT COUNT(*) FROM acore_world.playercreateinfo_action WHERE race IN (33,45); SELECT COUNT(*) FROM acore_world.player_race_stats WHERE Race IN (33,45); SELECT COUNT(*) FROM acore_world.ascension_custom_class_race WHERE race IN (33,45);") +} +fn clone_character(db: &Db, guid: u32, race: u32, class: u32, name: &str) -> Result<()> { + let columns = db.query("SHOW COLUMNS FROM acore_characters.characters;")?; + let names: Vec<_> = columns + .lines() + .map(|l| l.split('\t').next().unwrap()) + .collect(); + let values: Vec = names + .iter() + .map(|c| match *c { + "guid" => guid.to_string(), + "name" => format!("'{name}'"), + "race" => race.to_string(), + "class" => class.to_string(), + "online" | "at_login" => "0".into(), + _ => format!("`{c}`"), + }) + .collect(); + db.query(&format!("INSERT INTO acore_characters.characters ({}) SELECT {} FROM acore_characters.characters WHERE class={class} LIMIT 1;",names.iter().map(|c|format!("`{c}`")).collect::>().join(","),values.join(",")))?; + Ok(()) +} diff --git a/crates/coa-core/examples/stabilization_schema_probe.rs b/crates/coa-core/examples/stabilization_schema_probe.rs new file mode 100644 index 0000000..24b90a8 --- /dev/null +++ b/crates/coa-core/examples/stabilization_schema_probe.rs @@ -0,0 +1,8 @@ +use coa_core::{backup, schema_check, Result}; +fn main()->Result<()> { + let root=std::path::PathBuf::from(std::env::args().nth(1).unwrap()); + let contract=std::path::PathBuf::from(std::env::args().nth(2).unwrap()); + assert!(root.join("recovery-e2e-started").is_file()); + assert!(contract.join(".release-schema-fixture").is_file()); + backup::with_database(&root,|db| {for p in schema_check::check(db,&contract)? {println!("{}.{}.{}: {}",p.database,p.table,p.column,p.detail);} Ok(())}) +} diff --git a/crates/coa-core/examples/stabilization_schema_sync_e2e.rs b/crates/coa-core/examples/stabilization_schema_sync_e2e.rs new file mode 100644 index 0000000..a9c843e --- /dev/null +++ b/crates/coa-core/examples/stabilization_schema_sync_e2e.rs @@ -0,0 +1,132 @@ +use base64::{engine::general_purpose::STANDARD, Engine}; +use coa_core::{ + backup, + driver::{self, Verb}, + fsx, + manifest::{Kind, Migration}, + package::{self, BuildOptions}, + pkgsource::Source, + update::{self, RepackEnv}, + Result, +}; +use ed25519_dalek::{Signer, SigningKey}; +use std::{collections::BTreeMap, path::PathBuf}; +fn main() -> Result<()> { + let root = PathBuf::from(std::env::args().nth(1).unwrap()); + let core = PathBuf::from(std::env::args().nth(2).unwrap()); + let release = PathBuf::from(std::env::args().nth(3).unwrap()); + assert!(root.join("recovery-e2e-started").is_file()); + let result = std::panic::catch_unwind(|| -> Result<()> { + let meta = coa_core::registry::metadata_dir_for(&root)?; + let source = root.join("schema-sync-source-v2"); + let pkg = root.join("schema-sync-package-v2"); + assert!(!pkg.exists()); + fsx::atomic_write( + &source.join("Core/schema-sync-proof.txt"), + b"official schema migration acceptance", + )?; + let published = + coa_core::manifest::Manifest::parse(&std::fs::read(release.join("manifest.json"))?)?; + let contract_path = PathBuf::from("C:/games/source/coa-schema-fixture-stability-upgrade-76-85-20261030/Scripts/database-schema.json"); + let contract = std::fs::read(contract_path)?; + let expected = published + .files + .iter() + .find(|f| f.path == "Scripts/database-schema.json") + .unwrap(); + assert_eq!(fsx::sha256_bytes(&contract), expected.sha256); + fsx::atomic_write(&source.join("Scripts/database-schema.json"), &contract)?; + let mut migrations: Vec = Vec::new(); + for id in [ + "rev_1793212891571528600", + "rev_20261027_18_coa_strange_piece_of_scrap_faction_diamond", + ] { + let m = published + .migrations + .iter() + .find(|m| m.id == id) + .unwrap() + .clone(); + let sql = std::fs::read( + core.join(format!("data/sql/updates/pending_db_{}/{}.sql", m.db, m.id)), + )?; + assert_eq!(fsx::sha256_bytes(&sql), m.sha256); + fsx::atomic_write( + &source.join(format!("_migrations/{}/{}.sql", m.db, m.id)), + &sql, + )?; + migrations.push(m); + } + package::build( + &source, + &pkg, + &BuildOptions { + kind: Kind::Update, + version: "3.0.0".into(), + core_commit: None, + bots_commit: None, + built_at: "private native fixture schema sync".into(), + part_size: 1 << 20, + migrations, + }, + &|_| {}, + )?; + let key = SigningKey::generate(&mut rand_core::OsRng); + fsx::atomic_write( + &pkg.join("manifest.json.sig"), + STANDARD + .encode( + key.sign(&std::fs::read(pkg.join("manifest.json"))?) + .to_bytes(), + ) + .as_bytes(), + )?; + let trusted = STANDARD.encode(key.verifying_key().to_bytes()); + let env = RepackEnv { + root: &root, + meta_dir: &meta, + }; + let out = update::apply( + &update::Params { + root: &root, + meta_dir: &meta, + source: Source::Dir(pkg), + trusted_key: &trusted, + cancel: Default::default(), + resolutions: BTreeMap::from([( + "Scripts/database-schema.json".into(), + update::Resolution::Replace, + )]), + env: &env, + fail_after_ops: None, + }, + &|step, pct| println!("{pct}% {step}"), + )?; + assert_eq!(out.txn.state, update::State::Committed); + backup::with_database(&root, |db| { + assert_eq!( + db.query("SELECT name,at_login FROM acore_characters.characters WHERE guid=3030;")? + .trim(), + "Christian Shadowheart\t1" + ); + assert_eq!( + db.query("SELECT id FROM acore_characters.manager_recovery_probe;")? + .trim(), + "42" + ); + assert_eq!( + db.query("SELECT id FROM acore_world.manager_recovery_probe;")? + .trim(), + "44" + ); + Ok(()) + })?; + println!("PASS: the exact two published migrations brought the old fixture schema forward through the Manager updater while preserving the rejected companion and recovery probes"); + Ok(()) + }); + let stop = driver::run(&root, Verb::StopAll)?; + assert!(stop.ok, "{}", stop.output); + result.map_err(|_| { + coa_core::Error::Invalid("Schema sync acceptance failed; fixture stopped".into()) + })? +} diff --git a/crates/coa-core/examples/stabilization_success_e2e.rs b/crates/coa-core/examples/stabilization_success_e2e.rs new file mode 100644 index 0000000..0aebc87 --- /dev/null +++ b/crates/coa-core/examples/stabilization_success_e2e.rs @@ -0,0 +1,166 @@ +use base64::{engine::general_purpose::STANDARD, Engine}; +use coa_core::{ + backup, driver, fsx, + manifest::{Kind, Migration}, + package::{self, BuildOptions}, + pkgsource::Source, + registry::MetaDir, + update::{self, RepackEnv}, + Result, +}; +use ed25519_dalek::{Signer, SigningKey}; +use std::{collections::BTreeMap, path::PathBuf}; + +fn main() -> Result<()> { + let root = PathBuf::from( + std::env::args() + .nth(1) + .expect("disposable recovery fixture"), + ); + assert!(root + .file_name() + .unwrap() + .to_string_lossy() + .starts_with("coa-update-recovery-fixture-")); + assert!(root.join("recovery-e2e-started").is_file()); + let cycles_only = std::env::args().nth(2).as_deref() == Some("--cycles-only"); + if !cycles_only { + assert!(!root.join("success-e2e-started").exists()); + fsx::atomic_write( + &root.join("success-e2e-started"), + b"disposable success acceptance", + )?; + } + let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { + if cycles_only { + restart_cycles(&root) + } else { + exercise(&root) + } + })); + assert!( + driver::run(&root, driver::Verb::StopAll)?.ok, + "fixture shutdown" + ); + result.map_err(|_| { + coa_core::Error::Invalid( + "Success acceptance assertion failed; fixture services stopped".into(), + ) + })? +} + +fn exercise(root: &std::path::Path) -> Result<()> { + let meta = coa_core::registry::metadata_dir_for(root)?; + assert!(update::unfinished(&meta).is_none()); + assert!(driver::run(root, driver::Verb::StopAll)?.ok); + let source = root.join("success-source"); + let pkg = root.join("success-package"); + fsx::atomic_write( + &source.join("Core/stabilization-success.txt"), + b"verified update", + )?; + let sql = b"UPDATE manager_recovery_probe SET id=44 WHERE id=43;"; + fsx::atomic_write( + &source.join("_migrations/world/stabilization_success.sql"), + sql, + )?; + let manifest = package::build( + &source, + &pkg, + &BuildOptions { + kind: Kind::Update, + version: "2.0.0".into(), + core_commit: None, + bots_commit: None, + built_at: "disposable acceptance".into(), + part_size: 1 << 20, + migrations: vec![Migration { + id: "stabilization_success".into(), + db: "world".into(), + sha256: fsx::sha256_bytes(sql), + compatible_sha256: vec![], + destructive: false, + }], + }, + &|_| {}, + )?; + let key = SigningKey::generate(&mut rand_core::OsRng); + fsx::atomic_write( + &pkg.join("manifest.json.sig"), + STANDARD + .encode( + key.sign(&std::fs::read(pkg.join("manifest.json"))?) + .to_bytes(), + ) + .as_bytes(), + )?; + let trusted = STANDARD.encode(key.verifying_key().to_bytes()); + let env = RepackEnv { + root, + meta_dir: &meta, + }; + let outcome = update::apply( + &update::Params { + root, + meta_dir: &meta, + source: Source::Dir(pkg), + trusted_key: &trusted, + cancel: Default::default(), + resolutions: BTreeMap::new(), + env: &env, + fail_after_ops: None, + }, + &|step, pct| println!("{pct}% {step}"), + )?; + assert_eq!(outcome.txn.state, update::State::Committed); + assert_eq!( + MetaDir::open(&meta)?.1.core.version.as_deref(), + Some("2.0.0") + ); + assert!(update::unfinished(&meta).is_none()); + assert_eq!( + std::fs::read(root.join("Core/stabilization-success.txt"))?, + b"verified update" + ); + backup::with_database(root, |db| { + assert_eq!( + db.query("SELECT id FROM acore_characters.manager_recovery_probe;")?, + "42" + ); + assert_eq!( + db.query("SELECT id FROM acore_characters.manager_recovery_view;")?, + "42" + ); + assert_eq!( + db.query("SELECT id FROM acore_world.manager_recovery_probe;")?, + "44" + ); + assert!(coa_core::migrations::status(db, &manifest.migrations)? + .iter() + .all(|m| m.status == coa_core::migrations::Status::Applied)); + Ok(()) + })?; + restart_cycles(root)?; + println!("PASS: signed update committed after failed rehearsal and recovery; SQL, files, metadata and player data verified; two native restart cycles passed"); + Ok(()) +} + +fn restart_cycles(root: &std::path::Path) -> Result<()> { + for cycle in 0..2 { + let stopped = driver::run(root, driver::Verb::StopAll)?; + assert!( + stopped.ok, + "Stop cycle {cycle}: {}", + coa_core::diag::redact(&stopped.output) + ); + let started = driver::run(root, driver::Verb::StartAll)?; + assert!(started.ok, "{}", started.output); + let pop = coa_core::population::query(root)?; + println!( + "Restart cycle {cycle}: world ready, players={}, bots={}", + pop.players_online, pop.bots_online + ); + } + println!("PASS: two native restart cycles finished"); + Ok(()) +} diff --git a/crates/coa-core/examples/update_recovery_e2e.rs b/crates/coa-core/examples/update_recovery_e2e.rs index 6c4f693..05ce404 100644 --- a/crates/coa-core/examples/update_recovery_e2e.rs +++ b/crates/coa-core/examples/update_recovery_e2e.rs @@ -30,15 +30,27 @@ fn main() -> Result<()> { .unwrap() .to_string_lossy() .starts_with("coa-update-recovery-fixture-")); - assert!( - !root.join("recovery-e2e-started").exists(), - "Use a new fixture; never reuse an owned server" - ); - fsx::atomic_write(&root.join("recovery-e2e-started"), b"disposable fixture")?; - let result = exercise(&root); - let stopped = driver::run(&root, Verb::StopAll)?; - assert!(stopped.ok); - result + let resume = std::env::args().nth(2).as_deref() == Some("--verify-recovered"); + let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { + if resume { + assert!(root.join("recovery-e2e-started").is_file()); + let manifest = coa_core::manifest::Manifest::parse(&std::fs::read( + root.join("fixture-package/manifest.json"), + )?)?; + verify_recovered(&root, &manifest) + } else { + assert!( + !root.join("recovery-e2e-started").exists(), + "Use a new fixture" + ); + fsx::atomic_write(&root.join("recovery-e2e-started"), b"disposable fixture")?; + exercise(&root) + } + })); + assert!(driver::run(&root, Verb::StopAll)?.ok); + result.map_err(|_| { + Error::Invalid("Recovery acceptance assertion failed; owned services were stopped".into()) + })? } fn exercise(root: &Path) -> Result<()> { @@ -122,9 +134,18 @@ fn exercise(root: &Path) -> Result<()> { assert!( error .to_string() - .contains("private update rehearsal failed"), + .contains("files and databases were restored to the recovery point"), "{error}" ); + verify_recovered(root, &manifest) +} + +fn verify_recovered(root: &Path, manifest: &coa_core::manifest::Manifest) -> Result<()> { + let meta = coa_core::registry::metadata_dir_for(root)?; + let env = RepackEnv { + root, + meta_dir: &meta, + }; assert!(!root.join("Core/recovery-probe.txt").exists()); assert!(update::unfinished(&meta).is_none()); assert_eq!( @@ -168,6 +189,6 @@ fn exercise(root: &Path) -> Result<()> { Db::from_repack(root, Account::Admin)?.realm(), coa_core::realms::Mode::Coa ); - println!("PASS: private rehearsal caught failed SQL before changing the installed world, characters, ledger, objects, files or version; complete recovery succeeded"); + println!("PASS: failed SQL was rolled back; characters, world, ledger, views, triggers, routines, files and version were verified; the saved recovery point was restored again"); Ok(()) } diff --git a/crates/coa-core/src/accounts.rs b/crates/coa-core/src/accounts.rs index 462d3de..be8213e 100644 --- a/crates/coa-core/src/accounts.rs +++ b/crates/coa-core/src/accounts.rs @@ -80,6 +80,60 @@ fn upper(name: &str) -> Result { Ok(name.to_ascii_uppercase()) } +pub fn create(root: &Path, name: &str, password: &str, administrator: bool) -> Result<()> { + validate_account(name, password)?; + let name = name.to_ascii_uppercase(); + let db = Db::from_repack(root, Account::Admin)?; + if db + .query(&format!( + "SELECT COUNT(*) FROM acore_auth.account WHERE username='{name}';" + ))? + .trim() + != "0" + { + return Err(Error::Invalid("That account name is already taken.".into())); + } + let mut ra = Ra::connect(root)?; + ra.performance().map_err(|error| Error::Invalid(format!("The server console is not ready for account creation. No create command was sent. {error}")))?; + let confirmed = ra.create_account(&name, password); + if let Err(error) = confirmed { + let stored = db.query(&format!( + "SELECT HEX(salt), HEX(verifier) FROM acore_auth.account WHERE username='{name}';" + ))?; + if !matches_credentials(&stored, &name, password) { + return Err(Error::Invalid(format!("Account creation was not confirmed. Refresh the account list before retrying. {error}"))); + } + if administrator { + ra = Ra::connect(root).map_err(|error| Error::Invalid(format!("The account was created, but administrator access was not confirmed. Refresh the account list and check its access level. {error}")))?; + } + } + if administrator { + if let Err(error) = ra.make_administrator(&name) { + let access = db.query(&format!("SELECT COUNT(*) FROM acore_auth.account_access WHERE id=(SELECT id FROM acore_auth.account WHERE username='{name}') AND gmlevel=3 AND RealmID=-1;"))?; + if access.trim() != "1" { + return Err(Error::Invalid(format!("The account was created, but administrator access was not confirmed. Refresh the account list and check its access level. {error}"))); + } + } + } + Ok(()) +} + +fn matches_credentials(stored: &str, name: &str, password: &str) -> bool { + let Some((salt, verifier)) = stored.trim().split_once('\t') else { + return false; + }; + let Ok(salt) = hex::decode(salt) else { + return false; + }; + let Ok(salt): std::result::Result<[u8; 32], _> = salt.try_into() else { + return false; + }; + let Ok(verifier) = hex::decode(verifier) else { + return false; + }; + verifier.as_slice() == crate::srp6::verifier(name, password, &salt) +} + /// Give the account a new name. Needs the world console (the new password is what makes the login work again) and an /// account that is not logged in. The old name is put back if anything goes wrong. pub fn rename(root: &Path, ra: &mut Ra, old: &str, new: &str, password: &str) -> Result<()> { @@ -165,6 +219,19 @@ pub fn delete(root: &Path, ra: &mut Ra, name: &str) -> Result<()> { mod tests { use super::*; + #[test] + fn lost_reply_requires_the_exact_requested_credentials() { + let salt = [42; 32]; + let verifier = crate::srp6::verifier("NewPlayer", "Password77", &salt); + let stored = format!("{}\t{}\n", hex::encode(salt), hex::encode(verifier)); + assert!(matches_credentials(&stored, "NEWPLAYER", "password77")); + assert!(!matches_credentials(&stored, "NEWPLAYER", "wrongpass")); + assert!(!matches_credentials(&stored, "OTHERPLAYER", "Password77")); + for value in ["", "NULL\tNULL", "00\t00", "malformed"] { + assert!(!matches_credentials(value, "NewPlayer", "Password77")); + } + } + #[test] fn rows_from_the_client_become_accounts() { let out = "2\tALICE\t3\t0\t2026-09-30 21:04:11\t4\n5\tBOB\t0\t1\t\t0\n7\tBROKEN\n"; diff --git a/crates/coa-core/src/client_graphics.rs b/crates/coa-core/src/client_graphics.rs new file mode 100644 index 0000000..06e87ac --- /dev/null +++ b/crates/coa-core/src/client_graphics.rs @@ -0,0 +1,134 @@ +use crate::{fsx, Error, Result}; +use serde::{Deserialize, Serialize}; +use std::{fs, path::Path}; + +#[derive(Default, Serialize, Deserialize)] +pub struct Graphics { + pub dxvk_disabled: bool, + pub enhancements_disabled: bool, +} + +fn preferences(client: &Path) -> Result> { + match fs::read(client.join(".coa-manager/graphics.json")) { + Ok(bytes) => Ok(Some(serde_json::from_slice(&bytes)?)), + Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(None), + Err(e) => Err(e.into()), + } +} + +pub fn status(client: &Path) -> Result { + let saved = preferences(client)?.unwrap_or_default(); + let actual = |name: &str, remembered: bool| -> Result { + let active = client.join(name).is_file(); + let inactive = client.join(format!("{name}.DISABLED")).is_file(); + if active && inactive { + return Err(Error::Invalid( + "Both enabled and disabled renderer files exist.".into(), + )); + } + Ok(inactive || (!active && remembered)) + }; + Ok(Graphics { + dxvk_disabled: actual("d3d9.dll", saved.dxvk_disabled)?, + enhancements_disabled: actual("dxgi.dll", saved.enhancements_disabled)?, + }) +} + +pub fn disabled(client: &Path, path: &str) -> Result { + let name = path.to_ascii_lowercase(); + if !matches!(name.as_str(), "d3d9.dll" | "dxgi.dll") { + return Ok(false); + } + let state = status(client)?; + Ok(if name == "d3d9.dll" { + state.dxvk_disabled + } else { + state.enhancements_disabled + }) +} + +pub fn set(client: &Path, name: &str, disabled: bool) -> Result { + if !matches!(name, "d3d9.dll" | "dxgi.dll") { + return Err(Error::Invalid("Unknown graphics setting.".into())); + } + if crate::client::is_running(client) { + return Err(Error::Invalid( + "Close the game before changing graphics settings.".into(), + )); + } + let active = fsx::safe_join(client, name)?; + let inactive = fsx::safe_join(client, &format!("{name}.DISABLED"))?; + if active.exists() && inactive.exists() { + return Err(Error::Invalid("Both enabled and disabled renderer files exist. Resolve the conflict before changing graphics settings.".into())); + } + let mut state = status(client)?; + if name == "d3d9.dll" { + state.dxvk_disabled = disabled; + } else { + state.enhancements_disabled = disabled; + } + let (source, target) = if disabled { + (&active, &inactive) + } else { + (&inactive, &active) + }; + // The no-clobber link also preserves an existing destination if another app changes the setting. + if source.is_file() { + if let Err(error) = fs::hard_link(source, target) { + if error.kind() == std::io::ErrorKind::AlreadyExists { + return Err(error.into()); + } + let mut output = fs::OpenOptions::new() + .write(true) + .create_new(true) + .open(target)?; + let copied = std::fs::File::open(source) + .and_then(|mut input| std::io::copy(&mut input, &mut output)) + .and_then(|_| output.sync_all()); + drop(output); + if let Err(error) = copied { + let _ = fs::remove_file(target); + return Err(error.into()); + } + } + if let Err(error) = fs::remove_file(source) { + let _ = fs::remove_file(target); + return Err(error.into()); + } + } + fsx::atomic_write_json(&client.join(".coa-manager/graphics.json"), &state)?; + Ok(state) +} + +#[cfg(test)] +mod tests { + use super::*; + #[test] + fn toggles_preserve_bytes_and_refuse_conflicts() { + let dir = tempfile::tempdir().unwrap(); + let root = dir.path(); + fs::write(root.join("d3d9.dll"), b"custom renderer").unwrap(); + assert!(set(root, "d3d9.dll", true).unwrap().dxvk_disabled); + assert!(!root.join("d3d9.dll").exists()); + assert_eq!( + fs::read(root.join("d3d9.dll.DISABLED")).unwrap(), + b"custom renderer" + ); + assert!(!set(root, "d3d9.dll", false).unwrap().dxvk_disabled); + fs::write(root.join("d3d9.dll.DISABLED"), b"other").unwrap(); + assert!(set(root, "d3d9.dll", false).is_err()); + assert_eq!(fs::read(root.join("d3d9.dll")).unwrap(), b"custom renderer"); + assert_eq!(fs::read(root.join("d3d9.dll.DISABLED")).unwrap(), b"other"); + } + + #[test] + fn remembers_missing_wrapper_and_imports_launcher_marker() { + let dir = tempfile::tempdir().unwrap(); + let root = dir.path(); + assert!(set(root, "d3d9.dll", true).unwrap().dxvk_disabled); + assert!(disabled(root, "d3d9.dll").unwrap()); + fs::write(root.join("dxgi.dll.DISABLED"), b"launcher disabled").unwrap(); + assert!(disabled(root, "dxgi.dll").unwrap()); + assert!(!disabled(root, "Data/d3d9.dll").unwrap()); + } +} diff --git a/crates/coa-core/src/clientdl.rs b/crates/coa-core/src/clientdl.rs index e605f73..2bd43f6 100644 --- a/crates/coa-core/src/clientdl.rs +++ b/crates/coa-core/src/clientdl.rs @@ -299,6 +299,11 @@ pub fn plan( bytes_per_sec: 0, file: Some(f.path.clone()), }); + if crate::client_graphics::disabled(client, &f.path)? { + kept += 1; + done += f.size; + continue; + } let path = fsx::safe_join(client, &f.path)?; let meta = match fs::metadata(&path) { Ok(meta) if meta.is_file() => meta, @@ -440,6 +445,9 @@ pub fn apply(a: &Apply, on_step: &dyn Fn(Step)) -> Result<()> { let mut todo = Vec::new(); for item in &a.plan.items { + if crate::client_graphics::disabled(a.client, &item.path)? { + continue; + } if item.kind == Kind::Modified && a.keep_modified { let path = fsx::safe_join(a.client, &item.path)?; let meta = fs::metadata(&path)?; @@ -777,6 +785,52 @@ mod tests { ); } + #[test] + fn disabled_launcher_renderers_are_never_restored_even_with_a_stale_plan() { + let dir = tempfile::tempdir().unwrap(); + let files: Vec<(&str, &[u8])> = vec![("d3d9.dll", b"dxvk"), ("dxgi.dll", b"enhancements")]; + let manifest = manifest("v1", &files); + let cancel = Cancel::default(); + let old_plan = plan(dir.path(), &manifest, &State::default(), &cancel, &|_| {}).unwrap(); + fs::write(dir.path().join("d3d9.dll.DISABLED"), b"custom disabled").unwrap(); + crate::client_graphics::set(dir.path(), "dxgi.dll", true).unwrap(); + let server = Server::new(&files); + apply( + &Apply { + client: dir.path(), + manifest: &manifest, + plan: &old_plan, + keep_modified: false, + transport: &server, + objects_url: "https://x.invalid/objects", + cancel: &cancel, + }, + &|_| {}, + ) + .unwrap(); + assert!(server.requested.lock().unwrap().is_empty()); + assert!(!dir.path().join("d3d9.dll").exists()); + assert!(!dir.path().join("dxgi.dll").exists()); + assert_eq!( + fs::read(dir.path().join("d3d9.dll.DISABLED")).unwrap(), + b"custom disabled" + ); + let after = plan( + dir.path(), + &manifest, + &load_state(dir.path()).unwrap(), + &cancel, + &|_| {}, + ) + .unwrap(); + assert!(after.items.is_empty()); + crate::client_graphics::set(dir.path(), "d3d9.dll", false).unwrap(); + assert_eq!( + fs::read(dir.path().join("d3d9.dll")).unwrap(), + b"custom disabled" + ); + } + #[test] fn renderer_files_configs_and_everything_not_in_the_manifest_survive_an_update_untouched() { let d = tempfile::tempdir().unwrap(); diff --git a/crates/coa-core/src/control/relay_link.rs b/crates/coa-core/src/control/relay_link.rs index 31f8622..ccd6a64 100644 --- a/crates/coa-core/src/control/relay_link.rs +++ b/crates/coa-core/src/control/relay_link.rs @@ -214,11 +214,13 @@ fn run( struct StreamWorker { tx: Sender, reset_on_drop: bool, + shutdown: Arc, } impl Drop for StreamWorker { fn drop(&mut self) { if self.reset_on_drop { + let _ = self.shutdown.shutdown(std::net::Shutdown::Both); let _ = self.tx.send(TunnelMsg::Reset { stream_id: 0 }); } } @@ -388,6 +390,8 @@ fn session( }; match TcpStream::connect(("127.0.0.1", local_port)) { Ok(tcp) => { + let tcp = Arc::new(tcp); + let shutdown = tcp.clone(); let (stream_tx, stream_rx) = channel::(); let ws_tx = ws_out_tx.clone(); @@ -398,6 +402,7 @@ fn session( StreamWorker { tx: stream_tx, reset_on_drop: true, + shutdown, }, ); @@ -456,19 +461,20 @@ fn session( fn spawn_local_tcp_bridge( stream_id: u32, - mut tcp: TcpStream, + tcp: Arc, from_tunnel: Receiver, to_tunnel: Sender, ) { let _ = tcp.set_nonblocking(false); let _ = tcp.set_nodelay(true); - let mut tcp_read = tcp.try_clone().expect("tcp clone"); + let tcp_read = tcp.clone(); let to_tunnel_read = to_tunnel.clone(); // Local TCP read -> to tunnel std::thread::Builder::new() .name(format!("relay-stream-{stream_id}-read")) .spawn(move || { + let mut tcp_read = tcp_read.as_ref(); let mut buf = [0u8; 16384]; loop { match tcp_read.read(&mut buf) { @@ -498,11 +504,12 @@ fn spawn_local_tcp_bridge( std::thread::Builder::new() .name(format!("relay-stream-{stream_id}-write")) .spawn(move || { + let mut tcp_write = tcp.as_ref(); while let Ok(msg) = from_tunnel.recv() { match msg { TunnelMsg::Data { chunk, .. } => { if let Ok(data) = base64::engine::general_purpose::STANDARD.decode(&chunk) { - if tcp.write_all(&data).is_err() { + if tcp_write.write_all(&data).is_err() { break; } } @@ -608,22 +615,71 @@ mod tests { } #[test] - fn dropping_a_tunnel_closes_its_local_tcp_stream() { + fn local_tunnel_exchanges_data_in_both_directions_before_reset() { let listener = TcpListener::bind("127.0.0.1:0").unwrap(); - let tcp = TcpStream::connect(listener.local_addr().unwrap()).unwrap(); + let tcp = Arc::new(TcpStream::connect(listener.local_addr().unwrap()).unwrap()); + let shutdown = tcp.clone(); let (mut peer, _) = listener.accept().unwrap(); peer.set_read_timeout(Some(Duration::from_secs(3))).unwrap(); let (tx, rx) = channel(); - let (out, _) = channel(); - spawn_local_tcp_bridge(7, tcp, rx, out); - drop(StreamWorker { + let (out, replies) = channel(); + spawn_local_tcp_bridge(8, tcp, rx, out); + let worker = StreamWorker { tx, reset_on_drop: true, - }); - match peer.read(&mut [0u8; 1]) { - Ok(0) => {}, - Err(error) if matches!(error.kind(), std::io::ErrorKind::ConnectionReset | std::io::ErrorKind::ConnectionAborted) => {}, - other => panic!("The abandoned relay stream must close, got {other:?}"), + shutdown, + }; + worker + .tx + .send(TunnelMsg::Data { + stream_id: 8, + chunk: base64::engine::general_purpose::STANDARD.encode(b"request"), + }) + .unwrap(); + let mut request = [0; 7]; + peer.read_exact(&mut request).unwrap(); + assert_eq!(&request, b"request"); + peer.write_all(b"response").unwrap(); + let mut response = Vec::new(); + while response.len() < 8 { + match replies.recv_timeout(Duration::from_secs(3)).unwrap() { + TunnelMsg::Data { chunk, .. } => response.extend( + base64::engine::general_purpose::STANDARD + .decode(chunk) + .unwrap(), + ), + other => panic!("Expected the local reply, got {other:?}"), + } + } + assert_eq!(response, b"response"); + drop(worker); + } + + #[test] + fn dropping_a_tunnel_closes_its_local_tcp_stream() { + for _ in 0..32 { + let listener = TcpListener::bind("127.0.0.1:0").unwrap(); + let tcp = Arc::new(TcpStream::connect(listener.local_addr().unwrap()).unwrap()); + let shutdown = tcp.clone(); + let (mut peer, _) = listener.accept().unwrap(); + peer.set_read_timeout(Some(Duration::from_secs(3))).unwrap(); + let (tx, rx) = channel(); + let (out, _) = channel(); + spawn_local_tcp_bridge(7, tcp, rx, out); + drop(StreamWorker { + tx, + reset_on_drop: true, + shutdown, + }); + match peer.read(&mut [0u8; 1]) { + Ok(0) => {} + Err(error) + if matches!( + error.kind(), + std::io::ErrorKind::ConnectionReset | std::io::ErrorKind::ConnectionAborted + ) => {} + other => panic!("The abandoned relay stream must close, got {other:?}"), + } } } } diff --git a/crates/coa-core/src/crashes.rs b/crates/coa-core/src/crashes.rs index 7c80be7..4f4deff 100644 --- a/crates/coa-core/src/crashes.rs +++ b/crates/coa-core/src/crashes.rs @@ -24,17 +24,25 @@ pub struct CrashItem { /// Lists recent crash reports from `Core/Crashes`, sorted newest first. pub fn list(root: &Path, limit: usize) -> Result> { - let dir = root.join("Core/Crashes"); + let mut roots = vec![root.to_path_buf()]; + roots.extend(crate::multiworld::Tree::ALL.map(|tree| crate::multiworld::tree_root(root, tree))); let mut files: Vec<(PathBuf, SystemTime)> = Vec::new(); - if let Ok(entries) = fs::read_dir(&dir) { - for entry in entries.flatten() { - let path = entry.path(); - if path.is_file() && path.extension().and_then(|e| e.to_str()) == Some("txt") { - let mtime = entry - .metadata() - .and_then(|m| m.modified()) - .unwrap_or(SystemTime::UNIX_EPOCH); - files.push((path, mtime)); + for world_root in roots { + let entries = match fs::read_dir(world_root.join("Core/Crashes")) { + Ok(entries) => Some(entries), + Err(e) if e.kind() == std::io::ErrorKind::NotFound => None, + Err(e) => return Err(e.into()), + }; + if let Some(entries) = entries { + for entry in entries.flatten() { + let path = entry.path(); + if path.is_file() && path.extension().and_then(|e| e.to_str()) == Some("txt") { + let mtime = entry + .metadata() + .and_then(|m| m.modified()) + .unwrap_or(SystemTime::UNIX_EPOCH); + files.push((path, mtime)); + } } } } @@ -43,8 +51,12 @@ pub fn list(root: &Path, limit: usize) -> Result> { let mut items = Vec::new(); for (path, mtime) in files { - if let Ok(content) = fs::read_to_string(&path) { - let item = parse_crash_content(&path, mtime, &content); + if let Ok(bytes) = fs::read(&path) { + let content = String::from_utf8_lossy(&bytes); + let mut item = parse_crash_content(&path, mtime, &content); + if let Ok(relative) = path.strip_prefix(root) { + item.id = relative.to_string_lossy().replace('\\', "/"); + } items.push(item); } } @@ -237,6 +249,49 @@ fn explain( mod tests { use super::*; + #[test] + fn discovers_native_ansi_reports_and_ignores_dump_files() { + let root = tempfile::tempdir().unwrap(); + assert!(list(root.path(), 10).unwrap().is_empty()); + fs::create_dir_all(root.path().join("Core/Crashes")).unwrap(); + fs::write( + root.path().join("Core/Crashes/report.txt"), + b"Exception code: C0000005 \xff\r\n", + ) + .unwrap(); + fs::write(root.path().join("Core/Crashes/report.dmp"), b"binary").unwrap(); + let reports = list(root.path(), 10).unwrap(); + assert_eq!(reports.len(), 1); + assert_eq!(reports[0].exception_code.as_deref(), Some("C0000005")); + } + + #[test] + fn discovers_reports_from_all_worlds_without_filename_collisions() { + let root = tempfile::tempdir().unwrap(); + for relative in [ + "Core/Crashes", + ".realms/secondary/Core/Crashes", + ".realms/reborn/Core/Crashes", + ] { + fs::create_dir_all(root.path().join(relative)).unwrap(); + fs::write( + root.path().join(relative).join("same.txt"), + b"Exception code: C0000005", + ) + .unwrap(); + } + let reports = list(root.path(), 10).unwrap(); + assert_eq!(reports.len(), 3); + assert_eq!( + reports + .iter() + .map(|r| &r.id) + .collect::>() + .len(), + 3 + ); + } + #[test] fn parses_assertion_report() { let report = r#"Revision: AzerothCore rev. df5bcdf26092 2026-10-02 22:08:42 +0500 (coa-bots branch) (Win64, RelWithDebInfo, Static) diff --git a/crates/coa-core/src/driver.rs b/crates/coa-core/src/driver.rs index 7e0eabd..9226085 100644 --- a/crates/coa-core/src/driver.rs +++ b/crates/coa-core/src/driver.rs @@ -103,7 +103,69 @@ pub(crate) fn validate_update(root: &Path) -> Result { run_inner(root, Verb::StartAll, true) } +pub fn force_stop(root: &Path) -> Result { + if crate::docker::is_docker(root) { + return Err(Error::Invalid( + "Forced shutdown is only available for Windows repacks.".into(), + )); + } + for tree in crate::multiworld::Tree::ALL { + let path = crate::multiworld::tree_root(root, tree); + if crate::multiworld::tree_running(root, tree) + || !crate::process::find_by_exe(&path.join("Core/worldserver.exe")).is_empty() + { + let child = fsx::ensure_within(root, &path)?; + let out = run_inner_mode(&child, Verb::StopAll, false, true)?; + if !out.ok || crate::multiworld::tree_running(root, tree) { + return Err(Error::Invalid(format!( + "An extra world could not stop; the shared database was left running. {}", + out.output + ))); + } + } + } + run_inner_mode(root, Verb::StopAll, false, true) +} + +fn recover_world_for_forced_stop(root: &Path) -> Result<()> { + let worlds = crate::process::find_by_exe(&root.join("Core/worldserver.exe")); + if worlds.len() > 1 { + return Err(Error::Invalid( + "More than one world process belongs to this folder; its database was left running." + .into(), + )); + } + if let Some(world) = worlds.first() { + if !crate::process::is_alive(world) { + return Err(Error::Invalid( + "The world process identity changed; retry the stop.".into(), + )); + } + if crate::process::read_state_record(root, "world") + .is_none_or(|saved| !saved.same_as(world)) + { + let record = root.join(".state/world.json"); + let previous = root.join(".state/world-before-forced-stop-recovery.json"); + if record.is_file() && !previous.exists() { + fsx::atomic_write(&previous, &std::fs::read(&record)?)?; + } + fsx::atomic_write_json(&record, world)?; + tracing::warn!(pid = world.pid, root = %root.display(), "Recovered owned world identity before an explicitly requested forced stop"); + } + } + Ok(()) +} + fn run_inner(root: &Path, verb: Verb, validating_update: bool) -> Result { + run_inner_mode(root, verb, validating_update, false) +} + +fn run_inner_mode( + root: &Path, + verb: Verb, + validating_update: bool, + force: bool, +) -> Result { let root = fsx::canonicalize_lenient(root)?; let _update_lock = if !validating_update && matches!(verb, Verb::StartAll | Verb::StartWorld) { Some(crate::update::operation_lock_for( @@ -124,7 +186,7 @@ fn run_inner(root: &Path, verb: Verb, validating_update: bool) -> Result Result Result<()> { if !matches!(verb, Verb::StartAll | Verb::StartWorld) { return Ok(()); } + std::fs::create_dir_all(root.join("Core/Crashes"))?; + let probe = tempfile::NamedTempFile::new_in(root.join("Core/Crashes"))?; + probe.close()?; for relative in [ "Settings/worldserver.conf.template", "Core/configs/worldserver.conf", @@ -575,6 +643,7 @@ mod tests { let folder = tempfile::tempdir().unwrap(); let root = folder.path(); prepare_headless_world(root, Verb::StartAll).unwrap(); + assert!(root.join("Core/Crashes").is_dir()); std::fs::create_dir_all(root.join("Core/configs")).unwrap(); let path = root.join("Core/configs/worldserver.conf"); for original in [ diff --git a/crates/coa-core/src/launcher_bridge.py b/crates/coa-core/src/launcher_bridge.py index e31d47c..3c003a1 100644 --- a/crates/coa-core/src/launcher_bridge.py +++ b/crates/coa-core/src/launcher_bridge.py @@ -25,14 +25,25 @@ def wait_ready(name, port, seconds=180): launcher["start_mysql"].__globals__["wait_ready"] = wait_ready -if sys.argv[1] == "stop-all": +if sys.argv[1] in ("stop-all", "force-stop-all"): shutdown = launcher["stop_all"].__globals__ + class UnsafeShutdown(Exception): + pass + + def stop_owned_world(world): + expected = Path(script).resolve().parents[1] / "Core" / "worldserver.exe" + if Path(world.get("exe", "")) != expected or not shutdown["same_process"](world): + raise UnsafeShutdown("World process ownership could not be verified; the database was left running.") + try: + shutdown["terminate"](world) + except (OSError, RuntimeError) as error: + raise UnsafeShutdown("Worldserver could not be stopped safely; its database was left running.") from error + if not shutdown["wait_stopped"](world, 90): + raise UnsafeShutdown("Worldserver is still stopping; its database was left running.") + if "ra" in shutdown: original_ra = shutdown["ra"] - class UnsafeShutdown(Exception): - pass - def shutdown_command(command, config): try: return original_ra(command, config) @@ -42,20 +53,33 @@ if sys.argv[1] == "stop-all": world = shutdown["process"]("world") if not world: return "Worldserver has already stopped." - expected = Path(script).resolve().parents[1] / "Core" / "worldserver.exe" - if Path(world.get("exe", "")) != expected or not shutdown["same_process"](world): - raise UnsafeShutdown("World process ownership could not be verified; the database was left running.") - try: - shutdown["terminate"](world) - except (OSError, RuntimeError) as error: - raise UnsafeShutdown("Worldserver could not be stopped safely; its database was left running.") from error - if not shutdown["wait_stopped"](world, 90): - raise UnsafeShutdown("Worldserver is still stopping; its database was left running.") + stop_owned_world(world) return "Stopped this server's recorded world process without its unavailable console." shutdown["ra"] = shutdown_command config = launcher["settings"]() with launcher["control_lock"](): + if sys.argv[1] == "force-stop-all": + world = shutdown["process"]("world") + if world: + stop_owned_world(world) + print("Force-stopped this server's verified world process; unsaved progress may be lost.", flush=True) launcher["stop_all"](config) else: launcher["main"]() + if sys.argv[1] in ("start-all", "start-world"): + config = launcher["settings"]() + deadline = world_deadline if world_deadline is not None else time.monotonic() + 1500 + last_error = None + while time.monotonic() < deadline: + if not launcher["process"]("world"): + raise RuntimeError("World startup failed: worldserver stopped before its console accepted commands.") + try: + launcher["ra"]("server info", config) + print("World console is accepting commands.", flush=True) + break + except (OSError, RuntimeError) as error: + last_error = error + time.sleep(0.5) + else: + raise RuntimeError(f"World startup failed: its console is still starting. {last_error}") diff --git a/crates/coa-core/src/lib.rs b/crates/coa-core/src/lib.rs index dbb2975..7857525 100644 --- a/crates/coa-core/src/lib.rs +++ b/crates/coa-core/src/lib.rs @@ -14,6 +14,7 @@ pub mod channels; pub mod character_start_check; pub mod cleanbase; pub mod client; +pub mod client_graphics; pub mod clientdl; pub mod companions; pub mod config; diff --git a/crates/coa-core/src/migrations.rs b/crates/coa-core/src/migrations.rs index a6b3a23..05008cf 100644 --- a/crates/coa-core/src/migrations.rs +++ b/crates/coa-core/src/migrations.rs @@ -307,6 +307,51 @@ pub struct Item { pub error: Option, } +#[derive(Debug, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct Audit { + pub total: usize, + pub applied: usize, + pub checksum_verified: usize, + pub legacy_unknown: usize, +} + +pub fn inventory_sha256(list: &[Migration]) -> Result { + let inventory: Vec<_> = list + .iter() + .map(|m| (&m.db, &m.id, &m.sha256, &m.compatible_sha256, m.destructive)) + .collect(); + Ok(fsx::sha256_bytes(&serde_json::to_vec(&inventory)?)) +} + +pub fn audit_applied(store: &dyn Store, list: &[Migration]) -> Result { + let rows = store.load_readonly()?; + check_history(&rows, list)?; + let mut audit = Audit { + total: list.len(), + applied: 0, + checksum_verified: 0, + legacy_unknown: 0, + }; + for migration in list { + let row = recorded(&rows, migration) + .filter(|r| r.status == Status::Applied) + .ok_or_else(|| { + Error::Invalid(format!( + "Release migration {} ({}) is not recorded as applied.", + migration.id, migration.db + )) + })?; + audit.applied += 1; + if row.sha256 == "0".repeat(64) { + audit.legacy_unknown += 1; + } else { + audit.checksum_verified += 1; + } + } + Ok(audit) +} + pub fn status(store: &dyn Store, list: &[Migration]) -> Result> { let rows = store.load()?; Ok(list @@ -358,7 +403,7 @@ fn preserve_auth_history(store: &dyn Store, rows: &[LedgerRow], list: &[Migratio } /// Migrations that were published with different bytes but have the same effect, so a server that applied either -/// version accepts the other. The Wildcard table repair went out as `c1d8…` (0.261005.0, 0.261006.1) and as `9e4a…` +/// version accepts the other. The Wildcard table repair went out as `c1d8…` (0.261005.0, 0.261006.1) and as `9e4a…` /// (0.261005.22, 0.261007.24); the packages carry no list of compatible versions, so the Manager knows this pair. const SAME_EFFECT: &[(&str, &[&str])] = &[( "manager_repair__20261005_missing_wildcard_tables", @@ -667,6 +712,61 @@ mod tests { } } + #[test] + fn qualification_inventory_digest_matches_release_pipeline_encoding() { + let list = vec![Migration { + id: "one".into(), + db: "world".into(), + sha256: "a".repeat(64), + compatible_sha256: vec![], + destructive: false, + }]; + assert_eq!( + inventory_sha256(&list).unwrap(), + "b35e45f666304500e69ff352f83103910075ace998afb7915b548765b8c30703" + ); + } + + #[test] + fn qualification_rejects_missing_interrupted_failed_and_changed_history() { + let (_dir, list) = setup(&[("world", "qualification_probe", "SELECT 1;")]); + let store = Mem::default(); + assert!(audit_applied(&store, &list).is_err()); + for status in [Status::Running, Status::Failed, Status::Pending] { + store + .put(&LedgerRow { + db: "world".into(), + id: list[0].id.clone(), + sha256: list[0].sha256.clone(), + status, + error: None, + baseline: false, + }) + .unwrap(); + assert!(audit_applied(&store, &list).is_err()); + } + store + .put(&LedgerRow { + db: "world".into(), + id: list[0].id.clone(), + sha256: "a".repeat(64), + status: Status::Applied, + error: None, + baseline: false, + }) + .unwrap(); + assert!(audit_applied(&store, &list).is_err()); + store.rows.borrow_mut()[0].sha256 = list[0].sha256.clone(); + assert_eq!(audit_applied(&store, &list).unwrap().checksum_verified, 1); + store.rows.borrow_mut()[0].sha256 = "0".repeat(64); + let audit = audit_applied(&store, &list).unwrap(); + assert_eq!( + (audit.applied, audit.checksum_verified, audit.legacy_unknown), + (1, 0, 1) + ); + assert!(store.ran.borrow().is_empty()); + } + fn setup(files: &[(&str, &str, &str)]) -> (tempfile::TempDir, Vec) { let d = tempfile::tempdir().unwrap(); let mut list = Vec::new(); diff --git a/crates/coa-core/src/release.rs b/crates/coa-core/src/release.rs index 906cf3c..5fe7506 100644 --- a/crates/coa-core/src/release.rs +++ b/crates/coa-core/src/release.rs @@ -21,22 +21,33 @@ pub struct SqlFile { pub sha256: String, } -fn sql_in(dir: &Path) -> Vec { - let mut v: Vec = fs::read_dir(dir) - .map(|rd| { - rd.flatten() - .map(|e| e.path()) - .filter(|p| p.extension().map(|e| e == "sql").unwrap_or(false)) - .collect() - }) - .unwrap_or_default(); - v.sort(); - v +fn entries(dir: &Path) -> Result> { + match fs::read_dir(dir) { + Ok(rd) => Ok(rd.collect::>>()?), + Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(vec![]), + Err(error) => Err(error.into()), + } +} + +fn sql_in(dir: &Path) -> Result> { + let mut paths: Vec<_> = entries(dir)? + .into_iter() + .map(|entry| entry.path()) + .filter(|path| path.extension().is_some_and(|ext| ext == "sql")) + .collect(); + paths.sort(); + Ok(paths) } /// The order in which files were first added to the repository (a pending script may rely on a table a module /// created earlier). Files git does not know come last, in name order. -fn introduction_rank(repo: &Path, pathspecs: &[&str]) -> std::collections::HashMap { +fn introduction_rank( + repo: &Path, + pathspecs: &[&str], +) -> Result> { + if !repo.join(".git").exists() { + return Ok(Default::default()); + } let mut args = vec![ "log", "--full-history", @@ -48,18 +59,22 @@ fn introduction_rank(repo: &Path, pathspecs: &[&str]) -> std::collections::HashM "--", ]; args.extend_from_slice(pathspecs); - let out = Command::new("git").current_dir(repo).args(&args).output(); - let mut rank = std::collections::HashMap::new(); - if let Ok(o) = out { - for (i, line) in String::from_utf8_lossy(&o.stdout) - .lines() - .filter(|l| l.ends_with(".sql")) - .enumerate() - { - rank.entry(line.to_string()).or_insert(i); - } + let out = Command::new("git").current_dir(repo).args(&args).output()?; + if !out.status.success() { + return Err(Error::Invalid(format!( + "Cannot establish SQL migration order: {}", + String::from_utf8_lossy(&out.stderr) + ))); } - rank + let mut rank = std::collections::HashMap::new(); + for (i, line) in String::from_utf8_lossy(&out.stdout) + .lines() + .filter(|line| line.ends_with(".sql")) + .enumerate() + { + rank.entry(line.to_string()).or_insert(i); + } + Ok(rank) } /// Incremental SQL of a core checkout. Installation-only module bases must never be replayed on a live database. @@ -91,7 +106,7 @@ fn collect_core_sql_mode(core: &Path, include_base: bool) -> Result ("world", ["db_world", "pending_db_world"]), ] { for d in dirs { - for f in sql_in(&core.join("data/sql/updates").join(d)) { + for f in sql_in(&core.join("data/sql/updates").join(d))? { let stem = f.file_stem().unwrap().to_string_lossy().into_owned(); let rel = format!( "data/sql/updates/{d}/{}", @@ -101,8 +116,8 @@ fn collect_core_sql_mode(core: &Path, include_base: bool) -> Result } } } - if let Ok(rd) = fs::read_dir(core.join("modules")) { - let mut mods: Vec<_> = rd.flatten().collect(); + { + let mut mods = entries(&core.join("modules"))?; mods.sort_by_key(|e| e.file_name()); for m in mods { let name = m.file_name().to_string_lossy().into_owned(); @@ -110,7 +125,7 @@ fn collect_core_sql_mode(core: &Path, include_base: bool) -> Result for kind in ["auth", "characters", "world"] { let base = m.path().join(format!("data/sql/db-{kind}")); for f in if include_base { - sql_in(&base.join("base")) + sql_in(&base.join("base"))? } else { vec![] } { @@ -121,7 +136,7 @@ fn collect_core_sql_mode(core: &Path, include_base: bool) -> Result ); push(kind, format!("mod_{mname}__base__{stem}"), f, rel)?; } - for f in sql_in(&base) { + for f in sql_in(&base)? { let stem = f.file_stem().unwrap().to_string_lossy().into_owned(); let rel = format!( "modules/{name}/data/sql/db-{kind}/{}", @@ -132,7 +147,7 @@ fn collect_core_sql_mode(core: &Path, include_base: bool) -> Result } } } - let rank = introduction_rank(core, &["data/sql/updates", "modules"]); + let rank = introduction_rank(core, &["data/sql/updates", "modules"])?; out.sort_by_key(|f| rank.get(&f.origin).copied().unwrap_or(usize::MAX)); Ok(out) } @@ -155,7 +170,7 @@ pub fn export_baseline(server: &Path, out: &Path) -> Result> /// SQL a bots module checkout ships for the characters database (its `dist/sql`). pub fn collect_bots_sql(bots: &Path) -> Result> { let mut out = Vec::new(); - for f in sql_in(&bots.join("dist/sql")) { + for f in sql_in(&bots.join("dist/sql"))? { let stem = f.file_stem().unwrap().to_string_lossy().into_owned(); out.push(SqlFile { db: "characters".into(), @@ -364,6 +379,30 @@ mod tests { fs::write(p, c).unwrap(); } + #[test] + fn sql_collection_rejects_broken_history_in_a_git_checkout() { + let dir = tempfile::tempdir().unwrap(); + write(dir.path(), ".git", "gitdir: missing-history"); + write(dir.path(), "data/sql/updates/db_world/one.sql", "SELECT 1;"); + assert!(collect_core_sql(dir.path()) + .unwrap_err() + .to_string() + .contains("migration order")); + } + + #[test] + fn sql_collection_rejects_unreadable_directories_instead_of_omitting_migrations() { + let dir = tempfile::tempdir().unwrap(); + write(dir.path(), "data/sql/updates/db_world", "not a directory"); + assert!(collect_core_sql(dir.path()).is_err()); + let bots = tempfile::tempdir().unwrap(); + write(bots.path(), "dist/sql", "not a directory"); + assert!(collect_bots_sql(bots.path()).is_err()); + let modules = tempfile::tempdir().unwrap(); + write(modules.path(), "modules", "not a directory"); + assert!(collect_core_sql(modules.path()).is_err()); + } + #[test] fn collects_core_and_module_sql_with_module_base_first_and_stable_ids() { let d = tempfile::tempdir().unwrap(); diff --git a/crates/coa-core/src/release_schema.rs b/crates/coa-core/src/release_schema.rs index aab598e..7ced2eb 100644 --- a/crates/coa-core/src/release_schema.rs +++ b/crates/coa-core/src/release_schema.rs @@ -96,7 +96,7 @@ pub fn qualify_upgrade( pkgsource::fetch_manifest(&pkgsource::Source::Dir(base.into()), trusted_key)?; let (source_manifest, source_bytes) = pkgsource::fetch_manifest(&pkgsource::Source::Dir(source.into()), trusted_key)?; - let (candidate_manifest, _) = + let (candidate_manifest, candidate_bytes) = pkgsource::fetch_manifest(&pkgsource::Source::Dir(candidate.into()), trusted_key)?; if candidate_manifest.kind != Kind::Update || !matches!(source_manifest.kind, Kind::Base | Kind::Update) @@ -149,6 +149,7 @@ pub fn qualify_upgrade( } env.ensure_stopped() }; + let mut migration_audit = None; install::with_scratch_ports(fixture, || { if source_manifest.kind == Kind::Update { apply(source)?; @@ -157,6 +158,7 @@ pub fn qualify_upgrade( let user_bytes = b"Qualification.UserSetting = 7391\r\n"; fsx::atomic_write(&user_file, user_bytes)?; apply(candidate)?; + migration_audit = Some(audit_migrations(fixture, &candidate_manifest.migrations)?); if std::fs::read(&user_file)?.as_slice() != user_bytes { return Err(Error::Invalid( "The update changed a user configuration file.".into(), @@ -175,9 +177,10 @@ pub fn qualify_upgrade( })?; Ok(serde_json::json!({ "schema": 1, "result": "passed", "fromVersion": source_manifest.version, - "toVersion": candidate_manifest.version, "fromManifestSha256": fsx::sha256_bytes(&source_bytes), + "toVersion": candidate_manifest.version, "toManifestSha256": fsx::sha256_bytes(&candidate_bytes), + "migrationInventorySha256": migrations::inventory_sha256(&candidate_manifest.migrations)?, "migrations": migration_audit, "fromManifestSha256": fsx::sha256_bytes(&source_bytes), "fromSchemaSha256": source_manifest.files.iter().find(|file| file.path == schema_check::CONTRACT).map(|file| &file.sha256), - "checks": ["manager-transaction", "recovery-backed-database-update", "database-schema", "private-auth-world-startup", "existing-identities", "user-file-preservation"], + "checks": ["legacy-race-start-data", "migration-ledger", "manager-transaction", "recovery-backed-database-update", "database-schema", "private-auth-world-startup", "existing-identities", "user-file-preservation"], })) } @@ -238,6 +241,15 @@ pub fn qualify_install( package: &Path, fixture: &Path, trusted_key: &str, +) -> Result { + qualify_install_against(package, None, fixture, trusted_key) +} + +pub fn qualify_install_against( + package: &Path, + update: Option<&Path>, + fixture: &Path, + trusted_key: &str, ) -> Result { use crate::update::Env; if !cfg!(windows) @@ -254,6 +266,21 @@ pub fn qualify_install( let package = fsx::canonicalize_lenient(package)?; let (manifest, bytes) = pkgsource::fetch_manifest(&pkgsource::Source::Dir(package.clone()), trusted_key)?; + let expected_update = update + .map(|path| pkgsource::fetch_manifest(&pkgsource::Source::Dir(path.into()), trusted_key)) + .transpose()?; + if let Some((expected, _)) = &expected_update { + if expected.kind != Kind::Update + || expected.version != manifest.version + || expected.core.commit != manifest.core.commit + || expected.bots.as_ref().and_then(|b| b.commit.as_ref()) + != manifest.bots.as_ref().and_then(|b| b.commit.as_ref()) + { + return Err(Error::Invalid( + "Clean installation image does not match the selected release.".into(), + )); + } + } let registry_dir = tempfile::tempdir()?; let registry = crate::registry::Registry::at(registry_dir.path().join("registry.json")); let installed = install::install_base( @@ -280,13 +307,84 @@ pub fn qualify_install( "Clean installation did not finish at the packaged release.".into(), )); } + let migration_audit = expected_update + .as_ref() + .map(|(expected, _)| audit_migrations(&fixture, &expected.migrations)) + .transpose()?; + env.ensure_stopped()?; + crate::mysql_snapshot::stop(&fixture)?; + let inventory = expected_update + .as_ref() + .map(|(expected, _)| migrations::inventory_sha256(&expected.migrations)) + .transpose()?; + let mut checks = vec![ + "clean-install", + "signed-full-package", + "credential-rotation", + "schema-contract", + "private-auth-world-startup", + ]; + if expected_update.is_some() { + checks.push("migration-ledger"); + checks.push("legacy-race-start-data"); + } Ok( serde_json::json!({ "schema": 1, "result": "passed", "version": installed.version, "manifestSha256": fsx::sha256_bytes(&bytes), - "checks": ["clean-install", "signed-full-package", "credential-rotation", "schema-contract", "private-auth-world-startup"] }), + "checks": checks, "migrationInventorySha256": inventory, "migrations": migration_audit }), ) } +fn audit_migrations( + root: &Path, + list: &[Migration], +) -> Result> { + install::with_scratch_ports(root, || { + backup::with_database(root, |db| { + crate::realms::state(root)? + .modes() + .into_iter() + .map(|mode| { + if mode == crate::realms::Mode::Coa { + let rows = db + .clone() + .for_realm(mode) + .query("SELECT race,class FROM acore_world.playercreateinfo;")?; + let missing = missing_legacy_starts(&rows); + if !missing.is_empty() { + return Err(Error::Invalid(format!( + "Release is missing legacy race starting data: {}", + missing.join(", ") + ))); + } + } + Ok(( + mode.name().to_string(), + migrations::audit_applied(&db.clone().for_realm(mode), list)?, + )) + }) + .collect() + }) + }) +} + +fn missing_legacy_starts(rows: &str) -> Vec { + let pairs: std::collections::BTreeSet<(u32, u32)> = rows + .lines() + .filter_map(|line| line.split_once('\t')) + .filter_map(|(race, class)| Some((race.parse().ok()?, class.parse().ok()?))) + .collect(); + let mut missing = Vec::new(); + for (race, parent) in [(33, 1), (45, 8)] { + for &(source, class) in &pairs { + if source == parent && !pairs.contains(&(race, class)) { + missing.push(format!("race {race} / class {class}")); + } + } + } + missing +} + pub fn collect(core: &Path, bots: Option<&Path>, repairs: Option<&Path>) -> Result> { let mut files = release::collect_core_sql(core)?; if let Some(bots) = bots { @@ -617,6 +715,56 @@ mod tests { use base64::{engine::general_purpose::STANDARD, Engine}; use ed25519_dalek::{Signer, SigningKey}; + #[test] + #[ignore = "Requires the disposable current-release installation audit fixture"] + fn real_current_image_is_blocked_until_legacy_start_data_is_restored() { + let root = std::path::PathBuf::from(std::env::var_os("COA_RELEASE_AUDIT_FIXTURE").unwrap()); + assert_eq!( + root.file_name().unwrap(), + "coa-schema-fixture-latest-install-audit-20261030" + ); + assert!(root.join(".release-schema-fixture").is_file()); + assert!(!root.join("legacy-release-gate-probe-started").exists()); + fsx::atomic_write( + &root.join("legacy-release-gate-probe-started"), + b"disposable regression test", + ) + .unwrap(); + let candidate = + std::path::PathBuf::from(std::env::var_os("COA_RELEASE_AUDIT_PACKAGE").unwrap()); + let (manifest, _) = pkgsource::fetch_manifest( + &pkgsource::Source::Dir(candidate), + crate::signing::EMBEDDED_PUBLIC_KEY, + ) + .unwrap(); + let failure = audit_migrations(&root, &manifest.migrations).unwrap_err(); + assert!(failure.to_string().contains("race 33 / class 12")); + assert!(failure.to_string().contains("race 45 / class 30")); + println!("PASS: signed current image is blocked for missing legacy starts despite a complete migration ledger"); + let sql = + fs::read_to_string(std::env::var_os("COA_RELEASE_AUDIT_CORRECTION").unwrap()).unwrap(); + install::with_scratch_ports(&root, || backup::with_database(&root, |db| { + let before = db.query("SELECT * FROM acore_characters.characters ORDER BY guid;")?; + db.query(&format!("USE acore_world;\n{sql}"))?; + let once = db.query("SELECT * FROM acore_world.playercreateinfo WHERE race IN (33,45) ORDER BY race,class;")?; + db.query(&format!("USE acore_world;\n{sql}"))?; + assert_eq!(once, db.query("SELECT * FROM acore_world.playercreateinfo WHERE race IN (33,45) ORDER BY race,class;")?); + assert_eq!(before, db.query("SELECT * FROM acore_characters.characters ORDER BY guid;")?); + Ok(()) + })).unwrap(); + let audits = audit_migrations(&root, &manifest.migrations).unwrap(); + println!("PASS: corrected data passes the release gate; characters unchanged; correction idempotent; audit={}", serde_json::to_string(&audits).unwrap()); + } + + #[test] + fn release_rejects_missing_legacy_starts_even_without_existing_characters() { + assert_eq!( + missing_legacy_starts("1\t12\n8\t30\n"), + ["race 33 / class 12", "race 45 / class 30"] + ); + assert!(missing_legacy_starts("1\t12\n8\t30\n33\t12\n45\t30\n").is_empty()); + } + #[test] #[ignore = "Requires a composed disposable installation image"] fn real_full_package_installs_the_current_version_without_an_update_transaction() { diff --git a/crates/coa-release/src/main.rs b/crates/coa-release/src/main.rs index 38f5ec9..cd9a302 100644 --- a/crates/coa-release/src/main.rs +++ b/crates/coa-release/src/main.rs @@ -94,8 +94,9 @@ fn run() -> Result<(), String> { .map_err(e)?; } "qualify-install" => { - let report = coa_core::release_schema::qualify_install( + let report = coa_core::release_schema::qualify_install_against( &PathBuf::from(need(&a, "package")?), + Some(&PathBuf::from(need(&a, "update")?)), &PathBuf::from(need(&a, "fixture")?), coa_core::signing::EMBEDDED_PUBLIC_KEY, ) diff --git a/package-lock.json b/package-lock.json index 1b5982f..49cf061 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "coa-server-manager", - "version": "0.9.4", + "version": "0.9.5", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "coa-server-manager", - "version": "0.9.4", + "version": "0.9.5", "dependencies": { "@tauri-apps/api": "^2.12.0", "@tauri-apps/plugin-dialog": "^2.8.0", diff --git a/package.json b/package.json index 5f09b63..39a376b 100644 --- a/package.json +++ b/package.json @@ -1,7 +1,7 @@ { "name": "coa-server-manager", "private": true, - "version": "0.9.4", + "version": "0.9.5", "license": "AGPL-3.0-only", "type": "module", "scripts": { diff --git a/src-tauri/Cargo.toml b/src-tauri/Cargo.toml index 6479bb9..84f15b9 100644 --- a/src-tauri/Cargo.toml +++ b/src-tauri/Cargo.toml @@ -16,6 +16,7 @@ tauri = { version = "2", features = ["tray-icon"] } tauri-plugin-dialog = "2" tauri-plugin-updater = "2" tauri-plugin-process = "2" +tauri-plugin-single-instance = "2" tauri-plugin-opener = "2" serde = { version = "1", features = ["derive"] } serde_json = "1" diff --git a/src-tauri/src/browse_preferences.rs b/src-tauri/src/browse_preferences.rs new file mode 100644 index 0000000..b60adfb --- /dev/null +++ b/src-tauri/src/browse_preferences.rs @@ -0,0 +1,52 @@ +use std::path::Path; + +pub fn enabled(dir: &Path) -> coa_core::Result { + match std::fs::read(dir.join("public-server-browsing.json")) { + Ok(bytes) => Ok(serde_json::from_slice(&bytes)?), + Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(true), + Err(e) => Err(e.into()), + } +} + +pub fn save(dir: &Path, enabled: bool) -> coa_core::Result<()> { + coa_core::fsx::atomic_write_json(&dir.join("public-server-browsing.json"), &enabled) +} + +pub fn require_enabled(dir: &Path) -> coa_core::Result<()> { + if enabled(dir)? { + Ok(()) + } else { + Err(coa_core::Error::Invalid( + "Public server browsing is disabled in Settings.".into(), + )) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn disabled_and_corrupt_preferences_block_browsing() { + let dir = std::env::temp_dir().join(format!( + "coa-browse-prefs-{}-{}", + std::process::id(), + std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .unwrap() + .as_nanos() + )); + std::fs::create_dir_all(&dir).unwrap(); + assert!(enabled(&dir).unwrap()); + save(&dir, false).unwrap(); + assert!(!enabled(&dir).unwrap()); + assert!(require_enabled(&dir).is_err()); + save(&dir, true).unwrap(); + assert!(require_enabled(&dir).is_ok()); + let file = dir.join("public-server-browsing.json"); + std::fs::write(&file, b"broken").unwrap(); + assert!(require_enabled(&dir).is_err()); + std::fs::remove_file(file).unwrap(); + std::fs::remove_dir(dir).unwrap(); + } +} diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rs index dc28d29..8527225 100644 --- a/src-tauri/src/lib.rs +++ b/src-tauri/src/lib.rs @@ -5,7 +5,9 @@ use std::collections::HashSet; use std::path::PathBuf; use std::sync::{Arc, Mutex}; +mod browse_preferences; mod docker_install; +mod window_preferences; use coa_core::backup::{self, Kind, RecoveryPoint, Trigger, VerifyReport}; use coa_core::config::{self, Scope, SettingsView}; @@ -301,10 +303,39 @@ fn installation_source(custom: Option) -> Result { .ok() .filter(|value| !value.trim().is_empty()) }); + select_installation_source(custom, || update_source(None)) +} + +fn select_installation_source( + custom: Option, + latest: impl FnOnce() -> Result, +) -> Result { if custom.is_some() { return Ok(package_source(custom)); } - Ok(Source::Installation(Box::new(update_source(None)?))) + Ok(Source::Installation(Box::new(latest()?))) +} + +#[cfg(test)] +mod installation_source_tests { + use super::*; + + #[test] + fn fresh_install_uses_the_selected_current_release_full_image() { + let source = select_installation_source(None, || { + Ok(Source::Url("https://example.test/releases/current".into())) + }).unwrap(); + assert!(matches!(source, Source::Installation(inner) + if matches!(*inner, Source::Url(ref url) if url.ends_with("/current")))); + } + + #[test] + fn unavailable_current_release_does_not_fall_back_to_an_old_base() { + let result = select_installation_source(None, || { + Err(Error::PackageNotPublished("current unavailable".into())) + }); + assert!(matches!(result, Err(Error::PackageNotPublished(_)))); + } } #[derive(Serialize)] @@ -622,7 +653,10 @@ async fn start_server( && coa_core::friends::load(&meta).mode != coa_core::friends::Mode::Local { let extra = coa_core::realms::state(&root)?.extra_world_ports(); - if let Err(e) = coa_core::firewall::ensure_rules_with_extra(&layout::read_ports(&root), &extra) { + if let Err(e) = coa_core::firewall::ensure_rules_with_extra( + &layout::read_ports(&root), + &extra, + ) { tracing::warn!("firewall rules for the running worlds were not added: {e}"); } } @@ -634,6 +668,16 @@ async fn start_server( Ok(out) } +#[tauri::command] +async fn force_stop_server( + state: State<'_, AppState>, + id: String, +) -> std::result::Result { + let root = path_of(&state, &id)?; + let _guard = BusyGuard::acquire(&state, &id)?; + blocking(move || driver::force_stop(&root)).await +} + #[tauri::command] async fn stop_server( state: State<'_, AppState>, @@ -1040,14 +1084,10 @@ async fn create_account( password: String, administrator: bool, ) -> std::result::Result<(), UiError> { + let _guard = BusyGuard::acquire(&state, &id)?; let root = path_of(&state, &id)?; blocking(move || { - coa_core::ra::validate_account(&username, &password)?; - let mut ra = Ra::connect(&root)?; - ra.create_account(&username, &password)?; - if administrator { - ra.make_administrator(&username)?; - } + coa_core::accounts::create(&root, &username, &password, administrator)?; tracing::info!(%username, administrator, "account created"); Ok(()) }) @@ -1997,6 +2037,34 @@ fn client_of(root: &std::path::Path) -> Result<(PathBuf, InstallMeta, Option, + id: String, +) -> std::result::Result { + Ok(coa_core::client_graphics::status( + &client_context(&state, &id)?.require()?, + )?) +} + +#[tauri::command] +fn client_set_graphics( + state: State<'_, AppState>, + id: String, + name: String, + disabled: bool, +) -> std::result::Result { + let job = state.client_cancel.lock().unwrap(); + if job.is_some() { + return Err(Error::Invalid("Wait for the client operation to finish.".into()).into()); + } + Ok(coa_core::client_graphics::set( + &client_context(&state, &id)?.require()?, + &name, + disabled, + )?) +} + #[tauri::command] fn client_info( state: State<'_, AppState>, @@ -2492,7 +2560,7 @@ async fn report_context( .into_iter() .flatten() .collect::>() - .join(" · "); + .join(" В· "); Ok(ReportContext { manager_version: coa_core::MANAGER_VERSION.to_string(), windows: windows_version(), @@ -2792,29 +2860,66 @@ async fn console_command( .await } +#[tauri::command] +fn manager_installing(enabled: bool) { + QUIT_REQUESTED.store(enabled, std::sync::atomic::Ordering::SeqCst); +} + +#[tauri::command] +fn close_manager(app: AppHandle) -> std::result::Result<(), UiError> { + if window_preferences::close_to_tray(&data_dir()).unwrap_or(false) { + QUIT_REQUESTED.store(false, std::sync::atomic::Ordering::SeqCst); + if let Some(window) = app.get_webview_window("main") { + window.hide().map_err(|e| Error::Invalid(e.to_string()))?; + } + } else { + QUIT_REQUESTED.store(true, std::sync::atomic::Ordering::SeqCst); + app.exit(0); + } + Ok(()) +} + +#[tauri::command] +fn close_to_tray() -> std::result::Result { + Ok(window_preferences::close_to_tray(&data_dir())?) +} + +#[tauri::command] +fn set_close_to_tray(enabled: bool) -> std::result::Result<(), UiError> { + Ok(window_preferences::save(&data_dir(), enabled)?) +} + +fn show_main_window(app: &AppHandle) { + let handle = app.clone(); + if let Err(error) = app.run_on_main_thread(move || { + if let Some(window) = handle.get_webview_window("main") { + let result = window + .unminimize() + .and_then(|_| window.show()) + .and_then(|_| window.set_focus()); + if let Err(error) = result { + tracing::error!(%error, "Could not restore the Manager window"); + } + } else { + tracing::error!("The Manager main window is missing"); + } + }) { + tracing::error!(%error, "Could not schedule Manager window restoration"); + } +} + static QUIT_REQUESTED: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false); pub fn run() { let dir = data_dir(); let _ = coa_core::logging::init(&dir.join("logs").join("manager.log")); - // Crash safety: recover any unfinished client realmlist overrides from previous abnormal termination - let _ = coa_core::client::revert_realmlist_override(&dir); - let portable = start_portable(&dir); - let (control, host_control) = control_cmds::start(&dir, portable.clone()); tauri::Builder::default() + .plugin(tauri_plugin_single_instance::init(|app, _, _| { + show_main_window(app) + })) .plugin(tauri_plugin_dialog::init()) .plugin(tauri_plugin_updater::Builder::new().build()) .plugin(tauri_plugin_process::init()) - .manage(AppState { - registry: Registry::at(dir.join("installs.json")), - busy: Mutex::new(HashSet::new()), - install_cancel: Mutex::new(None), - client_cancel: Mutex::new(None), - portable, - realm_registry: start_realm_registry(&dir), - control, - host_control, - }) .invoke_handler(tauri::generate_handler![ release_history, default_install_dir, @@ -2828,6 +2933,7 @@ pub fn run() { server_status, start_server, stop_server, + force_stop_server, get_settings, save_settings, list_presets, @@ -2892,6 +2998,8 @@ pub fn run() { remote_connection, remote_connect, client_info, + client_graphics, + client_set_graphics, set_client, client_realmlist, client_install_addon, @@ -2932,6 +3040,12 @@ pub fn run() { portable_launch, registry_status, portable_preflight_remote, + manager_installing, + close_manager, + close_to_tray, + set_close_to_tray, + browse_enabled, + browse_set_enabled, browse_list, browse_detail, module_catalog, @@ -2952,18 +3066,43 @@ pub fn run() { ]) .on_window_event(|window, event| { if let tauri::WindowEvent::CloseRequested { api, .. } = event { - api.prevent_close(); - let _ = window.hide(); + if window.label() != "main" { + return; + } + if window_preferences::close_to_tray(&data_dir()).unwrap_or(false) { + api.prevent_close(); + if let Err(error) = window.hide() { + tracing::warn!(%error, "Could not hide the Manager window"); + } + } else { + QUIT_REQUESTED.store(true, std::sync::atomic::Ordering::SeqCst); + } } }) .setup(|app| { + let dir = data_dir(); + // Crash safety: recover any unfinished client realmlist overrides from previous abnormal termination + let _ = coa_core::client::revert_realmlist_override(&dir); + let portable = start_portable(&dir); + let (control, host_control) = control_cmds::start(&dir, portable.clone()); + app.manage(AppState { + registry: Registry::at(dir.join("installs.json")), + busy: Mutex::new(HashSet::new()), + install_cancel: Mutex::new(None), + client_cancel: Mutex::new(None), + portable, + realm_registry: start_realm_registry(&dir), + control, + host_control, + }); + #[cfg(desktop)] { use tauri::menu::{Menu, MenuItem}; use tauri::tray::{MouseButton, MouseButtonState, TrayIconBuilder, TrayIconEvent}; - use tauri::Manager; - let show = MenuItem::with_id(app, "show", "Open CoA Server Manager", true, None::<&str>)?; + let show = + MenuItem::with_id(app, "show", "Open CoA Server Manager", true, None::<&str>)?; let quit = MenuItem::with_id(app, "quit", "Exit", true, None::<&str>)?; let menu = Menu::with_items(app, &[&show, &quit])?; @@ -2973,11 +3112,7 @@ pub fn run() { .show_menu_on_left_click(false) .on_menu_event(|app, event| match event.id.as_ref() { "show" => { - if let Some(window) = app.get_webview_window("main") { - let _ = window.show(); - let _ = window.unminimize(); - let _ = window.set_focus(); - } + show_main_window(app); } "quit" => { QUIT_REQUESTED.store(true, std::sync::atomic::Ordering::SeqCst); @@ -2993,11 +3128,7 @@ pub fn run() { } = event { let app = tray.app_handle(); - if let Some(window) = app.get_webview_window("main") { - let _ = window.show(); - let _ = window.unminimize(); - let _ = window.set_focus(); - } + show_main_window(app); } }); @@ -3057,6 +3188,7 @@ async fn portable_preflight_remote( } fn browse_client() -> std::result::Result { + browse_preferences::require_enabled(&data_dir())?; let settings = coa_core::realm_registry::settings::load(&data_dir().join("registry"))?; let url = std::env::var("COA_REGISTRY_URL") .ok() @@ -3065,6 +3197,16 @@ fn browse_client() -> std::result::Result std::result::Result { + Ok(browse_preferences::enabled(&data_dir())?) +} + +#[tauri::command] +fn browse_set_enabled(enabled: bool) -> std::result::Result<(), UiError> { + Ok(browse_preferences::save(&data_dir(), enabled)?) +} + fn browse_error(e: coa_core::realm_registry::ClientError) -> UiError { Error::Invalid(e.to_string()).into() } diff --git a/src-tauri/src/window_preferences.rs b/src-tauri/src/window_preferences.rs new file mode 100644 index 0000000..1a7d927 --- /dev/null +++ b/src-tauri/src/window_preferences.rs @@ -0,0 +1,13 @@ +use std::path::Path; + +pub fn close_to_tray(dir: &Path) -> coa_core::Result { + match std::fs::read(dir.join("close-to-tray.json")) { + Ok(bytes) => Ok(serde_json::from_slice(&bytes)?), + Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(false), + Err(e) => Err(e.into()), + } +} + +pub fn save(dir: &Path, enabled: bool) -> coa_core::Result<()> { + coa_core::fsx::atomic_write_json(&dir.join("close-to-tray.json"), &enabled) +} diff --git a/src-tauri/tauri.conf.json b/src-tauri/tauri.conf.json index e283af7..3bdba56 100644 --- a/src-tauri/tauri.conf.json +++ b/src-tauri/tauri.conf.json @@ -1,7 +1,7 @@ { "$schema": "https://schema.tauri.app/config/2", "productName": "CoA Server Manager", - "version": "0.9.4", + "version": "0.9.5", "identifier": "com.coa.servermanager", "build": { "beforeDevCommand": "npm run dev", diff --git a/src/data/README.md b/src/data/README.md index 7d05ebd..b2e0e9b 100644 --- a/src/data/README.md +++ b/src/data/README.md @@ -2,8 +2,8 @@ The Manager feed is imported from the canonical `changelog/history.json`. The server snapshot in this directory is copied from `Corfirean/coa-server-build` -commit `9bf1411de93e98cbcd0e8ebbcdac3a457d5fbaf0`, path -`changelog/history.json`, on 2026-10-28. Only schema, component, repository and +commit `15687243bd3f4d60dfedf70b938b6076c1bd6393`, path +`changelog/history.json`, on 2026-10-30. Only schema, component, repository and releases are retained. Do not independently edit historical records here. At runtime the native read-only command fetches the fixed canonical URL, bounds @@ -22,3 +22,7 @@ canonical commit and add all five translations for each new original note. Never rewrite released fragments to add translations. Run `node --test tools/release-history.test.mjs`; its completeness check expects the latest bundled record of each component to have every translation. + +Manager 0.9.5 prepares all five translations of the ten reviewed stabilization notes and +three server stabilization notes before their release. The bundled snapshot includes server +0.261029.85 from the pinned commit above. Pending notes do not fabricate published records. diff --git a/src/data/latest-note-translations.json b/src/data/latest-note-translations.json index 9b03a07..92a658b 100644 --- a/src/data/latest-note-translations.json +++ b/src/data/latest-note-translations.json @@ -20,7 +20,17 @@ "Slow server startup no longer triggers an early update rollback": "Медленный запуск сервера больше не вызывает преждевременный откат обновления", "Settings group updates, startup and maintenance with translated release history": "Настройки сгруппированы по обновлениям, запуску и обслуживанию с переведённой историей выпусков", "Update and launch without updating share a divided button": "Обновление и запуск без обновления объединены в разделённую кнопку", - "Maximizing the window keeps text and controls at a comfortable size": "При разворачивании окна текст и элементы управления сохраняют удобный размер" + "Maximizing the window keeps text and controls at a comfortable size": "При разворачивании окна текст и элементы управления сохраняют удобный размер", + "Account creation verifies a lost console reply against the requested login": "Создание аккаунта проверяет запрошенные данные входа при потере ответа консоли", + "Abandoned game relay tunnels close their local connection immediately": "Закрытые игровые туннели немедленно освобождают локальное соединение", + "Keep disabled graphics components disabled during client updates": "Обновление клиента сохраняет отключённые графические компоненты", + "Force-stop an unresponsive world after a failed normal shutdown": "Принудительно останавливайте зависший мир после неудачной обычной остановки", + "Crash history includes reports from every world and Windows text files": "История сбоев включает отчёты всех миров и текстовые файлы Windows", + "Show the online bot count for Playerbots on the overview": "Обзор показывает количество ботов Playerbots в игре", + "Disable public server browsing in Settings": "Отключайте просмотр публичных серверов в настройках", + "Keep deliberate stops and update shutdowns from triggering crash restart": "Ручная остановка и остановка для обновления не вызывают перезапуск после сбоя", + "Server startup waits for a responsive console before reporting success": "Запуск сервера ожидает ответа консоли перед сообщением об успехе", + "Restore the existing Manager window when launching it again": "Повторный запуск открывает уже существующее окно менеджера" }, "de": { "Choose Parallel or Global level scaling in module settings": "Parallele oder globale Levelskalierung in den Moduleinstellungen wählen", @@ -42,7 +52,17 @@ "Slow server startup no longer triggers an early update rollback": "Ein langsamer Serverstart löst keinen vorzeitigen Update-Rollback mehr aus", "Settings group updates, startup and maintenance with translated release history": "Einstellungen bündeln Updates, Start und Wartung mit übersetztem Versionsverlauf", "Update and launch without updating share a divided button": "Aktualisieren und ohne Update starten teilen sich eine geteilte Schaltfläche", - "Maximizing the window keeps text and controls at a comfortable size": "Beim Maximieren bleiben Text und Bedienelemente angenehm groß" + "Maximizing the window keeps text and controls at a comfortable size": "Beim Maximieren bleiben Text und Bedienelemente angenehm groß", + "Account creation verifies a lost console reply against the requested login": "Bei verlorener Konsolenantwort werden die angeforderten Kontodaten geprüft", + "Abandoned game relay tunnels close their local connection immediately": "Verlassene Spieltunnel schließen ihre lokale Verbindung sofort", + "Keep disabled graphics components disabled during client updates": "Deaktivierte Grafikkomponenten bleiben bei Client-Updates deaktiviert", + "Force-stop an unresponsive world after a failed normal shutdown": "Eine nicht reagierende Welt nach fehlgeschlagenem normalem Herunterfahren zwangsweise stoppen", + "Crash history includes reports from every world and Windows text files": "Der Absturzverlauf enthält Berichte aller Welten und Windows-Textdateien", + "Show the online bot count for Playerbots on the overview": "Die Übersicht zeigt die Anzahl angemeldeter Playerbots", + "Disable public server browsing in Settings": "Öffentliche Serversuche in den Einstellungen deaktivieren", + "Keep deliberate stops and update shutdowns from triggering crash restart": "Bewusstes Stoppen und Herunterfahren für Updates lösen keinen Absturzneustart aus", + "Server startup waits for a responsive console before reporting success": "Der Serverstart wartet vor der Erfolgsmeldung auf eine reagierende Konsole", + "Restore the existing Manager window when launching it again": "Erneutes Starten stellt das vorhandene Manager-Fenster wieder her" }, "fr": { "Choose Parallel or Global level scaling in module settings": "Choisissez une progression parallèle ou globale des niveaux dans les paramètres du module", @@ -64,7 +84,17 @@ "Slow server startup no longer triggers an early update rollback": "Un démarrage lent du serveur ne déclenche plus un retour arrière prématuré", "Settings group updates, startup and maintenance with translated release history": "Les paramètres regroupent les mises à jour, le démarrage et la maintenance avec un historique traduit", "Update and launch without updating share a divided button": "La mise à jour et le lancement sans mise à jour partagent un bouton divisé", - "Maximizing the window keeps text and controls at a comfortable size": "Le texte et les commandes gardent une taille confortable lorsque la fenêtre est maximisée" + "Maximizing the window keeps text and controls at a comfortable size": "Le texte et les commandes gardent une taille confortable lorsque la fenêtre est maximisée", + "Account creation verifies a lost console reply against the requested login": "La création de compte vérifie les identifiants demandés si la réponse de la console est perdue", + "Abandoned game relay tunnels close their local connection immediately": "Les tunnels de jeu abandonnés ferment immédiatement leur connexion locale", + "Keep disabled graphics components disabled during client updates": "Les composants graphiques désactivés le restent lors des mises à jour du client", + "Force-stop an unresponsive world after a failed normal shutdown": "Arrêtez de force un monde bloqué après un échec de l’arrêt normal", + "Crash history includes reports from every world and Windows text files": "L’historique des plantages inclut les rapports de tous les mondes et les fichiers texte Windows", + "Show the online bot count for Playerbots on the overview": "La vue d’ensemble affiche le nombre de Playerbots connectés", + "Disable public server browsing in Settings": "Désactivez la consultation des serveurs publics dans les paramètres", + "Keep deliberate stops and update shutdowns from triggering crash restart": "Les arrêts volontaires et ceux des mises à jour ne déclenchent plus de redémarrage après plantage", + "Server startup waits for a responsive console before reporting success": "Le démarrage du serveur attend une console réactive avant d’annoncer sa réussite", + "Restore the existing Manager window when launching it again": "Un nouveau lancement restaure la fenêtre existante du gestionnaire" }, "es": { "Choose Parallel or Global level scaling in module settings": "Elige escalado de nivel paralelo o global en los ajustes del módulo", @@ -86,7 +116,17 @@ "Slow server startup no longer triggers an early update rollback": "El inicio lento del servidor ya no provoca una reversión prematura de la actualización", "Settings group updates, startup and maintenance with translated release history": "Los ajustes agrupan actualizaciones, inicio y mantenimiento con un historial de versiones traducido", "Update and launch without updating share a divided button": "Actualizar e iniciar sin actualizar comparten un botón dividido", - "Maximizing the window keeps text and controls at a comfortable size": "Al maximizar la ventana, el texto y los controles mantienen un tamaño cómodo" + "Maximizing the window keeps text and controls at a comfortable size": "Al maximizar la ventana, el texto y los controles mantienen un tamaño cómodo", + "Account creation verifies a lost console reply against the requested login": "La creación de cuentas verifica las credenciales solicitadas si se pierde la respuesta de la consola", + "Abandoned game relay tunnels close their local connection immediately": "Los túneles de juego abandonados cierran su conexión local de inmediato", + "Keep disabled graphics components disabled during client updates": "Los componentes gráficos desactivados permanecen así al actualizar el cliente", + "Force-stop an unresponsive world after a failed normal shutdown": "Detén por la fuerza un mundo bloqueado si falla el cierre normal", + "Crash history includes reports from every world and Windows text files": "El historial de fallos incluye informes de todos los mundos y archivos de texto de Windows", + "Show the online bot count for Playerbots on the overview": "El resumen muestra la cantidad de Playerbots conectados", + "Disable public server browsing in Settings": "Desactiva la consulta de servidores públicos en los ajustes", + "Keep deliberate stops and update shutdowns from triggering crash restart": "Las paradas voluntarias y las de actualización no activan el reinicio por fallo", + "Server startup waits for a responsive console before reporting success": "El arranque del servidor espera a que responda la consola antes de indicar que ha terminado", + "Restore the existing Manager window when launching it again": "Al volver a iniciar el gestor se restaura su ventana existente" }, "zh": { "Choose Parallel or Global level scaling in module settings": "在模块设置中选择并行或全局等级缩放", @@ -108,7 +148,17 @@ "Slow server startup no longer triggers an early update rollback": "服务器启动缓慢不再导致更新过早回滚", "Settings group updates, startup and maintenance with translated release history": "设置按更新、启动和维护分组,并提供已翻译的版本历史", "Update and launch without updating share a divided button": "更新和不更新直接启动使用同一个分段按钮", - "Maximizing the window keeps text and controls at a comfortable size": "最大化窗口时,文字和控件仍保持舒适的大小" + "Maximizing the window keeps text and controls at a comfortable size": "最大化窗口时,文字和控件仍保持舒适的大小", + "Account creation verifies a lost console reply against the requested login": "控制台响应丢失时,创建账号会核验所请求的登录凭据", + "Abandoned game relay tunnels close their local connection immediately": "废弃的游戏中继隧道会立即关闭本地连接", + "Keep disabled graphics components disabled during client updates": "客户端更新时保留已禁用的图形组件状态", + "Force-stop an unresponsive world after a failed normal shutdown": "正常关闭失败后可强制停止无响应的世界服务器", + "Crash history includes reports from every world and Windows text files": "崩溃历史包含所有世界的报告和 Windows 文本文件", + "Show the online bot count for Playerbots on the overview": "概览中显示在线 Playerbots 数量", + "Disable public server browsing in Settings": "可在设置中禁用公共服务器浏览", + "Keep deliberate stops and update shutdowns from triggering crash restart": "主动停止及更新时关闭不会触发崩溃自动重启", + "Server startup waits for a responsive console before reporting success": "服务器启动会等待控制台响应后再报告成功", + "Restore the existing Manager window when launching it again": "再次启动时恢复已有的管理器窗口" } }, "server": { @@ -145,7 +195,11 @@ "Normal Classic dungeons retain their authored damage at full party size": "Обычные подземелья классики сохраняют исходный урон при полной группе", "Interactive World Map displays allied bots, guild tasks and events": "Интерактивная карта мира показывает союзных ботов, задания гильдии и события", "Database startup allows time for slower hard drives": "Запуск базы данных допускает более долгое ожидание на медленных дисках", - "Option to make low-health runners walk": "Добавлена возможность замедлить убегающих существ с низким здоровьем до шага" + "Option to make low-health runners walk": "Добавлена возможность замедлить убегающих существ с низким здоровьем до шага", + "Prevent crashes while players update Apex Hunt quest markers on different maps": "Устранены падения при обновлении меток заданий Apex Hunt игроками на разных картах", + "Thin Human and Leper Troll characters retain their starting data after updates": "Персонажи Thin Human и Leper Troll сохраняют стартовые данные после обновлений", + "Companions avoid rejected names and recover from forced rename login failures": "Компаньоны получают допустимые имена и восстанавливают вход при требовании переименования", + "Updated the reviewed CoA upstream snapshot": "Обновлена проверенная версия исходников CoA" }, "de": { "Restrict new characters by custom race without changing existing characters": "Neue Charaktere nach zusätzlichem Volk beschränken, ohne bestehende Charaktere zu ändern", @@ -180,7 +234,11 @@ "Normal Classic dungeons retain their authored damage at full party size": "Normale Classic-Dungeons behalten bei voller Gruppe ihren ursprünglichen Schaden", "Interactive World Map displays allied bots, guild tasks and events": "Die interaktive Weltkarte zeigt verbündete Bots, Gildenaufgaben und Ereignisse", "Database startup allows time for slower hard drives": "Der Datenbankstart lässt langsameren Festplatten mehr Zeit", - "Option to make low-health runners walk": "Fliehende Kreaturen mit wenig Gesundheit können im Schritttempo laufen" + "Option to make low-health runners walk": "Fliehende Kreaturen mit wenig Gesundheit können im Schritttempo laufen", + "Prevent crashes while players update Apex Hunt quest markers on different maps": "Abstürze beim Aktualisieren von Apex-Hunt-Questmarkierungen auf verschiedenen Karten verhindern", + "Thin Human and Leper Troll characters retain their starting data after updates": "Charaktere der Völker Thin Human und Leper Troll behalten ihre Startdaten nach Updates", + "Companions avoid rejected names and recover from forced rename login failures": "Begleiter vermeiden unzulässige Namen und können sich nach erzwungener Umbenennung wieder anmelden", + "Updated the reviewed CoA upstream snapshot": "Geprüften CoA-Upstream-Stand aktualisiert" }, "fr": { "Restrict new characters by custom race without changing existing characters": "Restreignez les races supplémentaires des nouveaux personnages sans modifier les personnages existants", @@ -215,7 +273,11 @@ "Normal Classic dungeons retain their authored damage at full party size": "Les donjons Classic normaux conservent leurs dégâts d’origine avec un groupe complet", "Interactive World Map displays allied bots, guild tasks and events": "La carte du monde interactive affiche les bots alliés, les tâches de guilde et les événements", "Database startup allows time for slower hard drives": "Le démarrage de la base de données laisse plus de temps aux disques lents", - "Option to make low-health runners walk": "Une option permet aux créatures affaiblies de fuir en marchant" + "Option to make low-health runners walk": "Une option permet aux créatures affaiblies de fuir en marchant", + "Prevent crashes while players update Apex Hunt quest markers on different maps": "Évite les plantages lorsque les joueurs actualisent les marqueurs de quête Apex Hunt sur différentes cartes", + "Thin Human and Leper Troll characters retain their starting data after updates": "Les personnages Thin Human et Leper Troll conservent leurs données de départ après les mises à jour", + "Companions avoid rejected names and recover from forced rename login failures": "Les compagnons évitent les noms refusés et récupèrent leur connexion après un renommage imposé", + "Updated the reviewed CoA upstream snapshot": "Version amont vérifiée de CoA mise à jour" }, "es": { "Restrict new characters by custom race without changing existing characters": "Restringe las razas adicionales de personajes nuevos sin modificar los existentes", @@ -250,7 +312,11 @@ "Normal Classic dungeons retain their authored damage at full party size": "Las mazmorras Classic normales conservan su daño original con un grupo completo", "Interactive World Map displays allied bots, guild tasks and events": "El mapa del mundo interactivo muestra bots aliados, tareas de hermandad y eventos", "Database startup allows time for slower hard drives": "El inicio de la base de datos permite más tiempo en discos lentos", - "Option to make low-health runners walk": "Una opción permite que las criaturas con poca salud huyan caminando" + "Option to make low-health runners walk": "Una opción permite que las criaturas con poca salud huyan caminando", + "Prevent crashes while players update Apex Hunt quest markers on different maps": "Evita fallos al actualizar marcadores de misiones Apex Hunt en distintos mapas", + "Thin Human and Leper Troll characters retain their starting data after updates": "Los personajes Thin Human y Leper Troll conservan sus datos iniciales tras actualizar", + "Companions avoid rejected names and recover from forced rename login failures": "Los compañeros evitan nombres rechazados y recuperan el acceso tras un cambio de nombre obligatorio", + "Updated the reviewed CoA upstream snapshot": "Actualizada la versión revisada del código original de CoA" }, "zh": { "Restrict new characters by custom race without changing existing characters": "限制新角色可选的自定义种族,不影响现有角色", @@ -285,7 +351,11 @@ "Normal Classic dungeons retain their authored damage at full party size": "普通经典地下城在满员队伍下保留原始伤害", "Interactive World Map displays allied bots, guild tasks and events": "交互式世界地图显示友方机器人、公会任务和事件", "Database startup allows time for slower hard drives": "数据库启动为较慢的硬盘预留更多等待时间", - "Option to make low-health runners walk": "新增选项,可让低生命值的逃跑生物改为步行" + "Option to make low-health runners walk": "新增选项,可让低生命值的逃跑生物改为步行", + "Prevent crashes while players update Apex Hunt quest markers on different maps": "防止玩家在不同地图更新 Apex Hunt 任务标记时崩溃", + "Thin Human and Leper Troll characters retain their starting data after updates": "Thin Human 和 Leper Troll 角色在更新后保留初始数据", + "Companions avoid rejected names and recover from forced rename login failures": "同伴避免使用被拒绝的名称,并修复强制改名导致的登录失败", + "Updated the reviewed CoA upstream snapshot": "更新已审核的 CoA 上游版本" } } } diff --git a/src/data/server-history.json b/src/data/server-history.json index 25d3f59..3ca3c59 100644 --- a/src/data/server-history.json +++ b/src/data/server-history.json @@ -1164,6 +1164,139 @@ "portable-characters" ], "compare": "https://github.com/Corfirean/coa-server-build/compare/server-0.261026.81...server-0.261028.83" + }, + { + "tag": "server-0.261029.85", + "version": "0.261029.85", + "date": "2026-10-29", + "url": "https://github.com/Corfirean/coa-server-build/releases/tag/server-0.261029.85", + "notes": [ + "Dungeon scaling preserves the level differences between creatures", + "Server includes newer upstream class, quest and dungeon updates", + "Interactive World Map displays allied bots, guild tasks and events", + "Normal Classic dungeons retain their authored damage at full party size", + "Database startup allows time for slower hard drives", + "Updated the reviewed CoA upstream snapshot" + ], + "snapshot": "386ef2183cb286cd50d9b966ab184a6dd743b08889bd92af65be6f295a60c25c", + "components": { + "upstream": { + "repository": "jealous-sound/azerothcore-wotlk-coa", + "ref": "783f87fc5d271192c56f71a4e48ff5b3111f4c00", + "sha": "783f87fc5d271192c56f71a4e48ff5b3111f4c00" + }, + "core": { + "repository": "Corfirean/azerothcore-wotlk-coa", + "ref": "084c26dde98099f6329b85f3bfda2df9e107b180", + "sha": "084c26dde98099f6329b85f3bfda2df9e107b180" + }, + "bots": { + "repository": "Corfirean/mod-coa-playerbots", + "ref": "16555af2303b870751d27d287ce3ce8088b9e933", + "sha": "16555af2303b870751d27d287ce3ce8088b9e933" + }, + "scaling": { + "repository": "Corfirean/mod-coa-content-scaling", + "ref": "0898a3e976677cde470a60ba4e6f9bb9d0fe5e2c", + "sha": "0898a3e976677cde470a60ba4e6f9bb9d0fe5e2c" + }, + "manager": { + "repository": "Corfirean/coa-server-manager", + "ref": "c004b90c54fa358b3037c56b093cf019dfcf02b8", + "sha": "c004b90c54fa358b3037c56b093cf019dfcf02b8" + }, + "races": { + "repository": "ilusixn/azerothcore-wotlk-coa", + "ref": "coa-custom-1.9.2", + "sha": "31bd63d309b8b0fb4f1a4d9b793a343b8ac36f1e", + "assets": [ + { + "name": "CoA-Custom-1.9.2-Client-1.zip", + "size": 1513021586, + "digest": "sha256:a9dd51ed2d90fb048d549602f40f5429d56e2df0df5606a38781b358fa369568", + "url": "https://github.com/ilusixn/azerothcore-wotlk-coa/releases/download/coa-custom-1.9.2/CoA-Custom-1.9.2-Client-1.zip" + }, + { + "name": "CoA-Custom-1.9.2-Client-2.zip", + "size": 1198283005, + "digest": "sha256:ab084a55509ccbcc2977a06dd0c01fa879973a1892baaacaeb3ff52f3dfc750e", + "url": "https://github.com/ilusixn/azerothcore-wotlk-coa/releases/download/coa-custom-1.9.2/CoA-Custom-1.9.2-Client-2.zip" + }, + { + "name": "CoA-Custom-1.9.2-Client-3.zip", + "size": 1678829573, + "digest": "sha256:907e267f0ee7038807e626c3c1eca5e12db6c88b747137a23c5fb52eaa1a358e", + "url": "https://github.com/ilusixn/azerothcore-wotlk-coa/releases/download/coa-custom-1.9.2/CoA-Custom-1.9.2-Client-3.zip" + }, + { + "name": "CoA-Custom-1.9.2-Client-4.zip", + "size": 502385128, + "digest": "sha256:e0bd87172af989fa50a8e2b08ba4321c72b6265047482f051a1db3b80d55bcaa", + "url": "https://github.com/ilusixn/azerothcore-wotlk-coa/releases/download/coa-custom-1.9.2/CoA-Custom-1.9.2-Client-4.zip" + }, + { + "name": "CoA-Custom-1.9.2-Client-5.zip", + "size": 168079711, + "digest": "sha256:73364ad1b58c6342641a848a3b20a835472834f600416606be1470386774ca78", + "url": "https://github.com/ilusixn/azerothcore-wotlk-coa/releases/download/coa-custom-1.9.2/CoA-Custom-1.9.2-Client-5.zip" + }, + { + "name": "CoA-Custom-1.9.2-Server.zip", + "size": 53004560, + "digest": "sha256:b893813573a4d3f6a0003c1f174582d3def997f37b402cbca44d53055d2fc1d2", + "url": "https://github.com/ilusixn/azerothcore-wotlk-coa/releases/download/coa-custom-1.9.2/CoA-Custom-1.9.2-Server.zip" + }, + { + "name": "INSTALL-GUIDE.txt", + "size": 3006, + "digest": "sha256:f17e97fafa3225901d1caf8c3b8141293f98fbfb8c9243c0c4717278c60146aa", + "url": "https://github.com/ilusixn/azerothcore-wotlk-coa/releases/download/coa-custom-1.9.2/INSTALL-GUIDE.txt" + }, + { + "name": "PATCH-NOTES-1.9.2.txt", + "size": 2822, + "digest": "sha256:f2fd4693ba181959a572d3fb10a0050e9ff6c4f735b3ab0019c7d16712db28cb", + "url": "https://github.com/ilusixn/azerothcore-wotlk-coa/releases/download/coa-custom-1.9.2/PATCH-NOTES-1.9.2.txt" + } + ] + }, + "squid": { + "repository": "Zyth45/mod-playerbots", + "ref": "v2.7", + "sha": "272c350b0d8c045ca04a790de4b5b2f0cef531ef" + }, + "build": { + "repository": "Corfirean/coa-server-build", + "ref": "3f7eb2b3b67d621259baf12c9a6fbcf23f791bb1", + "sha": "3f7eb2b3b67d621259baf12c9a6fbcf23f791bb1" + }, + "navigation": { + "repository": "Corfirean/azerothcore-wotlk-coa", + "ref": "8b44099f480af0b69c6dfc697e4d388e865e9ffc", + "sha": "8b44099f480af0b69c6dfc697e4d388e865e9ffc", + "sourceRelease": "navigation-20261012", + "manifestSha256": "7f28600735f115792e79a5e8d1c8d78a83a8f5ed14a090c6d87268e49c2bb683", + "archiveSha256": "aa1347a095f85af44b4f592270a0e9314954801fda4578f0147f847e32c24a60", + "assets": [ + { + "name": "navigation.zip.001", + "size": 1500000000, + "sha256": "e3a93903fc8155ee0d92db399ec426769c360bef87c44c07beb7e21cfd892c18", + "url": "https://github.com/Corfirean/coa-server-build/releases/download/navigation-20261012/navigation.zip.001" + }, + { + "name": "navigation.zip.002", + "size": 1377006470, + "sha256": "c1af26ba7f83676278613076c357c4da0a11cfa6ae1ff00003479057c4864471", + "url": "https://github.com/Corfirean/coa-server-build/releases/download/navigation-20261012/navigation.zip.002" + } + ] + } + }, + "experimentalFeatures": [ + "portable-characters" + ], + "compare": "https://github.com/Corfirean/coa-server-build/compare/server-0.261028.83...server-0.261029.85" } ] } diff --git a/src/dev/mock.ts b/src/dev/mock.ts index e2e8725..7b8e566 100644 --- a/src/dev/mock.ts +++ b/src/dev/mock.ts @@ -29,6 +29,12 @@ export {}; (window as any).__TAURI_INTERNALS__ = { transformCallback: (cb: unknown)=>cb, unregisterCallback(){}, convertFileSrc:(x: unknown)=>x, invoke: async (cmd: string, args?: any)=>{ + if(cmd==="close_to_tray") return localStorage.getItem("demo-close-tray")==="1"; + if(cmd==="set_close_to_tray"){localStorage.setItem("demo-close-tray",args.enabled?"1":"0");return;} + if(cmd==="client_graphics") return JSON.parse(localStorage.getItem("demo-graphics")??'{"dxvk_disabled":false,"enhancements_disabled":false}'); + if(cmd==="client_set_graphics"){const g=JSON.parse(localStorage.getItem("demo-graphics")??'{"dxvk_disabled":false,"enhancements_disabled":false}');g[args.name==="d3d9.dll"?"dxvk_disabled":"enhancements_disabled"]=args.disabled;localStorage.setItem("demo-graphics",JSON.stringify(g));return g;} + if(cmd==="browse_enabled") return localStorage.getItem("demo-browse-enabled") !== "0"; + if(cmd==="browse_set_enabled"){localStorage.setItem("demo-browse-enabled", args.enabled ? "1" : "0");return;} if(cmd==="open_link") return null; if(cmd==="pending_update") return null; if(cmd==="plugin:app|version") return "0.8.2"; @@ -47,6 +53,7 @@ export {}; if(cmd==="add_server"){added=true;return {id:"1",name:"CoA-Repack",path:report.path};} if(cmd==="server_status"){const s=running?"running":"stopped";return {observed:{mysql:svc("mysql",3307,s),auth:svc("auth",3724,s),world:svc("world",8085,s),secondary_world:simultaneous?svc("world-secondary",8086,s):null,reborn_world:withReborn?svc("world-reborn",8087,s):null},busy:false,path_exists:true};} if(cmd==="start_server"){await new Promise((r: any)=>setTimeout(r,1500));running=true;return {ok:true,exit_code:0,code:null,human:null,output:""};} + if(cmd==="force_stop_server"){running=false;return {ok:true,exit_code:0,code:null,human:null,output:""};} if(cmd==="stop_server"){await new Promise((r: any)=>setTimeout(r,1500));running=false;return {ok:true,exit_code:0,code:null,human:null,output:""};} if(cmd.startsWith("plugin:dialog")) return "C:\\games\\CoA-Repack"; if(cmd==="get_settings"){const sc=args?.scope==="server"?serverSchema:botsSchema;return {scope:args?.scope,categories:sc.categories,settings:(sc.settings as any[]).map(x=>({...x,options:x.options??[],value:x.default,is_default:true,present:true,problem:null,drift:false})),unknown_keys:3,drift_keys:[],files:[]};} diff --git a/src/i18n/locales/de.ts b/src/i18n/locales/de.ts index 43268aa..fee3534 100644 --- a/src/i18n/locales/de.ts +++ b/src/i18n/locales/de.ts @@ -1066,6 +1066,23 @@ const de: Partial> = { "registry.realmStoppedHint": "Der Realm ist gestoppt. Den Server starten, damit Spieler beitreten und Charaktersitzungen verfolgen können.", "access.portableEnabled": "Portable Charaktere zulassen", "access.portableEnabledHint": "Spieler können auf diesem Realm mit ihren im Manager gespeicherten Charakteren spielen.", + "settings.publicServers": "Öffentliche Server anzeigen", + "settings.publicServersHint": "Wenn deaktiviert, ruft der Manager keine öffentlichen Serverlisten oder Details ab. Wenn aktiviert, lädt Aktualisieren die Liste.", + "browse.disabled": "Die Anzeige öffentlicher Server ist deaktiviert. Aktiviere sie in den Einstellungen, um den Katalog zu laden.", + + "client.graphics.dxvk": "Kompatible Grafik verwenden (DXVK deaktivieren)", + "client.graphics.enhancements": "Zusätzliche Grafikverbesserungen deaktivieren", + "client.graphics.hint": "Schließe das Spiel vor Änderungen. Client-Updates lassen deaktivierte Grafikkomponenten ausgeschaltet.", + "settings.closeToTray": "Beim Schließen in den Infobereich minimieren", + "settings.closeToTrayHint": "Wenn ausgeschaltet, beendet das Schließen des Fensters den Manager. Ein erneuter Start öffnet das bereits laufende Fenster.", + + "overview.bots": "+ {n} Bots", + + "stop.force": "Beenden erzwingen", + "stop.forceTitle": "Diesen Server zwangsweise beenden?", + "stop.forceWarning": "Ungespeicherter Spielfortschritt kann verloren gehen. Nur geprüfte Prozesse dieses Servers werden beendet. Die Datenbank läuft weiter, bis alle Welten beendet sind.", + "stop.cancel": "Abbrechen", + }; export default de; diff --git a/src/i18n/locales/en.ts b/src/i18n/locales/en.ts index fe16ef1..2b8e2e7 100644 --- a/src/i18n/locales/en.ts +++ b/src/i18n/locales/en.ts @@ -1277,6 +1277,22 @@ const en = { "access.relay": "Relay", "access.relayUp": "Game relay connected", "access.relayDown": "Game relay disconnected", + "settings.publicServers": "Allow public server browsing", + "settings.publicServersHint": "When disabled, the Manager does not request public server lists or details. When enabled, load the list with Refresh.", + "browse.disabled": "Public server browsing is disabled. Enable it in Settings to load the catalog.", + "client.graphics.dxvk": "Use compatibility graphics (disable DXVK)", + "client.graphics.enhancements": "Disable additional graphics enhancements", + "client.graphics.hint": "Close the game before changing these settings. Disabled renderers stay disabled during client updates.", + "settings.closeToTray": "Minimize to tray when closing the window", + "settings.closeToTrayHint": "When off, closing the window exits the Manager. Launching it again opens the existing window if it is already running.", + + "overview.bots": "+ {n} bots", + + "stop.force": "Force stop", + "stop.forceTitle": "Force-stop this server?", + "stop.forceWarning": "Unsaved player progress may be lost. Only verified processes belonging to this server will be stopped. The database will remain running until every world has stopped.", + "stop.cancel": "Cancel", + } as const; export default en; diff --git a/src/i18n/locales/es.ts b/src/i18n/locales/es.ts index 3f005b3..3bd966c 100644 --- a/src/i18n/locales/es.ts +++ b/src/i18n/locales/es.ts @@ -1066,6 +1066,23 @@ const es: Partial> = { "registry.realmStoppedHint": "El reino está detenido. Inicia el servidor para que los jugadores entren y se registren las sesiones de personajes.", "access.portableEnabled": "Permitir personajes portátiles", "access.portableEnabledHint": "Los jugadores pueden usar en este reino sus personajes guardados en Manager.", + "settings.publicServers": "Permitir consultar servidores públicos", + "settings.publicServersHint": "Si se desactiva, el gestor no solicita listas ni detalles de servidores públicos. Si se activa, carga la lista con Actualizar.", + "browse.disabled": "La consulta de servidores públicos está desactivada. Actívala en los ajustes para cargar el catálogo.", + + "client.graphics.dxvk": "Usar gráficos compatibles (desactivar DXVK)", + "client.graphics.enhancements": "Desactivar mejoras gráficas adicionales", + "client.graphics.hint": "Cierra el juego antes de cambiar estos ajustes. Las actualizaciones mantienen desactivados los componentes gráficos elegidos.", + "settings.closeToTray": "Minimizar a la bandeja al cerrar la ventana", + "settings.closeToTrayHint": "Si se desactiva, cerrar la ventana sale del gestor. Volver a iniciarlo abre la ventana existente si ya está en ejecución.", + + "overview.bots": "+ {n} bots", + + "stop.force": "Forzar detención", + "stop.forceTitle": "¿Forzar la detención de este servidor?", + "stop.forceWarning": "Puede perderse el progreso sin guardar. Solo se detendrán los procesos verificados de este servidor. La base de datos seguirá activa hasta que se detengan todos los mundos.", + "stop.cancel": "Cancelar", + }; export default es; diff --git a/src/i18n/locales/fr.ts b/src/i18n/locales/fr.ts index 95b0f94..a1a4f25 100644 --- a/src/i18n/locales/fr.ts +++ b/src/i18n/locales/fr.ts @@ -1066,6 +1066,23 @@ const fr: Partial> = { "registry.realmStoppedHint": "Le royaume est arrêté. Démarrez le serveur pour permettre la connexion et le suivi des sessions des personnages.", "access.portableEnabled": "Autoriser les personnages portables", "access.portableEnabledHint": "Les joueurs peuvent utiliser sur ce royaume leurs personnages enregistrés dans Manager.", + "settings.publicServers": "Autoriser la consultation des serveurs publics", + "settings.publicServersHint": "Si cette option est désactivée, le gestionnaire ne demande ni liste ni détails des serveurs publics. Sinon, chargez la liste avec Actualiser.", + "browse.disabled": "La consultation des serveurs publics est désactivée. Activez-la dans les paramètres pour charger le catalogue.", + + "client.graphics.dxvk": "Utiliser le mode graphique compatible (désactiver DXVK)", + "client.graphics.enhancements": "Désactiver les améliorations graphiques supplémentaires", + "client.graphics.hint": "Fermez le jeu avant toute modification. Les mises à jour du client conservent les composants graphiques désactivés.", + "settings.closeToTray": "Réduire dans la zone de notification à la fermeture", + "settings.closeToTrayHint": "Sinon, fermer la fenêtre quitte le gestionnaire. Un nouveau lancement ouvre la fenêtre existante si le gestionnaire est déjà actif.", + + "overview.bots": "+ {n} bots", + + "stop.force": "Forcer l’arrêt", + "stop.forceTitle": "Forcer l’arrêt de ce serveur ?", + "stop.forceWarning": "La progression non enregistrée peut être perdue. Seuls les processus vérifiés de ce serveur seront arrêtés. La base de données reste active jusqu’à l’arrêt de tous les mondes.", + "stop.cancel": "Annuler", + }; export default fr; diff --git a/src/i18n/locales/ru.ts b/src/i18n/locales/ru.ts index c04a1ac..f93a4d4 100644 --- a/src/i18n/locales/ru.ts +++ b/src/i18n/locales/ru.ts @@ -1259,6 +1259,23 @@ const ru: Partial> = { "access.relay": "Relay", "access.relayUp": "Игровой relay подключён", "access.relayDown": "Игровой relay не подключён", + "settings.publicServers": "Разрешить просмотр публичных серверов", + "settings.publicServersHint": "Если выключено, менеджер не запрашивает списки и сведения о публичных серверах. Если включено, список загружается кнопкой «Обновить».", + "browse.disabled": "Просмотр публичных серверов отключён. Включите его в настройках, чтобы загрузить каталог.", + + "client.graphics.dxvk": "Совместимый режим графики (отключить DXVK)", + "client.graphics.enhancements": "Отключить дополнительные графические улучшения", + "client.graphics.hint": "Перед изменением закройте игру. Обновление клиента сохраняет отключённые графические компоненты.", + "settings.closeToTray": "Сворачивать в трей при закрытии окна", + "settings.closeToTrayHint": "Если выключено, закрытие окна завершает менеджер. Повторный запуск открывает уже работающий экземпляр.", + + "overview.bots": "+ {n} ботов", + + "stop.force": "Принудительно остановить", + "stop.forceTitle": "Принудительно остановить этот сервер?", + "stop.forceWarning": "Несохранённый прогресс игроков может быть потерян. Будут остановлены только проверенные процессы этого сервера. База данных останется работать до остановки всех миров.", + "stop.cancel": "Отмена", + }; export default ru; diff --git a/src/i18n/locales/zh.ts b/src/i18n/locales/zh.ts index a23eb81..dab7ba6 100644 --- a/src/i18n/locales/zh.ts +++ b/src/i18n/locales/zh.ts @@ -1068,6 +1068,23 @@ const zh = { "registry.realmStoppedHint": "世界当前已停止。请启动服务器,以便玩家加入并跟踪角色会话。", "access.portableEnabled": "允许便携角色", "access.portableEnabledHint": "允许玩家在此服务器使用保存在 Manager 中的角色。", + "settings.publicServers": "允许浏览公共服务器", + "settings.publicServersHint": "关闭后,管理器不会请求公共服务器列表或详情。启用后,点击“刷新”加载列表。", + "browse.disabled": "公共服务器浏览已关闭。请在设置中启用以加载目录。", + + "client.graphics.dxvk": "使用兼容图形模式(禁用 DXVK)", + "client.graphics.enhancements": "禁用额外图形增强", + "client.graphics.hint": "更改前请关闭游戏。客户端更新会保留已禁用的图形组件。", + "settings.closeToTray": "关闭窗口时最小化到托盘", + "settings.closeToTrayHint": "关闭此选项后,关闭窗口将退出管理器。再次启动会打开已运行的窗口。", + + "overview.bots": "+ {n} 个机器人", + + "stop.force": "强制停止", + "stop.forceTitle": "强制停止此服务器?", + "stop.forceWarning": "玩家未保存的进度可能丢失。只会停止经验证属于此服务器的进程。所有世界停止后才会关闭数据库。", + "stop.cancel": "取消", + } as const; export default zh; diff --git a/src/lib/api.ts b/src/lib/api.ts index 538b410..b2d932f 100644 --- a/src/lib/api.ts +++ b/src/lib/api.ts @@ -496,6 +496,7 @@ export const api = { forget: (id: string) => invoke("forget_server", { id }), status: (id: string) => invoke("server_status", { id }), start: (id: string) => invoke("start_server", { id }), + forceStop: (id: string) => invoke("force_stop_server", { id }), stop: (id: string) => invoke("stop_server", { id }), settings: (id: string, scope: Scope) => invoke("get_settings", { id, scope }), save: (id: string, scope: Scope, changes: Record) => invoke("save_settings", { id, scope, changes }), @@ -560,6 +561,8 @@ export const api = { performance: (id: string) => invoke("get_performance", { id }), companionSizes: () => invoke("companion_sizes"), addCompanions: (id: string, count: number) => invoke<{ spawned: string | null; created: number | null; baseline: number | null }>("add_companions", { id, count }), + clientGraphics: (id: string) => invoke<{ dxvk_disabled: boolean; enhancements_disabled: boolean }>("client_graphics", { id }), + clientSetGraphics: (id: string, name: string, disabled: boolean) => invoke<{ dxvk_disabled: boolean; enhancements_disabled: boolean }>("client_set_graphics", { id, name, disabled }), clientInfo: (id: string) => invoke("client_info", { id }), setClient: (id: string, path: string) => invoke("set_client", { id, path }), setRealmlist: (id: string, host: string) => invoke("client_realmlist", { id, host }), diff --git a/src/lib/browse.ts b/src/lib/browse.ts index b8e1b37..6cfb25a 100644 --- a/src/lib/browse.ts +++ b/src/lib/browse.ts @@ -69,6 +69,8 @@ export interface BrowseParams { } export const browse = { + enabled: () => invoke("browse_enabled"), + setEnabled: (enabled: boolean) => invoke("browse_set_enabled", { enabled }), list: (params: BrowseParams) => invoke("browse_list", { params }), detail: (realmId: string) => invoke("browse_detail", { realmId }), modules: () => invoke("module_catalog"), diff --git a/src/lib/selfUpdate.ts b/src/lib/selfUpdate.ts index e73bca6..e59391f 100644 --- a/src/lib/selfUpdate.ts +++ b/src/lib/selfUpdate.ts @@ -1,3 +1,4 @@ +import { invoke } from "@tauri-apps/api/core"; import { useSyncExternalStore } from "react"; import { getCurrentWindow } from "@tauri-apps/api/window"; import { check, type Update } from "@tauri-apps/plugin-updater"; @@ -93,9 +94,11 @@ export async function installNow(): Promise { if (state.phase !== "ready") await downloadPending(); if (state.phase !== "ready") return; set({ phase: "installing" }); + await invoke("manager_installing", { enabled: true }); await update.install(); await relaunch(); } catch (e) { + await invoke("manager_installing", { enabled: false }).catch(() => {}); set({ phase: "error", error: String(e) }); } } @@ -107,14 +110,23 @@ export function installOnClose(): () => void { const win = getCurrentWindow(); void win .onCloseRequested(async (event) => { - if (state.phase !== "ready" || !update || !autoUpdateEnabled()) return; event.preventDefault(); + if (state.phase !== "ready" || !update || !autoUpdateEnabled()) { + await invoke("close_manager"); + return; + } + if (await invoke("close_to_tray")) { + await invoke("close_manager"); + return; + } try { set({ phase: "installing" }); + await invoke("manager_installing", { enabled: true }); await update.install(); } catch (e) { + await invoke("manager_installing", { enabled: false }).catch(() => {}); set({ phase: "error", error: String(e) }); - await win.destroy(); + await invoke("close_manager"); } }) .then((un) => { diff --git a/src/lib/serverLifecycle.ts b/src/lib/serverLifecycle.ts new file mode 100644 index 0000000..0ee5fc2 --- /dev/null +++ b/src/lib/serverLifecycle.ts @@ -0,0 +1,38 @@ +export class ServerLifecycle { + private wasRunning = false; + private maintenance = false; + private stopRequested = false; + private operationPending = false; + + request(action: "starting" | "stopping" | "restarting") { + this.stopRequested = action !== "starting"; + this.operationPending = true; + } + + complete(action: "starting" | "stopping" | "restarting") { + this.operationPending = false; + if (action !== "stopping") { this.stopRequested = false; this.wasRunning = false; } + } + + beginMaintenance() { this.maintenance = true; this.wasRunning = false; } + endMaintenance() { this.maintenance = false; this.wasRunning = false; } + + observe(running: boolean, busy: boolean, updating: boolean): boolean { + if (this.maintenance) { this.wasRunning = false; return false; } + if (running) { this.wasRunning = true; return false; } + if (this.stopRequested || updating || this.operationPending) { + this.wasRunning = false; + if (!busy && !this.operationPending) this.stopRequested = false; + return false; + } + if (this.wasRunning && !busy) { this.wasRunning = false; return true; } + return false; + } +} + +const lifecycles = new Map(); +export function serverLifecycle(id: string) { + let lifecycle = lifecycles.get(id); + if (!lifecycle) { lifecycle = new ServerLifecycle(); lifecycles.set(id, lifecycle); } + return lifecycle; +} diff --git a/src/lib/serverUpdate.ts b/src/lib/serverUpdate.ts index 4f46dac..3bacd07 100644 --- a/src/lib/serverUpdate.ts +++ b/src/lib/serverUpdate.ts @@ -1,3 +1,4 @@ +import { serverLifecycle } from "@/lib/serverLifecycle"; import { useSyncExternalStore } from "react"; import { listen } from "@tauri-apps/api/event"; import { api, asUiError, type UiError, type UpdatePreview, type UpdateTxn } from "@/lib/api"; @@ -30,6 +31,11 @@ const listeners = new Set<() => void>(); export const CHECK_EVERY_MS = 5 * 60 * 1000; const get = (id: string) => states.get(id) ?? EMPTY; +export function serverUpdateBlocksRestart(id: string): boolean { + const state = get(id); + return state.applying || state.stateError !== null || !!(state.result && "pending" in state.result); +} + function set(id: string, next: Partial) { states.set(id, { ...get(id), ...next }); listeners.forEach((l) => l()); @@ -89,6 +95,7 @@ export async function applyServerUpdate(id: string, opts?: { choices: Record [s.observed.mysql, s.observed.auth, s.observed.world].some((x) => x.state === "running" || x.state === "starting")).catch(() => true); + serverLifecycle(id).beginMaintenance(); set(id, { applying: true, step: null, percent: 0, error: null, uiError: null, result: null }); let un: (() => void) | undefined; try { @@ -110,6 +117,7 @@ export async function applyServerUpdate(id: string, opts?: { choices: Record(null); + const [error, setError] = useState(null); + useEffect(() => { void browse.enabled().then(setEnabled).catch(e => setError(asUiError(e).technical)); }, []); + if (error) return

{error}

; + if (enabled === null) return ; + if (!enabled) return

{t("browse.title")}

{t("browse.disabled")}

; + return ; +} + +function EnabledBrowsePage() { const { t } = useI18n(); const { status } = useRegistryStatus(5000); const [q, setQ] = useState(""); @@ -213,6 +224,7 @@ export function BrowsePage() { const [preferredSaved, setPreferredSaved] = useState(""); const [preferredNote, setPreferredNote] = useState(null); const ticket = useRef(0); + const [requested, setRequested] = useState(false); useEffect(() => { void control.status().then((c) => { setPreferred(c.preferred_username); setPreferredSaved(c.preferred_username); }).catch(() => {}); }, []); useEffect(() => { void browse.modules().then((m) => setCatalog(Object.fromEntries(m.map((x) => [x.id, x])))).catch(() => {}); }, []); @@ -244,10 +256,10 @@ export function BrowsePage() { }, [params]); useEffect(() => { - if (!status?.url) return; + if (!requested || !status?.url) return; const timer = setTimeout(() => void load(), q ? 300 : 0); return () => clearTimeout(timer); - }, [load, status?.url]); // eslint-disable-line react-hooks/exhaustive-deps + }, [load, status?.url, requested]); // eslint-disable-line react-hooks/exhaustive-deps function onSort(k: SortKey) { if (k === sort) setOrder((o) => (o === "asc" ? "desc" : "asc")); @@ -263,7 +275,7 @@ export function BrowsePage() {

{t("browse.title")}

{t("browse.text")}

- + {noUrl &&

{t("browse.noUrl")}

} diff --git a/src/screens/ClientCard.tsx b/src/screens/ClientCard.tsx index 7d5baaa..50164db 100644 --- a/src/screens/ClientCard.tsx +++ b/src/screens/ClientCard.tsx @@ -3,6 +3,7 @@ import { listen } from "@tauri-apps/api/event"; import { open } from "@tauri-apps/plugin-dialog"; import { api, asUiError, type ClientInfo, type ClientStatus, type UiError } from "@/lib/api"; import { checkClient } from "@/lib/clientUpdate"; +import { ClientGraphics } from "./ClientGraphics"; import { ClientDialog, type ClientDialogMode } from "@/screens/ClientDialog"; import { Button } from "@/components/ui/button"; import { Card } from "@/components/ui/card"; @@ -95,6 +96,7 @@ export function ClientCard({ serverId, remote = false }: { serverId: string; rem
{t("client.otherAddons")}
{t("client.leftAsIs", { n: info.other_addons })}
+ {!remote && (