mirror of
https://github.com/Corfirean/coa-server-manager.git
synced 2026-11-19 19:25:56 +00:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
2d9c6a65bb | ||
|
|
ce83f04d9d | ||
|
|
81f031b30f | ||
|
|
ee3ca2c517 | ||
|
|
50e858dcd5 | ||
|
|
8bbf16ed4f | ||
|
|
324e9810cc | ||
|
|
1aade1dcf9 | ||
|
|
787549237f | ||
|
|
088cd05e4f |
No files matched your search
@@ -25,4 +25,6 @@ jobs:
|
|||||||
- run: npm ci
|
- run: npm ci
|
||||||
- run: node tools/check-i18n.mjs
|
- run: node tools/check-i18n.mjs
|
||||||
- run: npm run build
|
- run: npm run build
|
||||||
|
- run: node --experimental-strip-types --test tools/*.test.mjs
|
||||||
|
- run: python -B -m unittest discover -s tools -p test_launcher_bridge.py
|
||||||
- run: cargo test --workspace --locked
|
- run: cargo test --workspace --locked
|
||||||
@@ -70,7 +70,9 @@ jobs:
|
|||||||
node-version: 22
|
node-version: 22
|
||||||
- run: npm ci
|
- run: npm ci
|
||||||
- name: Tests
|
- name: Tests
|
||||||
run: cargo test --workspace -- --test-threads=1
|
run: cargo test --workspace --locked -- --test-threads=1
|
||||||
|
- run: node --experimental-strip-types --test tools/*.test.mjs
|
||||||
|
- run: python -B -m unittest discover -s tools -p test_launcher_bridge.py
|
||||||
- name: Build and sign (publish only when requested)
|
- name: Build and sign (publish only when requested)
|
||||||
id: tauri
|
id: tauri
|
||||||
uses: tauri-apps/tauri-action@v0
|
uses: tauri-apps/tauri-action@v0
|
||||||
|
|||||||
@@ -8,6 +8,32 @@ Published releases and previews. Pre-release entries do not change the stable up
|
|||||||
|
|
||||||
Dates follow GitHub publication (UTC); legacy records retain their archived dates. Newest releases first.
|
Dates follow GitHub publication (UTC); legacy records retain their archived dates. Newest releases first.
|
||||||
|
|
||||||
|
## 0.9.1 — 2026-10-28
|
||||||
|
|
||||||
|
**Portable Characters are experimental and may contain bugs.**
|
||||||
|
|
||||||
|
- Existing unsupported character records no longer block unrelated server updates.
|
||||||
|
|
||||||
|
[Release](https://github.com/Corfirean/coa-server-manager/releases/tag/v0.9.1) · [Source changes](https://github.com/Corfirean/coa-server-manager/compare/v0.9.0...v0.9.1)
|
||||||
|
|
||||||
|
## 0.9.0 — 2026-10-28
|
||||||
|
|
||||||
|
**Portable Characters are experimental and may contain bugs.**
|
||||||
|
|
||||||
|
- Choose Parallel or Global level scaling in module settings.
|
||||||
|
- Report Content Scaling problems directly to its repository.
|
||||||
|
- Send custom race problem reports directly to their maintainer.
|
||||||
|
- Internet sharing restores the LAN address after server restarts.
|
||||||
|
- Configure custom race availability for new characters.
|
||||||
|
- Public listing offers every realm that starts together, not just the main one.
|
||||||
|
- Public listing is a short list of realms with a window for the details.
|
||||||
|
- Configure profession and defense skill gains in server settings.
|
||||||
|
- Starting a server sets the character classes of the realm chosen on Overview.
|
||||||
|
- Start Wildcard and Warcraft Reborn together with Conquest of Azeroth.
|
||||||
|
- Control portable characters and keep Manager running in the system tray.
|
||||||
|
|
||||||
|
[Release](https://github.com/Corfirean/coa-server-manager/releases/tag/v0.9.0) · [Source changes](https://github.com/Corfirean/coa-server-manager/compare/v0.8.2...v0.9.0)
|
||||||
|
|
||||||
## 0.8.2 — 2026-10-27
|
## 0.8.2 — 2026-10-27
|
||||||
|
|
||||||
**Portable Characters are experimental and may contain bugs.**
|
**Portable Characters are experimental and may contain bugs.**
|
||||||
|
|||||||
Generated
+3
-3
@@ -586,7 +586,7 @@ dependencies = [
|
|||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "coa-core"
|
name = "coa-core"
|
||||||
version = "0.9.0"
|
version = "0.9.2"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"base64 0.22.1",
|
"base64 0.22.1",
|
||||||
"chrono",
|
"chrono",
|
||||||
@@ -634,7 +634,7 @@ dependencies = [
|
|||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "coa-release"
|
name = "coa-release"
|
||||||
version = "0.9.0"
|
version = "0.9.2"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"chrono",
|
"chrono",
|
||||||
"coa-core",
|
"coa-core",
|
||||||
@@ -643,7 +643,7 @@ dependencies = [
|
|||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "coa-server-manager"
|
name = "coa-server-manager"
|
||||||
version = "0.9.0"
|
version = "0.9.2"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"coa-control-proto",
|
"coa-control-proto",
|
||||||
"coa-core",
|
"coa-core",
|
||||||
|
|||||||
+1
-1
@@ -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"]
|
exclude = ["services/coa-registry", "services/coa-registry-e2e", "services/coa-coordinator", "services/coa-relay"]
|
||||||
|
|
||||||
[workspace.package]
|
[workspace.package]
|
||||||
version = "0.9.0"
|
version = "0.9.2"
|
||||||
edition = "2021"
|
edition = "2021"
|
||||||
license = "AGPL-3.0-only"
|
license = "AGPL-3.0-only"
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,7 @@
|
|||||||
|
---
|
||||||
|
area: manager
|
||||||
|
type: added
|
||||||
|
audience: admins
|
||||||
|
title: Find and edit CoA options in the existing server settings
|
||||||
|
---
|
||||||
|
Search includes the separate CoA configuration, including legacy mount flight. Changes go to the correct file; realm profile controls stay managed by the Manager.
|
||||||
@@ -0,0 +1,7 @@
|
|||||||
|
---
|
||||||
|
area: manager
|
||||||
|
type: fixed
|
||||||
|
audience: admins
|
||||||
|
title: Existing unsupported character records no longer block unrelated server updates
|
||||||
|
---
|
||||||
|
Updates compare each affected character with its saved pre-update state. Unchanged older problems are reported as warnings without changing characters. Newly missing race/class data still blocks the update and triggers recovery; schema and identity checks remain enforced.
|
||||||
@@ -0,0 +1,7 @@
|
|||||||
|
---
|
||||||
|
area: manager
|
||||||
|
type: fixed
|
||||||
|
audience: admins
|
||||||
|
title: Recovery can stop an unfinished world startup after restoring an older launcher
|
||||||
|
---
|
||||||
|
If the world console is unavailable, stop only the verified recorded world process. Keep MySQL running if ownership or shutdown cannot be confirmed.
|
||||||
@@ -0,0 +1,7 @@
|
|||||||
|
---
|
||||||
|
area: manager
|
||||||
|
type: fixed
|
||||||
|
audience: admins
|
||||||
|
title: New server installation waits for slower database startup
|
||||||
|
---
|
||||||
|
Allow up to five minutes for MySQL to become ready. Failed installations stop their temporary database before cleaning up its files.
|
||||||
@@ -0,0 +1,7 @@
|
|||||||
|
---
|
||||||
|
area: manager
|
||||||
|
type: fixed
|
||||||
|
audience: admins
|
||||||
|
title: Simultaneous update checks share results or wait their turn
|
||||||
|
---
|
||||||
|
Repeated checks no longer compete with another foreground or background check in the same Manager window. Maintenance and recovery locks remain enforced.
|
||||||
+51
-1
@@ -123,6 +123,7 @@
|
|||||||
"Corfirean/coa-server-manager:20261021-scaling-health-settings.md",
|
"Corfirean/coa-server-manager:20261021-scaling-health-settings.md",
|
||||||
"Corfirean/coa-server-manager:20261021-warcraft-reborn-realm.md",
|
"Corfirean/coa-server-manager:20261021-warcraft-reborn-realm.md",
|
||||||
"Corfirean/coa-server-manager:20261022-custom-races-client.md",
|
"Corfirean/coa-server-manager:20261022-custom-races-client.md",
|
||||||
|
"Corfirean/coa-server-manager:20261022-scaling-progression-modes.md",
|
||||||
"Corfirean/coa-server-manager:20261023-ah-bot-single-switch.md",
|
"Corfirean/coa-server-manager:20261023-ah-bot-single-switch.md",
|
||||||
"Corfirean/coa-server-manager:20261023-interface-language-coverage.md",
|
"Corfirean/coa-server-manager:20261023-interface-language-coverage.md",
|
||||||
"Corfirean/coa-server-manager:20261023-online-players-exclude-squid-bots.md",
|
"Corfirean/coa-server-manager:20261023-online-players-exclude-squid-bots.md",
|
||||||
@@ -138,7 +139,18 @@
|
|||||||
"Corfirean/coa-server-manager:20261024-remote-refresh.md",
|
"Corfirean/coa-server-manager:20261024-remote-refresh.md",
|
||||||
"Corfirean/coa-server-manager:20261025-custom-races-191.md",
|
"Corfirean/coa-server-manager:20261025-custom-races-191.md",
|
||||||
"Corfirean/coa-server-manager:20261026-custom-races-192.md",
|
"Corfirean/coa-server-manager:20261026-custom-races-192.md",
|
||||||
"Corfirean/coa-server-manager:20261027-merged-database-migration-order.md"
|
"Corfirean/coa-server-manager:20261027-content-scaling-reports.md",
|
||||||
|
"Corfirean/coa-server-manager:20261027-custom-races-reports.md",
|
||||||
|
"Corfirean/coa-server-manager:20261027-internet-lan-address.md",
|
||||||
|
"Corfirean/coa-server-manager:20261027-merged-database-migration-order.md",
|
||||||
|
"Corfirean/coa-server-manager:20261027-per-race-server-settings.md",
|
||||||
|
"Corfirean/coa-server-manager:20261027-public-list-shows-every-running-realm.md",
|
||||||
|
"Corfirean/coa-server-manager:20261027-public-listing-window.md",
|
||||||
|
"Corfirean/coa-server-manager:20261027-skill-gain-controls.md",
|
||||||
|
"Corfirean/coa-server-manager:20261027-start-checks-the-realm-class-setting.md",
|
||||||
|
"Corfirean/coa-server-manager:20261027-start-wildcard-and-reborn-with-coa.md",
|
||||||
|
"Corfirean/coa-server-manager:20261028-existing-character-update-validation.md",
|
||||||
|
"Corfirean/coa-server-manager:20261028-portable-settings-and-tray.md"
|
||||||
],
|
],
|
||||||
"releases": [
|
"releases": [
|
||||||
{
|
{
|
||||||
@@ -721,6 +733,44 @@
|
|||||||
"experimentalFeatures": [
|
"experimentalFeatures": [
|
||||||
"portable-characters"
|
"portable-characters"
|
||||||
]
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"tag": "v0.9.0",
|
||||||
|
"version": "0.9.0",
|
||||||
|
"date": "2026-10-28",
|
||||||
|
"url": "https://github.com/Corfirean/coa-server-manager/releases/tag/v0.9.0",
|
||||||
|
"notes": [
|
||||||
|
"Choose Parallel or Global level scaling in module settings",
|
||||||
|
"Report Content Scaling problems directly to its repository",
|
||||||
|
"Send custom race problem reports directly to their maintainer",
|
||||||
|
"Internet sharing restores the LAN address after server restarts",
|
||||||
|
"Configure custom race availability for new characters",
|
||||||
|
"Public listing offers every realm that starts together, not just the main one",
|
||||||
|
"Public listing is a short list of realms with a window for the details",
|
||||||
|
"Configure profession and defense skill gains in server settings",
|
||||||
|
"Starting a server sets the character classes of the realm chosen on Overview",
|
||||||
|
"Start Wildcard and Warcraft Reborn together with Conquest of Azeroth",
|
||||||
|
"Control portable characters and keep Manager running in the system tray"
|
||||||
|
],
|
||||||
|
"commit": "dc97095bd6b36d9b5111f04f0cfd88e1fb2ab1f1",
|
||||||
|
"compare": "https://github.com/Corfirean/coa-server-manager/compare/v0.8.2...v0.9.0",
|
||||||
|
"experimentalFeatures": [
|
||||||
|
"portable-characters"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"version": "0.9.1",
|
||||||
|
"tag": "v0.9.1",
|
||||||
|
"date": "2026-10-28",
|
||||||
|
"notes": [
|
||||||
|
"Existing unsupported character records no longer block unrelated server updates"
|
||||||
|
],
|
||||||
|
"experimentalFeatures": [
|
||||||
|
"portable-characters"
|
||||||
|
],
|
||||||
|
"url": "https://github.com/Corfirean/coa-server-manager/releases/tag/v0.9.1",
|
||||||
|
"compare": "https://github.com/Corfirean/coa-server-manager/compare/v0.9.0...v0.9.1",
|
||||||
|
"commit": "8bbf16ed4f14e9b78c680783e4be5d8c580cc06b"
|
||||||
}
|
}
|
||||||
]
|
]
|
||||||
}
|
}
|
||||||
@@ -1,5 +1,5 @@
|
|||||||
//! Every setting of the world server's configuration, for people who want more than the curated list: the documented
|
//! Every setting of the world server's configuration, for people who want more than the curated list: the documented
|
||||||
//! settings come from `worldserver.conf.dist` (the file that ships with the server and explains each one), the current
|
//! settings come from `worldserver.conf.dist` and `modules/coa.conf.dist`, the current
|
||||||
//! values from the configuration the next start will use. Anything that holds a password, a port, an address, a folder or
|
//! values from the configuration the next start will use. Anything that holds a password, a port, an address, a folder or
|
||||||
//! the database connection is left out; the Manager owns those.
|
//! the database connection is left out; the Manager owns those.
|
||||||
|
|
||||||
@@ -10,7 +10,7 @@ use std::path::Path;
|
|||||||
use serde::Serialize;
|
use serde::Serialize;
|
||||||
|
|
||||||
use crate::config::parser::ConfFile;
|
use crate::config::parser::ConfFile;
|
||||||
use crate::config::{take_snapshot, targets, Scope};
|
use crate::config::{take_snapshot, targets, Scope, Targets};
|
||||||
use crate::error::{Error, Result};
|
use crate::error::{Error, Result};
|
||||||
use crate::fsx;
|
use crate::fsx;
|
||||||
|
|
||||||
@@ -39,6 +39,14 @@ fn hidden(key: &str) -> bool {
|
|||||||
|| k.starts_with("logindatabase.")
|
|| k.starts_with("logindatabase.")
|
||||||
|| k.starts_with("worlddatabase.")
|
|| k.starts_with("worlddatabase.")
|
||||||
|| k.starts_with("characterdatabase.")
|
|| k.starts_with("characterdatabase.")
|
||||||
|
|| [
|
||||||
|
"coa.classmodel",
|
||||||
|
"coa.realmtype",
|
||||||
|
"coa.gamemodemask",
|
||||||
|
"coa.mapclass10towarrior",
|
||||||
|
"coa.clientbooleanconfigs",
|
||||||
|
]
|
||||||
|
.contains(&k.as_str())
|
||||||
|| [
|
|| [
|
||||||
"bindip",
|
"bindip",
|
||||||
"realmid",
|
"realmid",
|
||||||
@@ -121,52 +129,85 @@ fn dist_path(root: &Path) -> std::path::PathBuf {
|
|||||||
root.join("Core/configs/worldserver.conf.dist")
|
root.join("Core/configs/worldserver.conf.dist")
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fn sources(root: &Path) -> Result<Vec<(std::path::PathBuf, Targets)>> {
|
||||||
|
let mut result = vec![(dist_path(root), targets(root, Scope::Server)?)];
|
||||||
|
let dist = root.join("Core/configs/modules/coa.conf.dist");
|
||||||
|
if dist.is_file() {
|
||||||
|
let active = root.join("Core/configs/modules/coa.conf");
|
||||||
|
result.push((
|
||||||
|
dist,
|
||||||
|
Targets {
|
||||||
|
read: active.clone(),
|
||||||
|
writes: vec![active],
|
||||||
|
generated: None,
|
||||||
|
},
|
||||||
|
));
|
||||||
|
}
|
||||||
|
Ok(result)
|
||||||
|
}
|
||||||
|
|
||||||
pub fn list(root: &Path) -> Result<Vec<Item>> {
|
pub fn list(root: &Path) -> Result<Vec<Item>> {
|
||||||
let dist = fs::read_to_string(dist_path(root)).map_err(|_| {
|
let mut items = Vec::new();
|
||||||
Error::Invalid(
|
for (dist_path, t) in sources(root)? {
|
||||||
"The documented settings file (worldserver.conf.dist) was not found on this server."
|
let dist = fs::read_to_string(&dist_path)?;
|
||||||
.into(),
|
let active = ConfFile::parse_bytes(&if t.read.exists() {
|
||||||
)
|
fs::read(&t.read)?
|
||||||
})?;
|
} else {
|
||||||
let t = targets(root, Scope::Server)?;
|
dist.as_bytes().to_vec()
|
||||||
let active = ConfFile::parse_bytes(&fs::read(&t.read)?)?;
|
})?;
|
||||||
Ok(parse_dist(&dist)
|
items.extend(
|
||||||
.into_iter()
|
parse_dist(&dist)
|
||||||
.filter(|(k, _, _)| !hidden(k))
|
.into_iter()
|
||||||
.map(|(key, default, doc)| {
|
.filter(|(k, _, _)| !hidden(k))
|
||||||
let value = active
|
.map(|(key, default, doc)| {
|
||||||
.get(&key)
|
let value = active
|
||||||
.map(|v| v.trim().to_string())
|
.get(&key)
|
||||||
.unwrap_or_else(|| default.clone());
|
.map(|v| v.trim().to_string())
|
||||||
let changed = value != default;
|
.unwrap_or_else(|| default.clone());
|
||||||
Item {
|
let changed = value != default;
|
||||||
key,
|
Item {
|
||||||
value,
|
key,
|
||||||
default,
|
value,
|
||||||
doc,
|
default,
|
||||||
changed,
|
doc,
|
||||||
}
|
changed,
|
||||||
})
|
}
|
||||||
.collect())
|
})
|
||||||
|
.collect::<Vec<_>>(),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
Ok(items)
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Change settings that exist in the documented file. A value is one line of at most 500 characters. Returns the keys
|
/// Change settings that exist in the documented file. A value is one line of at most 500 characters. Returns the keys
|
||||||
/// that actually changed; the previous files are snapshotted first (and can be restored from Settings).
|
/// that actually changed; the previous files are snapshotted first (and can be restored from Settings).
|
||||||
pub fn save(root: &Path, meta: &Path, changes: &BTreeMap<String, String>) -> Result<Vec<String>> {
|
pub fn save(root: &Path, meta: &Path, changes: &BTreeMap<String, String>) -> Result<Vec<String>> {
|
||||||
let known: BTreeMap<String, String> =
|
let _lock = crate::update::operation_lock(meta)?;
|
||||||
parse_dist(&fs::read_to_string(dist_path(root)).map_err(|_| {
|
crate::update::ensure_recovered(meta)?;
|
||||||
Error::Invalid("worldserver.conf.dist was not found on this server.".into())
|
let sources = sources(root)?;
|
||||||
})?)
|
let mut known = BTreeMap::new();
|
||||||
.into_iter()
|
|
||||||
.map(|(k, d, _)| (k, d))
|
|
||||||
.collect();
|
|
||||||
let t = targets(root, Scope::Server)?;
|
|
||||||
let mut originals: Vec<(std::path::PathBuf, Vec<u8>)> = Vec::new();
|
let mut originals: Vec<(std::path::PathBuf, Vec<u8>)> = Vec::new();
|
||||||
let mut confs: Vec<ConfFile> = Vec::new();
|
let mut confs: Vec<ConfFile> = Vec::new();
|
||||||
for p in &t.writes {
|
let mut owners = Vec::new();
|
||||||
let bytes = fs::read(p)?;
|
for (index, (dist, t)) in sources.iter().enumerate() {
|
||||||
confs.push(ConfFile::parse_bytes(&bytes)?);
|
let defaults = fs::read(dist)?;
|
||||||
originals.push((p.clone(), bytes));
|
for (key, default, _) in parse_dist(&String::from_utf8_lossy(&defaults)) {
|
||||||
|
if known.insert(key.clone(), (default, index)).is_some() {
|
||||||
|
return Err(Error::Invalid(format!(
|
||||||
|
"{key} is documented in more than one configuration file."
|
||||||
|
)));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for p in &t.writes {
|
||||||
|
let bytes = if p.exists() {
|
||||||
|
fs::read(p)?
|
||||||
|
} else {
|
||||||
|
defaults.clone()
|
||||||
|
};
|
||||||
|
confs.push(ConfFile::parse_bytes(&bytes)?);
|
||||||
|
originals.push((p.clone(), bytes));
|
||||||
|
owners.push(index);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
let mut changed = Vec::new();
|
let mut changed = Vec::new();
|
||||||
for (key, value) in changes {
|
for (key, value) in changes {
|
||||||
@@ -181,10 +222,22 @@ pub fn save(root: &Path, meta: &Path, changes: &BTreeMap<String, String>) -> Res
|
|||||||
"The value of {key} must be one line of text."
|
"The value of {key} must be one line of text."
|
||||||
)));
|
)));
|
||||||
}
|
}
|
||||||
let same = confs.iter().all(|c| match c.get(key) {
|
let (default, owner) = &known[key];
|
||||||
Some(v) => v.trim() == value,
|
if default.parse::<f64>().is_ok() && !value.parse::<f64>().is_ok_and(f64::is_finite)
|
||||||
None => known[key] == value,
|
|| key == "CoA.LegacyMountFlight" && !matches!(value, "0" | "1")
|
||||||
});
|
{
|
||||||
|
return Err(Error::Invalid(format!(
|
||||||
|
"The value of {key} must be a number matching its documented default."
|
||||||
|
)));
|
||||||
|
}
|
||||||
|
let same = confs
|
||||||
|
.iter()
|
||||||
|
.zip(&owners)
|
||||||
|
.filter(|(_, index)| *index == owner)
|
||||||
|
.all(|(c, _)| match c.get(key) {
|
||||||
|
Some(v) => v.trim() == value,
|
||||||
|
None => default == value,
|
||||||
|
});
|
||||||
if !same {
|
if !same {
|
||||||
changed.push((key.clone(), value.to_string()));
|
changed.push((key.clone(), value.to_string()));
|
||||||
}
|
}
|
||||||
@@ -192,20 +245,31 @@ pub fn save(root: &Path, meta: &Path, changes: &BTreeMap<String, String>) -> Res
|
|||||||
if changed.is_empty() {
|
if changed.is_empty() {
|
||||||
return Ok(Vec::new());
|
return Ok(Vec::new());
|
||||||
}
|
}
|
||||||
for c in &mut confs {
|
for (c, owner) in confs.iter_mut().zip(&owners) {
|
||||||
for (k, v) in &changed {
|
for (k, v) in &changed {
|
||||||
c.set(k, v, &["Added by CoA Server Manager"]);
|
if known[k].1 == *owner {
|
||||||
|
c.set(k, v, &["Added by CoA Server Manager"]);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
let texts: Vec<String> = confs.iter().map(ConfFile::to_text).collect();
|
let texts: Vec<String> = confs.iter().map(ConfFile::to_text).collect();
|
||||||
for text in &texts {
|
for (text, owner) in texts.iter().zip(&owners) {
|
||||||
let reread = ConfFile::parse(text);
|
let reread = ConfFile::parse(text);
|
||||||
for (k, v) in &changed {
|
for (k, v) in &changed {
|
||||||
if reread.get(k).map(str::trim) != Some(v.as_str()) {
|
if known[k].1 == *owner && reread.get(k).map(str::trim) != Some(v.as_str()) {
|
||||||
return Err(Error::Invalid(format!("internal check failed for {k}")));
|
return Err(Error::Invalid(format!("internal check failed for {k}")));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
let affected: std::collections::BTreeSet<_> =
|
||||||
|
changed.iter().map(|(key, _)| known[key].1).collect();
|
||||||
|
let (originals, texts): (Vec<_>, Vec<_>) = originals
|
||||||
|
.into_iter()
|
||||||
|
.zip(texts)
|
||||||
|
.zip(owners)
|
||||||
|
.filter(|(_, owner)| affected.contains(owner))
|
||||||
|
.map(|(pair, _)| pair)
|
||||||
|
.unzip();
|
||||||
take_snapshot(
|
take_snapshot(
|
||||||
meta,
|
meta,
|
||||||
Scope::Server,
|
Scope::Server,
|
||||||
@@ -232,6 +296,114 @@ pub fn save(root: &Path, meta: &Path, changes: &BTreeMap<String, String>) -> Res
|
|||||||
mod tests {
|
mod tests {
|
||||||
use super::*;
|
use super::*;
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn unrelated_saves_do_not_create_coa_files_and_existing_realm_values_are_preserved() {
|
||||||
|
let d = tempfile::tempdir().unwrap();
|
||||||
|
let (root, meta) = server(d.path());
|
||||||
|
let module = root.join("Core/configs/modules");
|
||||||
|
fs::create_dir_all(&module).unwrap();
|
||||||
|
fs::write(
|
||||||
|
module.join("coa.conf.dist"),
|
||||||
|
"CoA.LegacyMountFlight = 0\nCoA.ClassModel = \"coa\"\n",
|
||||||
|
)
|
||||||
|
.unwrap();
|
||||||
|
save(
|
||||||
|
&root,
|
||||||
|
&meta,
|
||||||
|
&BTreeMap::from([("Rate.Drop.Item.Rare".into(), "1.5".into())]),
|
||||||
|
)
|
||||||
|
.unwrap();
|
||||||
|
assert!(!module.join("coa.conf").exists());
|
||||||
|
fs::write(
|
||||||
|
module.join("coa.conf"),
|
||||||
|
"# Reborn realm\nCoA.ClassModel = \"wcr\"\nCustom.Preserved = 42\n",
|
||||||
|
)
|
||||||
|
.unwrap();
|
||||||
|
assert!(save(
|
||||||
|
&root,
|
||||||
|
&meta,
|
||||||
|
&BTreeMap::from([("CoA.ClassModel".into(), "\"coa\"".into())])
|
||||||
|
)
|
||||||
|
.is_err());
|
||||||
|
save(
|
||||||
|
&root,
|
||||||
|
&meta,
|
||||||
|
&BTreeMap::from([("CoA.LegacyMountFlight".into(), "1".into())]),
|
||||||
|
)
|
||||||
|
.unwrap();
|
||||||
|
let actual = fs::read_to_string(module.join("coa.conf")).unwrap();
|
||||||
|
assert!(
|
||||||
|
actual.contains("CoA.ClassModel = \"wcr\"") && actual.contains("Custom.Preserved = 42")
|
||||||
|
);
|
||||||
|
assert!(actual.contains("# Reborn realm"));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn coa_settings_are_found_saved_to_the_module_and_snapshotted_without_profile_overrides() {
|
||||||
|
let d = tempfile::tempdir().unwrap();
|
||||||
|
let (root, meta) = server(d.path());
|
||||||
|
let module = root.join("Core/configs/modules");
|
||||||
|
fs::create_dir_all(&module).unwrap();
|
||||||
|
let defaults = "[worldserver]\n# Mount flight rules\nCoA.LegacyMountFlight = 0\nCoA.ClassModel = \"coa\"\nCoA.RealmType = \"live\"\n";
|
||||||
|
fs::write(module.join("coa.conf.dist"), defaults).unwrap();
|
||||||
|
let original_world = fs::read(root.join("Core/configs/worldserver.conf")).unwrap();
|
||||||
|
let items = list(&root).unwrap();
|
||||||
|
assert!(items
|
||||||
|
.iter()
|
||||||
|
.any(|i| i.key == "CoA.LegacyMountFlight" && i.value == "0"));
|
||||||
|
assert!(!items
|
||||||
|
.iter()
|
||||||
|
.any(|i| i.key == "CoA.ClassModel" || i.key == "CoA.RealmType"));
|
||||||
|
for value in ["2", "invalid", "1\nInjected = 1"] {
|
||||||
|
assert!(save(
|
||||||
|
&root,
|
||||||
|
&meta,
|
||||||
|
&BTreeMap::from([("CoA.LegacyMountFlight".into(), value.into())])
|
||||||
|
)
|
||||||
|
.is_err());
|
||||||
|
}
|
||||||
|
assert!(!module.join("coa.conf").exists());
|
||||||
|
save(
|
||||||
|
&root,
|
||||||
|
&meta,
|
||||||
|
&BTreeMap::from([
|
||||||
|
("CoA.LegacyMountFlight".into(), "1".into()),
|
||||||
|
("Rate.Drop.Item.Rare".into(), "1.5".into()),
|
||||||
|
]),
|
||||||
|
)
|
||||||
|
.unwrap();
|
||||||
|
assert!(fs::read_to_string(module.join("coa.conf"))
|
||||||
|
.unwrap()
|
||||||
|
.contains("CoA.LegacyMountFlight = 1"));
|
||||||
|
let world = fs::read_to_string(root.join("Core/configs/worldserver.conf")).unwrap();
|
||||||
|
assert!(!world.contains("CoA.LegacyMountFlight"));
|
||||||
|
assert!(world.contains("Rate.Drop.Item.Rare = 1.5"));
|
||||||
|
assert!(!String::from_utf8(original_world)
|
||||||
|
.unwrap()
|
||||||
|
.contains("CoA.LegacyMountFlight"));
|
||||||
|
assert_eq!(
|
||||||
|
list(&root)
|
||||||
|
.unwrap()
|
||||||
|
.iter()
|
||||||
|
.find(|i| i.key == "CoA.LegacyMountFlight")
|
||||||
|
.unwrap()
|
||||||
|
.value,
|
||||||
|
"1"
|
||||||
|
);
|
||||||
|
assert!(!crate::config::list_snapshots(&meta).is_empty());
|
||||||
|
let saved = crate::config::list_snapshots(&meta).remove(0);
|
||||||
|
crate::config::restore_snapshot(&meta, &saved.id).unwrap();
|
||||||
|
assert_eq!(
|
||||||
|
list(&root)
|
||||||
|
.unwrap()
|
||||||
|
.iter()
|
||||||
|
.find(|i| i.key == "CoA.LegacyMountFlight")
|
||||||
|
.unwrap()
|
||||||
|
.value,
|
||||||
|
"0"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
const DIST: &str = "[worldserver]\r\n\r\n###################\r\n# SECTION\r\n###################\r\n\r\n#\r\n# Rate.Drop.Item.Epic\r\n# Rate.Drop.Item.Rare\r\n# Description: Drop rates by quality.\r\n# Default: 1\r\n#\r\n\r\nRate.Drop.Item.Rare = 1\r\nRate.Drop.Item.Epic = 1\r\n\r\n#\r\n# LoginDatabaseInfo\r\n# Description: secret\r\n#\r\n\r\nLoginDatabaseInfo = \"127.0.0.1;3306;a;b;c\"\r\n\r\n#\r\n# Instance.ResetTimeHour\r\n# Description: Hour of the reset.\r\n# Important: Use 0-23.\r\n# Default: 4\r\n#\r\n\r\nInstance.ResetTimeHour = 4\r\n";
|
const DIST: &str = "[worldserver]\r\n\r\n###################\r\n# SECTION\r\n###################\r\n\r\n#\r\n# Rate.Drop.Item.Epic\r\n# Rate.Drop.Item.Rare\r\n# Description: Drop rates by quality.\r\n# Default: 1\r\n#\r\n\r\nRate.Drop.Item.Rare = 1\r\nRate.Drop.Item.Epic = 1\r\n\r\n#\r\n# LoginDatabaseInfo\r\n# Description: secret\r\n#\r\n\r\nLoginDatabaseInfo = \"127.0.0.1;3306;a;b;c\"\r\n\r\n#\r\n# Instance.ResetTimeHour\r\n# Description: Hour of the reset.\r\n# Important: Use 0-23.\r\n# Default: 4\r\n#\r\n\r\nInstance.ResetTimeHour = 4\r\n";
|
||||||
|
|
||||||
fn server(d: &Path) -> (std::path::PathBuf, std::path::PathBuf) {
|
fn server(d: &Path) -> (std::path::PathBuf, std::path::PathBuf) {
|
||||||
|
|||||||
@@ -0,0 +1,124 @@
|
|||||||
|
//! Update-only comparison of existing unsupported character starts. Never repairs or deletes rows.
|
||||||
|
use crate::{db::Db, Error, Result};
|
||||||
|
use serde::{Deserialize, Serialize};
|
||||||
|
use std::collections::{BTreeMap, BTreeSet};
|
||||||
|
use std::path::Path;
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
|
||||||
|
pub struct MissingStart {
|
||||||
|
pub guid: u32,
|
||||||
|
pub race: u32,
|
||||||
|
pub class: u32,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||||
|
pub struct Baseline {
|
||||||
|
pub schema: u32,
|
||||||
|
pub realms: BTreeMap<String, BTreeSet<MissingStart>>,
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn parse_missing(text: &str) -> Result<BTreeSet<MissingStart>> {
|
||||||
|
text.lines()
|
||||||
|
.map(|line| {
|
||||||
|
let values = line
|
||||||
|
.split('\t')
|
||||||
|
.map(str::parse::<u32>)
|
||||||
|
.collect::<std::result::Result<Vec<_>, _>>()
|
||||||
|
.map_err(|_| {
|
||||||
|
Error::Invalid("Cannot read existing character start identities.".into())
|
||||||
|
})?;
|
||||||
|
if values.len() != 3 {
|
||||||
|
return Err(Error::Invalid(
|
||||||
|
"Incomplete character start identity.".into(),
|
||||||
|
));
|
||||||
|
}
|
||||||
|
Ok(MissingStart {
|
||||||
|
guid: values[0],
|
||||||
|
race: values[1],
|
||||||
|
class: values[2],
|
||||||
|
})
|
||||||
|
})
|
||||||
|
.collect()
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn missing(db: &Db) -> Result<BTreeSet<MissingStart>> {
|
||||||
|
parse_missing(&db.query("SELECT c.guid,c.race,c.class FROM acore_characters.characters c LEFT JOIN acore_world.playercreateinfo p ON p.race=c.race AND p.class=c.class WHERE p.race IS NULL;")?)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn capture(db: &Db, root: &Path) -> Result<Baseline> {
|
||||||
|
let mut realms = BTreeMap::new();
|
||||||
|
for mode in crate::realms::state(root)?.modes() {
|
||||||
|
realms.insert(
|
||||||
|
mode.name().to_owned(),
|
||||||
|
missing(&db.clone().for_realm(mode))?,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
Ok(Baseline { schema: 1, realms })
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Match identity and race/class, never just totals: one new failure cannot replace an old one.
|
||||||
|
pub fn introduced(
|
||||||
|
current: &BTreeSet<MissingStart>,
|
||||||
|
before: &BTreeSet<MissingStart>,
|
||||||
|
) -> BTreeSet<MissingStart> {
|
||||||
|
current.difference(before).copied().collect()
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
#[test]
|
||||||
|
fn old_gaps_are_not_new_character_loss() {
|
||||||
|
let before = parse_missing("1\t44\t14\n2\t44\t14\n3\t44\t14").unwrap();
|
||||||
|
assert!(introduced(&before, &before).is_empty());
|
||||||
|
assert!(introduced(&BTreeSet::new(), &before).is_empty());
|
||||||
|
let replaced = parse_missing("1\t44\t14\n2\t44\t14\n4\t44\t14").unwrap();
|
||||||
|
assert_eq!(
|
||||||
|
introduced(&replaced, &before),
|
||||||
|
parse_missing("4\t44\t14").unwrap()
|
||||||
|
);
|
||||||
|
let changed = parse_missing("1\t44\t15").unwrap();
|
||||||
|
assert_eq!(introduced(&changed, &before), changed);
|
||||||
|
assert_eq!(introduced(&before, &BTreeSet::new()), before);
|
||||||
|
}
|
||||||
|
#[test]
|
||||||
|
fn malformed_identity_is_not_silently_ignored() {
|
||||||
|
for text in ["1\t44", "bad\t44\t14", "1\t44\t14\t0", "1\t44\t-1"] {
|
||||||
|
assert!(parse_missing(text).is_err());
|
||||||
|
}
|
||||||
|
assert!(parse_missing("").unwrap().is_empty());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn reported_174_old_records_cannot_mask_one_newly_hidden_character() {
|
||||||
|
// Reproduce the report's scale without shipping another person's diagnostics or identities.
|
||||||
|
let before: BTreeSet<_> = (1..=174)
|
||||||
|
.map(|guid| MissingStart {
|
||||||
|
guid,
|
||||||
|
race: 44,
|
||||||
|
class: 14,
|
||||||
|
})
|
||||||
|
.collect();
|
||||||
|
assert!(introduced(&before, &before).is_empty());
|
||||||
|
let mut after = before.clone();
|
||||||
|
after.remove(&MissingStart {
|
||||||
|
guid: 1,
|
||||||
|
race: 44,
|
||||||
|
class: 14,
|
||||||
|
});
|
||||||
|
after.insert(MissingStart {
|
||||||
|
guid: 175,
|
||||||
|
race: 44,
|
||||||
|
class: 14,
|
||||||
|
});
|
||||||
|
assert_eq!(after.len(), before.len());
|
||||||
|
assert_eq!(
|
||||||
|
introduced(&after, &before),
|
||||||
|
BTreeSet::from([MissingStart {
|
||||||
|
guid: 175,
|
||||||
|
race: 44,
|
||||||
|
class: 14
|
||||||
|
}])
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -34,8 +34,8 @@ impl Verb {
|
|||||||
fn timeout(self, root: &Path) -> Duration {
|
fn timeout(self, root: &Path) -> Duration {
|
||||||
match self {
|
match self {
|
||||||
Verb::StartAll | Verb::StartWorld if squid_enabled(root) => Duration::from_secs(2700),
|
Verb::StartAll | Verb::StartWorld if squid_enabled(root) => Duration::from_secs(2700),
|
||||||
Verb::StartAll | Verb::StartWorld => Duration::from_secs(420),
|
Verb::StartAll | Verb::StartWorld => Duration::from_secs(720),
|
||||||
Verb::StartMysql => Duration::from_secs(120),
|
Verb::StartMysql => Duration::from_secs(360),
|
||||||
Verb::StopAll => Duration::from_secs(240),
|
Verb::StopAll => Duration::from_secs(240),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -393,7 +393,7 @@ fn recover_mysql_launcher_state(root: &Path, prefer_listener: bool) -> Result<()
|
|||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
const LAUNCH_SCRIPT: &str = "import runpy,sys\nfrom pathlib import Path\nscript=sys.argv[1]\nsys.path.insert(0,str(Path(script).resolve().parent))\nsys.argv=sys.argv[1:]\nif sys.argv[1]=='stop-all':\n launcher=runpy.run_path(script,run_name='coa_manager_shutdown')\n config=launcher['settings']()\n with launcher['control_lock']():\n launcher['stop_all'](config)\nelse:\n runpy.run_path(script,run_name='__main__')";
|
const LAUNCH_SCRIPT: &str = include_str!("launcher_bridge.py");
|
||||||
|
|
||||||
pub(crate) fn patch_launcher_imports(text: &str) -> Result<String> {
|
pub(crate) fn patch_launcher_imports(text: &str) -> Result<String> {
|
||||||
let line = "sys.path.insert(0, str(Path(__file__).resolve().parent))";
|
let line = "sys.path.insert(0, str(Path(__file__).resolve().parent))";
|
||||||
@@ -624,7 +624,11 @@ mod tests {
|
|||||||
std::fs::write(modules.join("playerbots.conf"), "AiPlayerbot.Enabled = 0\n").unwrap();
|
std::fs::write(modules.join("playerbots.conf"), "AiPlayerbot.Enabled = 0\n").unwrap();
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
Verb::StartWorld.timeout(folder.path()),
|
Verb::StartWorld.timeout(folder.path()),
|
||||||
Duration::from_secs(420)
|
Duration::from_secs(720)
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
Verb::StartMysql.timeout(folder.path()),
|
||||||
|
Duration::from_secs(360)
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -239,14 +239,14 @@ fn bootstrap_database_inner(root: &Path) -> Result<()> {
|
|||||||
}
|
}
|
||||||
fs::copy(&boot, &target)?; // launcher needs database.json to render its files at first start
|
fs::copy(&boot, &target)?; // launcher needs database.json to render its files at first start
|
||||||
|
|
||||||
let started = driver::run(root, Verb::StartMysql)?;
|
|
||||||
if !started.ok {
|
|
||||||
return Err(Error::Invalid(format!(
|
|
||||||
"The database could not be started. {}",
|
|
||||||
driver::startup_failure(root, &started)
|
|
||||||
)));
|
|
||||||
}
|
|
||||||
let result = (|| -> Result<()> {
|
let result = (|| -> Result<()> {
|
||||||
|
let started = driver::run(root, Verb::StartMysql)?;
|
||||||
|
if !started.ok {
|
||||||
|
return Err(Error::Invalid(format!(
|
||||||
|
"The database could not be started. {}",
|
||||||
|
driver::startup_failure(root, &started)
|
||||||
|
)));
|
||||||
|
}
|
||||||
let db = Db::from_repack(root, Account::Admin)?;
|
let db = Db::from_repack(root, Account::Admin)?;
|
||||||
let (root_pw, app_pw) = (random_hex(48), random_hex(48));
|
let (root_pw, app_pw) = (random_hex(48), random_hex(48));
|
||||||
let accounts = db.query(
|
let accounts = db.query(
|
||||||
@@ -362,6 +362,7 @@ pub fn install_base(p: &Params, report: &dyn Fn(Step)) -> Result<Installed> {
|
|||||||
// 3. Extract into our own staging folder.
|
// 3. Extract into our own staging folder.
|
||||||
if staging_root.exists() {
|
if staging_root.exists() {
|
||||||
if staging_root.join(MARKER).is_file() {
|
if staging_root.join(MARKER).is_file() {
|
||||||
|
stop_installation(&staging_root)?;
|
||||||
fs::remove_dir_all(&staging_root)?; // leftover of an earlier failed attempt that we created
|
fs::remove_dir_all(&staging_root)?; // leftover of an earlier failed attempt that we created
|
||||||
} else {
|
} else {
|
||||||
return Err(Error::Invalid(format!("{} is left over from an earlier installation that did not finish, and the Manager cannot tell whether it may be deleted. Delete that folder yourself, then try again.", staging_root.display())));
|
return Err(Error::Invalid(format!("{} is left over from an earlier installation that did not finish, and the Manager cannot tell whether it may be deleted. Delete that folder yourself, then try again.", staging_root.display())));
|
||||||
@@ -426,24 +427,60 @@ pub fn install_base(p: &Params, report: &dyn Fn(Step)) -> Result<Installed> {
|
|||||||
})();
|
})();
|
||||||
|
|
||||||
if result.is_err() {
|
if result.is_err() {
|
||||||
if staging_root.join(MARKER).exists() {
|
let unfinished = if staging_root.join(MARKER).is_file() {
|
||||||
// Unfinished work of ours; the destination was never touched.
|
Some(&staging_root)
|
||||||
let _ = driver::run(&staging_root, Verb::StopAll);
|
|
||||||
let _ = fs::remove_dir_all(&staging_root);
|
|
||||||
} else if dest.join(MARKER).is_file() {
|
} else if dest.join(MARKER).is_file() {
|
||||||
// Failed after the folder was moved into place. The destination was empty or absent before (preflight),
|
Some(&dest)
|
||||||
// so what carries our marker is only our unfinished install.
|
} else {
|
||||||
let _ = driver::run(&dest, Verb::StopAll);
|
None
|
||||||
let _ = fs::remove_dir_all(&dest);
|
};
|
||||||
|
if let Some(unfinished) = unfinished {
|
||||||
|
if let Err(cleanup) = stop_installation(unfinished) {
|
||||||
|
return Err(Error::Invalid(format!(
|
||||||
|
"{} {cleanup}",
|
||||||
|
result.as_ref().unwrap_err()
|
||||||
|
)));
|
||||||
|
}
|
||||||
|
let _ = fs::remove_dir_all(unfinished);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
result
|
result
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fn stop_installation(root: &Path) -> Result<()> {
|
||||||
|
if !root.join("Scripts/manage.py").is_file() {
|
||||||
|
return Ok(());
|
||||||
|
}
|
||||||
|
let stopped = driver::run(root, Verb::StopAll)?;
|
||||||
|
if !stopped.ok {
|
||||||
|
return Err(Error::Invalid(format!(
|
||||||
|
"The unfinished installation could not be stopped; its files were kept. {}",
|
||||||
|
driver::startup_failure(root, &stopped)
|
||||||
|
)));
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
mod tests {
|
mod tests {
|
||||||
use super::*;
|
use super::*;
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn an_unstoppable_partial_installation_keeps_its_files_for_recovery() {
|
||||||
|
let folder = tempfile::tempdir().unwrap();
|
||||||
|
let root = folder.path();
|
||||||
|
fs::create_dir_all(root.join("Scripts")).unwrap();
|
||||||
|
fs::write(root.join("Scripts/manage.py"), "# incomplete launcher").unwrap();
|
||||||
|
fs::write(root.join(MARKER), "").unwrap();
|
||||||
|
fs::write(root.join("database-preserved"), "unchanged").unwrap();
|
||||||
|
assert!(stop_installation(root).is_err());
|
||||||
|
assert_eq!(
|
||||||
|
fs::read_to_string(root.join("database-preserved")).unwrap(),
|
||||||
|
"unchanged"
|
||||||
|
);
|
||||||
|
assert!(root.join(MARKER).is_file());
|
||||||
|
}
|
||||||
|
|
||||||
fn reg(d: &Path) -> Registry {
|
fn reg(d: &Path) -> Registry {
|
||||||
Registry::at(d.join("reg/installs.json"))
|
Registry::at(d.join("reg/installs.json"))
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,50 @@
|
|||||||
|
import runpy
|
||||||
|
import sys
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
script = sys.argv[1]
|
||||||
|
sys.path.insert(0, str(Path(script).resolve().parent))
|
||||||
|
sys.argv = sys.argv[1:]
|
||||||
|
launcher = runpy.run_path(script, run_name="coa_manager_launcher")
|
||||||
|
original_wait = launcher["wait_ready"]
|
||||||
|
|
||||||
|
|
||||||
|
def wait_ready(name, port, seconds=180):
|
||||||
|
return original_wait(name, port, max(seconds, 300) if name == "mysql" else seconds)
|
||||||
|
|
||||||
|
|
||||||
|
launcher["start_mysql"].__globals__["wait_ready"] = wait_ready
|
||||||
|
if sys.argv[1] == "stop-all":
|
||||||
|
shutdown = launcher["stop_all"].__globals__
|
||||||
|
if "ra" in shutdown:
|
||||||
|
original_ra = shutdown["ra"]
|
||||||
|
|
||||||
|
class UnsafeShutdown(Exception):
|
||||||
|
pass
|
||||||
|
|
||||||
|
def shutdown_command(command, config):
|
||||||
|
try:
|
||||||
|
return original_ra(command, config)
|
||||||
|
except (OSError, RuntimeError):
|
||||||
|
if not command.startswith("server shutdown "):
|
||||||
|
raise
|
||||||
|
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.")
|
||||||
|
return "Stopped this server's recorded world process without its unavailable console."
|
||||||
|
|
||||||
|
shutdown["ra"] = shutdown_command
|
||||||
|
config = launcher["settings"]()
|
||||||
|
with launcher["control_lock"]():
|
||||||
|
launcher["stop_all"](config)
|
||||||
|
else:
|
||||||
|
launcher["main"]()
|
||||||
@@ -11,6 +11,7 @@ pub mod accounts;
|
|||||||
pub mod allsettings;
|
pub mod allsettings;
|
||||||
pub mod backup;
|
pub mod backup;
|
||||||
pub mod channels;
|
pub mod channels;
|
||||||
|
pub mod character_start_check;
|
||||||
pub mod cleanbase;
|
pub mod cleanbase;
|
||||||
pub mod client;
|
pub mod client;
|
||||||
pub mod clientdl;
|
pub mod clientdl;
|
||||||
|
|||||||
@@ -1004,6 +1004,89 @@ mod tests {
|
|||||||
};
|
};
|
||||||
let mut server = start();
|
let mut server = start();
|
||||||
db.query("CREATE DATABASE acore_characters; CREATE DATABASE acore_world; CREATE DATABASE acore_auth; CREATE TABLE acore_characters.probe(id INT PRIMARY KEY, note VARCHAR(40)); CREATE TABLE acore_world.probe(id INT NOT NULL DEFAULT 0); INSERT INTO acore_world.probe VALUES(43); CREATE TABLE acore_auth.probe(id INT); INSERT INTO acore_auth.probe VALUES(44); CREATE USER 'fixture_user'@'localhost' IDENTIFIED BY 'fixture'; CREATE TRIGGER acore_characters.probe_insert BEFORE INSERT ON acore_characters.probe FOR EACH ROW SET NEW.note='triggered'; INSERT INTO acore_characters.probe VALUES(42,'original'); CREATE VIEW acore_characters.probe_view AS SELECT c.id,w.id AS world_id FROM acore_characters.probe c CROSS JOIN acore_world.probe w; CREATE PROCEDURE acore_characters.probe_proc() SELECT id FROM acore_characters.probe; CREATE FUNCTION acore_characters.probe_func() RETURNS INT DETERMINISTIC RETURN 73;").unwrap();
|
db.query("CREATE DATABASE acore_characters; CREATE DATABASE acore_world; CREATE DATABASE acore_auth; CREATE TABLE acore_characters.probe(id INT PRIMARY KEY, note VARCHAR(40)); CREATE TABLE acore_world.probe(id INT NOT NULL DEFAULT 0); INSERT INTO acore_world.probe VALUES(43); CREATE TABLE acore_auth.probe(id INT); INSERT INTO acore_auth.probe VALUES(44); CREATE USER 'fixture_user'@'localhost' IDENTIFIED BY 'fixture'; CREATE TRIGGER acore_characters.probe_insert BEFORE INSERT ON acore_characters.probe FOR EACH ROW SET NEW.note='triggered'; INSERT INTO acore_characters.probe VALUES(42,'original'); CREATE VIEW acore_characters.probe_view AS SELECT c.id,w.id AS world_id FROM acore_characters.probe c CROSS JOIN acore_world.probe w; CREATE PROCEDURE acore_characters.probe_proc() SELECT id FROM acore_characters.probe; CREATE FUNCTION acore_characters.probe_func() RETURNS INT DETERMINISTIC RETURN 73;").unwrap();
|
||||||
|
// Regression: an upgrade must distinguish pre-existing unsupported character starts
|
||||||
|
// from a newly lost start, without weakening any structural schema check.
|
||||||
|
db.query("CREATE TABLE acore_characters.characters(guid INT UNSIGNED PRIMARY KEY,race INT UNSIGNED NOT NULL,class INT UNSIGNED NOT NULL); CREATE TABLE acore_world.playercreateinfo(race INT UNSIGNED,class INT UNSIGNED,PRIMARY KEY(race,class)); INSERT INTO acore_characters.characters VALUES(100,44,14),(101,44,14),(102,7,14);").unwrap();
|
||||||
|
let starts = [1, 2, 3, 4, 5, 6, 7, 8, 10, 11]
|
||||||
|
.into_iter()
|
||||||
|
.flat_map(|race| (12..=32).map(move |class| format!("({race},{class})")))
|
||||||
|
.collect::<Vec<_>>()
|
||||||
|
.join(",");
|
||||||
|
db.query(&format!(
|
||||||
|
"INSERT INTO acore_world.playercreateinfo VALUES {starts};"
|
||||||
|
))
|
||||||
|
.unwrap();
|
||||||
|
crate::schema_check::capture(&db, &root).unwrap();
|
||||||
|
let baseline = crate::character_start_check::capture(&db, &root).unwrap();
|
||||||
|
assert_eq!(baseline.realms[crate::realms::Mode::Coa.name()].len(), 2);
|
||||||
|
assert!(
|
||||||
|
!crate::schema_check::check(&db, &root).unwrap().is_empty(),
|
||||||
|
"ordinary diagnostics stay strict"
|
||||||
|
);
|
||||||
|
assert!(
|
||||||
|
crate::schema_check::check_update_with_report(&db, &root, Some(&baseline))
|
||||||
|
.unwrap()
|
||||||
|
.is_empty(),
|
||||||
|
"unchanged old gaps must not block an unrelated upgrade"
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
db.query("SELECT COUNT(*) FROM acore_characters.characters;")
|
||||||
|
.unwrap()
|
||||||
|
.trim(),
|
||||||
|
"3"
|
||||||
|
);
|
||||||
|
let report_dir = crate::registry::metadata_dir_for(&root)
|
||||||
|
.unwrap()
|
||||||
|
.join("diagnostics");
|
||||||
|
let report_path = fs::read_dir(report_dir)
|
||||||
|
.unwrap()
|
||||||
|
.flatten()
|
||||||
|
.map(|e| e.path())
|
||||||
|
.find(|p| {
|
||||||
|
p.file_name()
|
||||||
|
.unwrap()
|
||||||
|
.to_string_lossy()
|
||||||
|
.starts_with("schema-validation-")
|
||||||
|
})
|
||||||
|
.unwrap();
|
||||||
|
let report: serde_json::Value = fsx::read_json(&report_path).unwrap();
|
||||||
|
assert_eq!(report["preexistingUnsupportedCharacters"], 2);
|
||||||
|
assert_eq!(
|
||||||
|
report["preexistingCharacterStarts"],
|
||||||
|
serde_json::json!([{"race":44,"class":14,"count":2}])
|
||||||
|
);
|
||||||
|
assert_eq!(report["problems"], serde_json::json!([]));
|
||||||
|
// Same count and race/class but a different GUID must still block.
|
||||||
|
db.query("UPDATE acore_characters.characters SET guid=103 WHERE guid=101;")
|
||||||
|
.unwrap();
|
||||||
|
assert!(
|
||||||
|
!crate::schema_check::check_update_with_report(&db, &root, Some(&baseline))
|
||||||
|
.unwrap()
|
||||||
|
.is_empty()
|
||||||
|
);
|
||||||
|
db.query("UPDATE acore_characters.characters SET guid=101 WHERE guid=103;")
|
||||||
|
.unwrap();
|
||||||
|
// Loss of a formerly valid start is never grandfathered.
|
||||||
|
db.query("DELETE FROM acore_world.playercreateinfo WHERE race=7 AND class=14;")
|
||||||
|
.unwrap();
|
||||||
|
assert!(
|
||||||
|
!crate::schema_check::check_update_with_report(&db, &root, Some(&baseline))
|
||||||
|
.unwrap()
|
||||||
|
.is_empty()
|
||||||
|
);
|
||||||
|
db.query("INSERT INTO acore_world.playercreateinfo VALUES(7,14);")
|
||||||
|
.unwrap();
|
||||||
|
db.query("ALTER TABLE acore_world.probe MODIFY id VARCHAR(30) NOT NULL DEFAULT '0';")
|
||||||
|
.unwrap();
|
||||||
|
assert!(
|
||||||
|
!crate::schema_check::check_update_with_report(&db, &root, Some(&baseline))
|
||||||
|
.unwrap()
|
||||||
|
.is_empty(),
|
||||||
|
"existing character warnings cannot hide a structural failure"
|
||||||
|
);
|
||||||
|
db.query("ALTER TABLE acore_world.probe MODIFY id INT NOT NULL DEFAULT 0; DROP TABLE acore_characters.characters; DROP TABLE acore_world.playercreateinfo;").unwrap();
|
||||||
|
fs::remove_file(root.join(crate::schema_check::CONTRACT)).unwrap();
|
||||||
|
|
||||||
// Shared auth must not run again when the active realm changes.
|
// Shared auth must not run again when the active realm changes.
|
||||||
use crate::migrations::Store;
|
use crate::migrations::Store;
|
||||||
db.query("CREATE DATABASE acore_world_wildcard;").unwrap();
|
db.query("CREATE DATABASE acore_world_wildcard;").unwrap();
|
||||||
|
|||||||
@@ -95,13 +95,42 @@ pub struct Problem {
|
|||||||
|
|
||||||
/// Keep all differences for support; never change a database to match a contract automatically.
|
/// Keep all differences for support; never change a database to match a contract automatically.
|
||||||
pub fn check_with_report(db: &Db, root: &Path) -> Result<Vec<Problem>> {
|
pub fn check_with_report(db: &Db, root: &Path) -> Result<Vec<Problem>> {
|
||||||
let problems = check(db, root)?;
|
check_update_with_report(db, root, None)
|
||||||
if problems.is_empty() {
|
}
|
||||||
|
|
||||||
|
/// Only a hash-verified pre-update baseline may downgrade unchanged missing starts to warnings.
|
||||||
|
pub fn check_update_with_report(
|
||||||
|
db: &Db,
|
||||||
|
root: &Path,
|
||||||
|
baseline: Option<&crate::character_start_check::Baseline>,
|
||||||
|
) -> Result<Vec<Problem>> {
|
||||||
|
let mut preexisting = BTreeMap::new();
|
||||||
|
let before = match baseline {
|
||||||
|
Some(b) if b.schema == 1 => Some(b.realms.get(db.realm().name()).ok_or_else(|| {
|
||||||
|
crate::Error::Invalid("The character baseline does not contain this realm.".into())
|
||||||
|
})?),
|
||||||
|
Some(_) => {
|
||||||
|
return Err(crate::Error::Invalid(
|
||||||
|
"Unsupported character start baseline.".into(),
|
||||||
|
))
|
||||||
|
}
|
||||||
|
None => None,
|
||||||
|
};
|
||||||
|
let problems = check_inner(db, root, before, &mut preexisting)?;
|
||||||
|
let existing: usize = preexisting.values().sum();
|
||||||
|
let preexisting_details: Vec<_> = preexisting.into_iter().map(|((race, class), count)| serde_json::json!({"race": race, "class": class, "count": count})).collect();
|
||||||
|
if existing > 0 {
|
||||||
|
tracing::warn!(realm = db.realm().name(), characters = existing, "Unchanged pre-update characters with missing starting data retained; no character records were repaired or deleted");
|
||||||
|
}
|
||||||
|
if problems.is_empty() && existing == 0 {
|
||||||
return Ok(problems);
|
return Ok(problems);
|
||||||
}
|
}
|
||||||
let report = serde_json::json!({
|
let report = serde_json::json!({
|
||||||
"schema": 1, "checkedAt": chrono::Utc::now().to_rfc3339(),
|
"schema": 1, "checkedAt": chrono::Utc::now().to_rfc3339(),
|
||||||
"realm": db.realm().name(), "problems": problems,
|
"realm": db.realm().name(), "problems": problems,
|
||||||
|
"preexistingUnsupportedCharacters": existing,
|
||||||
|
"preexistingCharacterStarts": preexisting_details,
|
||||||
|
"note": "Unchanged pre-update missing starts are reported separately. New missing character starts and all schema errors still block the update.",
|
||||||
});
|
});
|
||||||
let path = crate::registry::metadata_dir_for(root)?
|
let path = crate::registry::metadata_dir_for(root)?
|
||||||
.join("diagnostics")
|
.join("diagnostics")
|
||||||
@@ -245,6 +274,15 @@ pub(crate) fn repair_missing_defaults(
|
|||||||
}
|
}
|
||||||
|
|
||||||
pub fn check(db: &Db, root: &Path) -> Result<Vec<Problem>> {
|
pub fn check(db: &Db, root: &Path) -> Result<Vec<Problem>> {
|
||||||
|
check_inner(db, root, None, &mut BTreeMap::new())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn check_inner(
|
||||||
|
db: &Db,
|
||||||
|
root: &Path,
|
||||||
|
before: Option<&BTreeSet<crate::character_start_check::MissingStart>>,
|
||||||
|
existing: &mut BTreeMap<(u32, u32), usize>,
|
||||||
|
) -> Result<Vec<Problem>> {
|
||||||
let contract = if root.join(CONTRACT).is_file() {
|
let contract = if root.join(CONTRACT).is_file() {
|
||||||
let contract: Contract = fsx::read_json(&root.join(CONTRACT))?;
|
let contract: Contract = fsx::read_json(&root.join(CONTRACT))?;
|
||||||
if contract.schema != 1 {
|
if contract.schema != 1 {
|
||||||
@@ -367,12 +405,24 @@ pub fn check(db: &Db, root: &Path) -> Result<Vec<Problem>> {
|
|||||||
}
|
}
|
||||||
// Check owned characters too, including legacy classes and Wildcard characters. Their rows
|
// Check owned characters too, including legacy classes and Wildcard characters. Their rows
|
||||||
// must not silently disappear from character selection after an otherwise healthy update.
|
// must not silently disappear from character selection after an otherwise healthy update.
|
||||||
let missing = db.query("SELECT c.race,c.class,COUNT(*) FROM acore_characters.characters c LEFT JOIN acore_world.playercreateinfo p ON p.race=c.race AND p.class=c.class WHERE p.race IS NULL GROUP BY c.race,c.class;")?;
|
let current = crate::character_start_check::missing(db)?;
|
||||||
for row in missing.lines() {
|
let blocking = if let Some(before) = before {
|
||||||
let fields: Vec<_> = row.split('\t').collect();
|
let introduced = crate::character_start_check::introduced(¤t, before);
|
||||||
if fields.len() == 3 {
|
for character in current.intersection(before) {
|
||||||
problems.push(Problem { database: "world".into(), table: "playercreateinfo".into(), column: String::new(), detail: format!("{} existing characters have no starting data for race {} / class {} and would be hidden from character selection", fields[2], fields[0], fields[1]) });
|
*existing
|
||||||
|
.entry((character.race, character.class))
|
||||||
|
.or_default() += 1;
|
||||||
}
|
}
|
||||||
|
introduced
|
||||||
|
} else {
|
||||||
|
current
|
||||||
|
};
|
||||||
|
let mut counts = BTreeMap::<(u32, u32), usize>::new();
|
||||||
|
for character in blocking {
|
||||||
|
*counts.entry((character.race, character.class)).or_default() += 1;
|
||||||
|
}
|
||||||
|
for ((race, class), count) in counts {
|
||||||
|
problems.push(Problem { database: "world".into(), table: "playercreateinfo".into(), column: String::new(), detail: format!("{count} existing characters have no starting data for race {race} / class {class} and would be hidden from character selection") });
|
||||||
}
|
}
|
||||||
Ok(problems)
|
Ok(problems)
|
||||||
}
|
}
|
||||||
|
|||||||
+248
-17
@@ -22,6 +22,8 @@ use crate::pkgsource::{fetch_manifest, fetch_parts, Source};
|
|||||||
use crate::registry::{InstallMeta, MetaDir};
|
use crate::registry::{InstallMeta, MetaDir};
|
||||||
|
|
||||||
const STAGED_PREFIX: &str = "_migrations/";
|
const STAGED_PREFIX: &str = "_migrations/";
|
||||||
|
const CHARACTER_BASELINE: &str = "character-start-baseline.json";
|
||||||
|
const CHARACTER_BASELINE_HASH: &str = "@character-starts";
|
||||||
|
|
||||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
|
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
|
||||||
#[serde(rename_all = "kebab-case")]
|
#[serde(rename_all = "kebab-case")]
|
||||||
@@ -106,6 +108,9 @@ pub trait Env {
|
|||||||
fn verify_snapshot(&self, _id: &str) -> Result<()> {
|
fn verify_snapshot(&self, _id: &str) -> Result<()> {
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
fn character_start_baseline(&self) -> Result<Option<crate::character_start_check::Baseline>> {
|
||||||
|
Ok(None)
|
||||||
|
}
|
||||||
fn snapshot(&self) -> Result<String>;
|
fn snapshot(&self) -> Result<String>;
|
||||||
fn restore_snapshot(&self, id: &str) -> Result<()>;
|
fn restore_snapshot(&self, id: &str) -> Result<()>;
|
||||||
fn migrate(&self, manifest: &Manifest, staged_migrations: &Path) -> Result<ApplyReport>;
|
fn migrate(&self, manifest: &Manifest, staged_migrations: &Path) -> Result<ApplyReport>;
|
||||||
@@ -223,11 +228,12 @@ fn read_journal(path: &Path) -> Result<Txn> {
|
|||||||
"Update journal contains invalid recovery hashes.".into(),
|
"Update journal contains invalid recovery hashes.".into(),
|
||||||
));
|
));
|
||||||
}
|
}
|
||||||
for key in txn
|
for key in txn.recovery_hashes.keys().filter(|key| {
|
||||||
.recovery_hashes
|
!matches!(
|
||||||
.keys()
|
key.as_str(),
|
||||||
.filter(|key| !matches!(key.as_str(), "@install" | "@point"))
|
"@install" | "@point" | CHARACTER_BASELINE_HASH
|
||||||
{
|
)
|
||||||
|
}) {
|
||||||
fsx::safe_join(path.parent().unwrap(), key)?;
|
fsx::safe_join(path.parent().unwrap(), key)?;
|
||||||
}
|
}
|
||||||
if completed_legacy_repair {
|
if completed_legacy_repair {
|
||||||
@@ -684,6 +690,7 @@ pub struct Params<'a> {
|
|||||||
#[derive(Debug, Serialize)]
|
#[derive(Debug, Serialize)]
|
||||||
pub struct Outcome {
|
pub struct Outcome {
|
||||||
pub txn: Txn,
|
pub txn: Txn,
|
||||||
|
pub preexisting_character_count: usize,
|
||||||
pub migrations: Option<ApplyReport>,
|
pub migrations: Option<ApplyReport>,
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -816,6 +823,26 @@ pub fn apply(p: &Params, report: &dyn Fn(&str, u8)) -> Result<Outcome> {
|
|||||||
.insert("@point".into(), fsx::sha256_file(&point_meta)?);
|
.insert("@point".into(), fsx::sha256_file(&point_meta)?);
|
||||||
}
|
}
|
||||||
save(meta_dir, &txn)?;
|
save(meta_dir, &txn)?;
|
||||||
|
// Capture before any new files or SQL are applied; retry must reuse these exact bytes.
|
||||||
|
let baseline = match p.env.character_start_baseline() {
|
||||||
|
Ok(baseline) => baseline,
|
||||||
|
Err(error) => {
|
||||||
|
txn.state = State::Failed;
|
||||||
|
txn.message = Some(format!("The update was not applied because the character baseline could not be captured: {error}"));
|
||||||
|
save(meta_dir, &txn)?;
|
||||||
|
return Err(error);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
let preexisting_character_count = baseline
|
||||||
|
.as_ref()
|
||||||
|
.map_or(0, |b| b.realms.values().map(|r| r.len()).sum());
|
||||||
|
if let Some(baseline) = &baseline {
|
||||||
|
let path = tdir.join(CHARACTER_BASELINE);
|
||||||
|
fsx::atomic_write_json(&path, baseline)?;
|
||||||
|
txn.recovery_hashes
|
||||||
|
.insert(CHARACTER_BASELINE_HASH.into(), fsx::sha256_file(&path)?);
|
||||||
|
save(meta_dir, &txn)?;
|
||||||
|
}
|
||||||
txn.ops = items
|
txn.ops = items
|
||||||
.iter()
|
.iter()
|
||||||
.filter(|i| i.action != Action::Skip)
|
.filter(|i| i.action != Action::Skip)
|
||||||
@@ -909,6 +936,7 @@ pub fn apply(p: &Params, report: &dyn Fn(&str, u8)) -> Result<Outcome> {
|
|||||||
save(meta_dir, &txn)?;
|
save(meta_dir, &txn)?;
|
||||||
return Ok(Outcome {
|
return Ok(Outcome {
|
||||||
txn,
|
txn,
|
||||||
|
preexisting_character_count,
|
||||||
migrations: migrated,
|
migrations: migrated,
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
@@ -919,6 +947,7 @@ pub fn apply(p: &Params, report: &dyn Fn(&str, u8)) -> Result<Outcome> {
|
|||||||
let _ = archive;
|
let _ = archive;
|
||||||
Ok(Outcome {
|
Ok(Outcome {
|
||||||
txn,
|
txn,
|
||||||
|
preexisting_character_count,
|
||||||
migrations: migrated,
|
migrations: migrated,
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
@@ -1039,6 +1068,7 @@ pub fn retry_validation(
|
|||||||
)));
|
)));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
read_character_baseline(meta_dir, &txn)?;
|
||||||
env.ensure_stopped()?;
|
env.ensure_stopped()?;
|
||||||
if let Err(error) = env.validate() {
|
if let Err(error) = env.validate() {
|
||||||
txn.message = Some(format!(
|
txn.message = Some(format!(
|
||||||
@@ -1115,7 +1145,13 @@ fn restore_transaction(
|
|||||||
txn: &mut Txn,
|
txn: &mut Txn,
|
||||||
env: &dyn Env,
|
env: &dyn Env,
|
||||||
) -> Result<()> {
|
) -> Result<()> {
|
||||||
for (rel, expected) in &txn.recovery_hashes {
|
// This baseline is a validation input, not a recovery copy: corruption must block
|
||||||
|
// retry/commit, but must never prevent restoration of the verified safety backup.
|
||||||
|
for (rel, expected) in txn
|
||||||
|
.recovery_hashes
|
||||||
|
.iter()
|
||||||
|
.filter(|(key, _)| key.as_str() != CHARACTER_BASELINE_HASH)
|
||||||
|
{
|
||||||
let saved = match rel.as_str() {
|
let saved = match rel.as_str() {
|
||||||
"@install" => before.join("manager-install.json"),
|
"@install" => before.join("manager-install.json"),
|
||||||
"@point" => crate::backup::point_json(
|
"@point" => crate::backup::point_json(
|
||||||
@@ -1504,6 +1540,33 @@ fn prune(meta_dir: &Path, keep: usize) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fn read_character_baseline(
|
||||||
|
meta: &Path,
|
||||||
|
txn: &Txn,
|
||||||
|
) -> Result<Option<crate::character_start_check::Baseline>> {
|
||||||
|
let path = txn_dir(meta, &txn.id)?.join(CHARACTER_BASELINE);
|
||||||
|
let Some(expected) = txn.recovery_hashes.get(CHARACTER_BASELINE_HASH) else {
|
||||||
|
if path.exists() {
|
||||||
|
return Err(Error::Invalid(
|
||||||
|
"An unverified character start baseline was found.".into(),
|
||||||
|
));
|
||||||
|
}
|
||||||
|
return Ok(None); // Older transactions remain strict; never learn a baseline after applying SQL.
|
||||||
|
};
|
||||||
|
if fsx::sha256_file(&path)? != *expected {
|
||||||
|
return Err(Error::Invalid(
|
||||||
|
"The saved character start baseline failed verification.".into(),
|
||||||
|
));
|
||||||
|
}
|
||||||
|
let baseline: crate::character_start_check::Baseline = fsx::read_json(&path)?;
|
||||||
|
if baseline.schema != 1 {
|
||||||
|
return Err(Error::Invalid(
|
||||||
|
"Unsupported character start baseline.".into(),
|
||||||
|
));
|
||||||
|
}
|
||||||
|
Ok(Some(baseline))
|
||||||
|
}
|
||||||
|
|
||||||
/// The real environment: a repack-shaped installation driven through its launcher.
|
/// The real environment: a repack-shaped installation driven through its launcher.
|
||||||
pub struct RepackEnv<'a> {
|
pub struct RepackEnv<'a> {
|
||||||
pub root: &'a Path,
|
pub root: &'a Path,
|
||||||
@@ -1511,6 +1574,12 @@ pub struct RepackEnv<'a> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
impl RepackEnv<'_> {
|
impl RepackEnv<'_> {
|
||||||
|
fn saved_character_baseline(&self) -> Result<Option<crate::character_start_check::Baseline>> {
|
||||||
|
match unfinished(self.meta_dir) {
|
||||||
|
Some(txn) => read_character_baseline(self.meta_dir, &txn),
|
||||||
|
None => Ok(None),
|
||||||
|
}
|
||||||
|
}
|
||||||
pub fn pending_migrations(&self, manifest: &Manifest) -> Result<usize> {
|
pub fn pending_migrations(&self, manifest: &Manifest) -> Result<usize> {
|
||||||
Ok(self
|
Ok(self
|
||||||
.pending_migrations_with(manifest, DatabaseAccess::Start)?
|
.pending_migrations_with(manifest, DatabaseAccess::Start)?
|
||||||
@@ -1527,9 +1596,9 @@ impl RepackEnv<'_> {
|
|||||||
return Ok(Some(0));
|
return Ok(Some(0));
|
||||||
}
|
}
|
||||||
let count = |db: &crate::db::Db| -> Result<usize> {
|
let count = |db: &crate::db::Db| -> Result<usize> {
|
||||||
let db = db.clone().with_read_deadline(
|
let db = db
|
||||||
std::time::Instant::now() + std::time::Duration::from_secs(15),
|
.clone()
|
||||||
);
|
.with_read_deadline(std::time::Instant::now() + std::time::Duration::from_secs(15));
|
||||||
let realms = crate::realms::state(self.root)?;
|
let realms = crate::realms::state(self.root)?;
|
||||||
let modes = realms.modes();
|
let modes = realms.modes();
|
||||||
let mut count = 0;
|
let mut count = 0;
|
||||||
@@ -1772,12 +1841,25 @@ impl Env for RepackEnv<'_> {
|
|||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fn character_start_baseline(&self) -> Result<Option<crate::character_start_check::Baseline>> {
|
||||||
|
crate::backup::with_database(self.root, |db| {
|
||||||
|
crate::character_start_check::capture(db, self.root)
|
||||||
|
})
|
||||||
|
.map(Some)
|
||||||
|
}
|
||||||
|
|
||||||
fn migrate(&self, manifest: &Manifest, staged: &Path) -> Result<ApplyReport> {
|
fn migrate(&self, manifest: &Manifest, staged: &Path) -> Result<ApplyReport> {
|
||||||
crate::backup::with_database(self.root, |db| {
|
crate::backup::with_database(self.root, |db| {
|
||||||
let identities = database_identities(db)?;
|
let identities = database_identities(db)?;
|
||||||
let result = migrate_databases(db, self.root, manifest, staged, &|| {
|
let baseline = self.saved_character_baseline()?;
|
||||||
self.migration_snapshot()
|
let result = migrate_databases(
|
||||||
})?;
|
db,
|
||||||
|
self.root,
|
||||||
|
manifest,
|
||||||
|
staged,
|
||||||
|
&|| self.migration_snapshot(),
|
||||||
|
baseline.as_ref(),
|
||||||
|
)?;
|
||||||
if result.failed.is_none() {
|
if result.failed.is_none() {
|
||||||
verify_database_identities(db, &identities)?;
|
verify_database_identities(db, &identities)?;
|
||||||
}
|
}
|
||||||
@@ -1799,6 +1881,11 @@ impl RepackEnv<'_> {
|
|||||||
crate::mysql_snapshot::stop(self.root)?;
|
crate::mysql_snapshot::stop(self.root)?;
|
||||||
self.ensure_stopped()?;
|
self.ensure_stopped()?;
|
||||||
self.recover_validation()?;
|
self.recover_validation()?;
|
||||||
|
let baseline = if check_schema {
|
||||||
|
self.saved_character_baseline()?
|
||||||
|
} else {
|
||||||
|
None
|
||||||
|
};
|
||||||
let result = (|| -> Result<()> {
|
let result = (|| -> Result<()> {
|
||||||
crate::update_isolation::begin(self.root, self.meta_dir)?;
|
crate::update_isolation::begin(self.root, self.meta_dir)?;
|
||||||
use crate::process::{observe, ServiceState};
|
use crate::process::{observe, ServiceState};
|
||||||
@@ -1806,9 +1893,10 @@ impl RepackEnv<'_> {
|
|||||||
if check_schema {
|
if check_schema {
|
||||||
let modes = crate::realms::state(self.root)?.modes();
|
let modes = crate::realms::state(self.root)?.modes();
|
||||||
for mode in modes {
|
for mode in modes {
|
||||||
if let Some(p) = crate::schema_check::check_with_report(
|
if let Some(p) = crate::schema_check::check_update_with_report(
|
||||||
&db.clone().for_realm(mode),
|
&db.clone().for_realm(mode),
|
||||||
self.root,
|
self.root,
|
||||||
|
baseline.as_ref(),
|
||||||
)?
|
)?
|
||||||
.first()
|
.first()
|
||||||
{
|
{
|
||||||
@@ -1851,8 +1939,7 @@ impl RepackEnv<'_> {
|
|||||||
if o.mysql.state == ServiceState::Running
|
if o.mysql.state == ServiceState::Running
|
||||||
&& o.auth.state == ServiceState::Running
|
&& o.auth.state == ServiceState::Running
|
||||||
&& o.world.state == ServiceState::Running
|
&& o.world.state == ServiceState::Running
|
||||||
&& o.extra_worlds()
|
&& o.extra_worlds().all(|s| s.state == ServiceState::Running)
|
||||||
.all(|s| s.state == ServiceState::Running)
|
|
||||||
{
|
{
|
||||||
let since = ready_since.get_or_insert_with(std::time::Instant::now);
|
let since = ready_since.get_or_insert_with(std::time::Instant::now);
|
||||||
if since.elapsed() >= std::time::Duration::from_secs(10) {
|
if since.elapsed() >= std::time::Duration::from_secs(10) {
|
||||||
@@ -1869,7 +1956,26 @@ impl RepackEnv<'_> {
|
|||||||
};
|
};
|
||||||
if healthy {
|
if healthy {
|
||||||
crate::backup::with_database(self.root, |db| {
|
crate::backup::with_database(self.root, |db| {
|
||||||
verify_database_identities(db, &identities)
|
verify_database_identities(db, &identities)?;
|
||||||
|
if check_schema {
|
||||||
|
for mode in crate::realms::state(self.root)?.modes() {
|
||||||
|
if let Some(problem) = crate::schema_check::check_update_with_report(
|
||||||
|
&db.clone().for_realm(mode),
|
||||||
|
self.root,
|
||||||
|
baseline.as_ref(),
|
||||||
|
)?
|
||||||
|
.first()
|
||||||
|
{
|
||||||
|
return Err(Error::Invalid(format!(
|
||||||
|
"Database validation failed after startup on {}: {}: {}",
|
||||||
|
mode.name(),
|
||||||
|
problem.table,
|
||||||
|
problem.detail
|
||||||
|
)));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
})?;
|
})?;
|
||||||
return Ok(());
|
return Ok(());
|
||||||
}
|
}
|
||||||
@@ -1892,6 +1998,7 @@ fn migrate_databases(
|
|||||||
manifest: &Manifest,
|
manifest: &Manifest,
|
||||||
staged: &Path,
|
staged: &Path,
|
||||||
snapshot: &dyn Fn() -> Result<String>,
|
snapshot: &dyn Fn() -> Result<String>,
|
||||||
|
baseline: Option<&crate::character_start_check::Baseline>,
|
||||||
) -> Result<ApplyReport> {
|
) -> Result<ApplyReport> {
|
||||||
let realms = crate::realms::state(root)?;
|
let realms = crate::realms::state(root)?;
|
||||||
let modes = realms.modes();
|
let modes = realms.modes();
|
||||||
@@ -1943,7 +2050,8 @@ fn migrate_databases(
|
|||||||
return Ok(result);
|
return Ok(result);
|
||||||
}
|
}
|
||||||
crate::schema_check::repair_missing_defaults(&db, root, contract)?;
|
crate::schema_check::repair_missing_defaults(&db, root, contract)?;
|
||||||
if let Some(p) = crate::schema_check::check_with_report(&db, root)?.first() {
|
if let Some(p) = crate::schema_check::check_update_with_report(&db, root, baseline)?.first()
|
||||||
|
{
|
||||||
return Err(Error::Invalid(format!(
|
return Err(Error::Invalid(format!(
|
||||||
"Database validation failed on {}: {}.{}: {}",
|
"Database validation failed on {}: {}.{}: {}",
|
||||||
mode.name(),
|
mode.name(),
|
||||||
@@ -2010,6 +2118,8 @@ mod tests {
|
|||||||
use std::cell::{Cell, RefCell};
|
use std::cell::{Cell, RefCell};
|
||||||
|
|
||||||
struct Fake {
|
struct Fake {
|
||||||
|
character_baseline: RefCell<Option<crate::character_start_check::Baseline>>,
|
||||||
|
baseline_failed: Cell<bool>,
|
||||||
activation_expected: RefCell<Option<(PathBuf, String)>>,
|
activation_expected: RefCell<Option<(PathBuf, String)>>,
|
||||||
activation_failed: Cell<bool>,
|
activation_failed: Cell<bool>,
|
||||||
activated: Cell<bool>,
|
activated: Cell<bool>,
|
||||||
@@ -2027,6 +2137,8 @@ mod tests {
|
|||||||
impl Fake {
|
impl Fake {
|
||||||
fn ok() -> Fake {
|
fn ok() -> Fake {
|
||||||
Fake {
|
Fake {
|
||||||
|
character_baseline: RefCell::new(None),
|
||||||
|
baseline_failed: Cell::new(false),
|
||||||
activation_expected: RefCell::new(None),
|
activation_expected: RefCell::new(None),
|
||||||
activation_failed: Cell::new(false),
|
activation_failed: Cell::new(false),
|
||||||
activated: Cell::new(false),
|
activated: Cell::new(false),
|
||||||
@@ -2044,6 +2156,14 @@ mod tests {
|
|||||||
}
|
}
|
||||||
|
|
||||||
impl Env for Fake {
|
impl Env for Fake {
|
||||||
|
fn character_start_baseline(
|
||||||
|
&self,
|
||||||
|
) -> Result<Option<crate::character_start_check::Baseline>> {
|
||||||
|
if self.baseline_failed.get() {
|
||||||
|
return Err(Error::Invalid("fixture baseline unavailable".into()));
|
||||||
|
}
|
||||||
|
Ok(self.character_baseline.borrow().clone())
|
||||||
|
}
|
||||||
fn activate(&self) -> Result<()> {
|
fn activate(&self) -> Result<()> {
|
||||||
if let Some((meta, version)) = self.activation_expected.borrow().as_ref() {
|
if let Some((meta, version)) = self.activation_expected.borrow().as_ref() {
|
||||||
ensure_recovered(meta)?;
|
ensure_recovered(meta)?;
|
||||||
@@ -3485,4 +3605,115 @@ mod tests {
|
|||||||
.iter()
|
.iter()
|
||||||
.any(|i| i.path == "Core/newfile.dll" && i.action == Action::Create));
|
.any(|i| i.path == "Core/newfile.dll" && i.action == Action::Create));
|
||||||
}
|
}
|
||||||
|
fn baseline_fixture() -> crate::character_start_check::Baseline {
|
||||||
|
crate::character_start_check::Baseline {
|
||||||
|
schema: 1,
|
||||||
|
realms: BTreeMap::from([(
|
||||||
|
"coa".into(),
|
||||||
|
crate::character_start_check::parse_missing("1\t44\t14\n2\t44\t14\n3\t44\t14")
|
||||||
|
.unwrap(),
|
||||||
|
)]),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn character_baseline_is_captured_once_persisted_and_verified_for_retry() {
|
||||||
|
let w = world(&[], true);
|
||||||
|
let env = Fake::ok();
|
||||||
|
*env.character_baseline.borrow_mut() = Some(baseline_fixture());
|
||||||
|
env.healthy.set(false);
|
||||||
|
let out = run(&w, &env, BTreeMap::new(), None).unwrap();
|
||||||
|
assert_eq!(out.txn.state, State::NeedsDecision);
|
||||||
|
assert_eq!(out.preexisting_character_count, 3);
|
||||||
|
let baseline_path = txn_dir(&w.meta, &out.txn.id)
|
||||||
|
.unwrap()
|
||||||
|
.join(CHARACTER_BASELINE);
|
||||||
|
let original = fs::read(&baseline_path).unwrap();
|
||||||
|
assert_eq!(
|
||||||
|
read_character_baseline(&w.meta, &out.txn)
|
||||||
|
.unwrap()
|
||||||
|
.unwrap()
|
||||||
|
.realms["coa"]
|
||||||
|
.len(),
|
||||||
|
3
|
||||||
|
);
|
||||||
|
// A retry may not learn new gaps from an already modified database.
|
||||||
|
*env.character_baseline.borrow_mut() = None;
|
||||||
|
env.healthy.set(true);
|
||||||
|
fs::write(&baseline_path, b"{}").unwrap();
|
||||||
|
assert!(retry_validation(
|
||||||
|
&w.root,
|
||||||
|
&w.meta,
|
||||||
|
&out.txn.id,
|
||||||
|
&Source::Dir(w.pkg.clone()),
|
||||||
|
&w.key,
|
||||||
|
&env
|
||||||
|
)
|
||||||
|
.is_err());
|
||||||
|
fs::write(&baseline_path, original).unwrap();
|
||||||
|
let done = retry_validation(
|
||||||
|
&w.root,
|
||||||
|
&w.meta,
|
||||||
|
&out.txn.id,
|
||||||
|
&Source::Dir(w.pkg.clone()),
|
||||||
|
&w.key,
|
||||||
|
&env,
|
||||||
|
)
|
||||||
|
.unwrap();
|
||||||
|
assert_eq!(done.state, State::Committed);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn corrupt_character_baseline_does_not_prevent_safe_rollback() {
|
||||||
|
let w = world(&[], true);
|
||||||
|
let env = Fake::ok();
|
||||||
|
*env.character_baseline.borrow_mut() = Some(baseline_fixture());
|
||||||
|
env.healthy.set(false);
|
||||||
|
let out = run(&w, &env, BTreeMap::new(), None).unwrap();
|
||||||
|
fs::write(
|
||||||
|
txn_dir(&w.meta, &out.txn.id)
|
||||||
|
.unwrap()
|
||||||
|
.join(CHARACTER_BASELINE),
|
||||||
|
b"bad",
|
||||||
|
)
|
||||||
|
.unwrap();
|
||||||
|
let restored = rollback(&w.root, &w.meta, &out.txn.id, &env).unwrap();
|
||||||
|
assert_eq!(restored.state, State::RolledBack);
|
||||||
|
assert_eq!(read(&w, "Core/worldserver.exe"), b"world-v1");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn missing_or_unverified_character_baselines_fail_closed() {
|
||||||
|
let w = world(&[], true);
|
||||||
|
let env = Fake::ok();
|
||||||
|
env.healthy.set(false);
|
||||||
|
let out = run(&w, &env, BTreeMap::new(), None).unwrap();
|
||||||
|
assert!(read_character_baseline(&w.meta, &out.txn)
|
||||||
|
.unwrap()
|
||||||
|
.is_none());
|
||||||
|
let path = txn_dir(&w.meta, &out.txn.id)
|
||||||
|
.unwrap()
|
||||||
|
.join(CHARACTER_BASELINE);
|
||||||
|
fsx::atomic_write_json(&path, &baseline_fixture()).unwrap();
|
||||||
|
assert!(read_character_baseline(&w.meta, &out.txn).is_err());
|
||||||
|
let mut txn = out.txn;
|
||||||
|
txn.recovery_hashes.insert(
|
||||||
|
CHARACTER_BASELINE_HASH.into(),
|
||||||
|
fsx::sha256_file(&path).unwrap(),
|
||||||
|
);
|
||||||
|
fs::remove_file(path).unwrap();
|
||||||
|
assert!(read_character_baseline(&w.meta, &txn).is_err());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn baseline_capture_failure_precedes_file_and_database_changes() {
|
||||||
|
let w = world(&[], true);
|
||||||
|
let env = Fake::ok();
|
||||||
|
env.baseline_failed.set(true);
|
||||||
|
assert!(run(&w, &env, BTreeMap::new(), None).is_err());
|
||||||
|
assert_eq!(read(&w, "Core/worldserver.exe"), b"world-v1");
|
||||||
|
assert!(!env.calls.borrow().contains(&"migrate"));
|
||||||
|
assert!(!env.calls.borrow().contains(&"validate"));
|
||||||
|
assert!(unfinished(&w.meta).is_none());
|
||||||
|
}
|
||||||
}
|
}
|
||||||
Generated
+2
-2
@@ -1,12 +1,12 @@
|
|||||||
{
|
{
|
||||||
"name": "coa-server-manager",
|
"name": "coa-server-manager",
|
||||||
"version": "0.9.0",
|
"version": "0.9.2",
|
||||||
"lockfileVersion": 3,
|
"lockfileVersion": 3,
|
||||||
"requires": true,
|
"requires": true,
|
||||||
"packages": {
|
"packages": {
|
||||||
"": {
|
"": {
|
||||||
"name": "coa-server-manager",
|
"name": "coa-server-manager",
|
||||||
"version": "0.9.0",
|
"version": "0.9.2",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@tauri-apps/api": "^2.12.0",
|
"@tauri-apps/api": "^2.12.0",
|
||||||
"@tauri-apps/plugin-dialog": "^2.8.0",
|
"@tauri-apps/plugin-dialog": "^2.8.0",
|
||||||
|
|||||||
+1
-1
@@ -1,7 +1,7 @@
|
|||||||
{
|
{
|
||||||
"name": "coa-server-manager",
|
"name": "coa-server-manager",
|
||||||
"private": true,
|
"private": true,
|
||||||
"version": "0.9.0",
|
"version": "0.9.2",
|
||||||
"license": "AGPL-3.0-only",
|
"license": "AGPL-3.0-only",
|
||||||
"type": "module",
|
"type": "module",
|
||||||
"scripts": {
|
"scripts": {
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
{
|
{
|
||||||
"$schema": "https://schema.tauri.app/config/2",
|
"$schema": "https://schema.tauri.app/config/2",
|
||||||
"productName": "CoA Server Manager",
|
"productName": "CoA Server Manager",
|
||||||
"version": "0.9.0",
|
"version": "0.9.2",
|
||||||
"identifier": "com.coa.servermanager",
|
"identifier": "com.coa.servermanager",
|
||||||
"build": {
|
"build": {
|
||||||
"beforeDevCommand": "npm run dev",
|
"beforeDevCommand": "npm run dev",
|
||||||
|
|||||||
@@ -0,0 +1,40 @@
|
|||||||
|
{
|
||||||
|
"manager": {
|
||||||
|
"ru": {
|
||||||
|
"Existing unsupported character records no longer block unrelated server updates": "Старые неподдерживаемые записи персонажей больше не блокируют несвязанные обновления сервера",
|
||||||
|
"New server installation waits for slower database startup": "Установка нового сервера дольше ожидает запуска базы на медленных дисках",
|
||||||
|
"Find and edit CoA options in the existing server settings": "Параметры CoA доступны для поиска и редактирования в настройках сервера",
|
||||||
|
"Simultaneous update checks share results or wait their turn": "Одновременные проверки обновлений используют общий результат или ожидают своей очереди",
|
||||||
|
"Recovery can stop an unfinished world startup after restoring an older launcher": "Восстановление может остановить зависший запуск мира после возврата старого launcher"
|
||||||
|
},
|
||||||
|
"de": {
|
||||||
|
"Existing unsupported character records no longer block unrelated server updates": "Bestehende nicht unterstützte Charakterdatensätze blockieren keine unabhängigen Serverupdates mehr",
|
||||||
|
"New server installation waits for slower database startup": "Die Neuinstallation wartet länger auf einen langsamen Datenbankstart",
|
||||||
|
"Find and edit CoA options in the existing server settings": "CoA-Optionen in den bestehenden Servereinstellungen suchen und bearbeiten",
|
||||||
|
"Simultaneous update checks share results or wait their turn": "Gleichzeitige Updateprüfungen teilen Ergebnisse oder warten aufeinander",
|
||||||
|
"Recovery can stop an unfinished world startup after restoring an older launcher": "Die Wiederherstellung stoppt einen unvollständigen Weltstart auch mit altem Launcher"
|
||||||
|
},
|
||||||
|
"fr": {
|
||||||
|
"Existing unsupported character records no longer block unrelated server updates": "Les anciennes fiches de personnage non prises en charge ne bloquent plus les mises à jour sans rapport",
|
||||||
|
"New server installation waits for slower database startup": "L’installation attend le démarrage de la base sur les disques plus lents",
|
||||||
|
"Find and edit CoA options in the existing server settings": "Recherchez et modifiez les options CoA dans les paramètres du serveur",
|
||||||
|
"Simultaneous update checks share results or wait their turn": "Les vérifications simultanées partagent leurs résultats ou attendent leur tour",
|
||||||
|
"Recovery can stop an unfinished world startup after restoring an older launcher": "La restauration peut arrêter un démarrage du monde inachevé avec un ancien lanceur"
|
||||||
|
},
|
||||||
|
"es": {
|
||||||
|
"Existing unsupported character records no longer block unrelated server updates": "Los registros antiguos de personajes no compatibles ya no bloquean actualizaciones del servidor no relacionadas",
|
||||||
|
"New server installation waits for slower database startup": "La instalación espera más tiempo al inicio de la base de datos en discos lentos",
|
||||||
|
"Find and edit CoA options in the existing server settings": "Busca y edita opciones de CoA en la configuración actual del servidor",
|
||||||
|
"Simultaneous update checks share results or wait their turn": "Las comprobaciones simultáneas comparten resultados o esperan su turno",
|
||||||
|
"Recovery can stop an unfinished world startup after restoring an older launcher": "La recuperación puede detener el inicio del mundo tras restaurar un lanzador antiguo"
|
||||||
|
},
|
||||||
|
"zh": {
|
||||||
|
"Existing unsupported character records no longer block unrelated server updates": "已有的不受支持角色记录不再阻止无关的服务器更新",
|
||||||
|
"New server installation waits for slower database startup": "安装新服务器时会等待较慢的数据库启动",
|
||||||
|
"Find and edit CoA options in the existing server settings": "在现有服务器设置中查找和编辑 CoA 选项",
|
||||||
|
"Simultaneous update checks share results or wait their turn": "同时进行的更新检查会共用结果或依次执行",
|
||||||
|
"Recovery can stop an unfinished world startup after restoring an older launcher": "恢复旧版启动器后,恢复流程也能停止未完成启动的世界服务器"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"server": {}
|
||||||
|
}
|
||||||
@@ -2,6 +2,8 @@ import type en from "./en";
|
|||||||
|
|
||||||
/** Deutsch. Entwurf einer Übersetzung; vor der Veröffentlichung von Muttersprachlern zu prüfen. */
|
/** Deutsch. Entwurf einer Übersetzung; vor der Veröffentlichung von Muttersprachlern zu prüfen. */
|
||||||
const de: Partial<Record<keyof typeof en, string>> = {
|
const de: Partial<Record<keyof typeof en, string>> = {
|
||||||
|
"upd.preexistingCharacters": "Bereits vor dem Update fehlten bei {n} Charakterdatensätzen die Startdaten für Volk/Klasse. Unveränderte Datensätze wurden bewahrt und blockierten das Update nicht. Details stehen in der Diagnose; diese älteren Unstimmigkeiten wurden nicht automatisch behoben.",
|
||||||
|
|
||||||
"races.unknownIds": "Nicht mehr im Katalog vorhandene Völker-IDs: {ids}. Beim Speichern werden diese alten Einschränkungen entfernt.",
|
"races.unknownIds": "Nicht mehr im Katalog vorhandene Völker-IDs: {ids}. Beim Speichern werden diese alten Einschränkungen entfernt.",
|
||||||
"races.reviewCatalog": "Der Völkerkatalog wurde geändert oder noch nicht geprüft. Prüfe die Liste und speichere sie erneut.",
|
"races.reviewCatalog": "Der Völkerkatalog wurde geändert oder noch nicht geprüft. Prüfe die Liste und speichere sie erneut.",
|
||||||
"races.available": "Verfügbare Völker",
|
"races.available": "Verfügbare Völker",
|
||||||
|
|||||||
@@ -1,5 +1,7 @@
|
|||||||
/** English is the source of truth: every key must exist here; other locales fall back to it. */
|
/** English is the source of truth: every key must exist here; other locales fall back to it. */
|
||||||
const en = {
|
const en = {
|
||||||
|
"upd.preexistingCharacters": "Before the update, {n} character records already lacked race/class starting data. Unchanged records were preserved and did not block the update. Details are saved in diagnostics; these older inconsistencies have not been automatically repaired.",
|
||||||
|
|
||||||
"races.unknownIds": "RaceIDs no longer in this catalog: {ids}. Saving the reviewed list removes these old restrictions.",
|
"races.unknownIds": "RaceIDs no longer in this catalog: {ids}. Saving the reviewed list removes these old restrictions.",
|
||||||
"races.reviewCatalog": "The race catalog changed or has not been verified. Review the list and save it before applying restrictions.",
|
"races.reviewCatalog": "The race catalog changed or has not been verified. Review the list and save it before applying restrictions.",
|
||||||
"races.available": "Available races",
|
"races.available": "Available races",
|
||||||
|
|||||||
@@ -2,6 +2,8 @@ import type en from "./en";
|
|||||||
|
|
||||||
/** Español. Traducción provisional; debe revisarla un hablante nativo antes de publicarse. */
|
/** Español. Traducción provisional; debe revisarla un hablante nativo antes de publicarse. */
|
||||||
const es: Partial<Record<keyof typeof en, string>> = {
|
const es: Partial<Record<keyof typeof en, string>> = {
|
||||||
|
"upd.preexistingCharacters": "Antes de actualizar, a {n} registros de personaje ya les faltaban datos iniciales de raza/clase. Los registros sin cambios se conservaron y no bloquearon la actualización. Los detalles están en el diagnóstico; estas inconsistencias anteriores no se repararon automáticamente.",
|
||||||
|
|
||||||
"races.unknownIds": "RaceID que ya no están en el catálogo: {ids}. Al guardar la lista revisada se eliminan estas restricciones antiguas.",
|
"races.unknownIds": "RaceID que ya no están en el catálogo: {ids}. Al guardar la lista revisada se eliminan estas restricciones antiguas.",
|
||||||
"races.reviewCatalog": "El catálogo de razas ha cambiado o aún no está verificado. Revisa la lista y guárdala.",
|
"races.reviewCatalog": "El catálogo de razas ha cambiado o aún no está verificado. Revisa la lista y guárdala.",
|
||||||
"races.available": "Razas disponibles",
|
"races.available": "Razas disponibles",
|
||||||
|
|||||||
@@ -2,6 +2,8 @@ import type en from "./en";
|
|||||||
|
|
||||||
/** Français. Traduction provisoire ; à faire relire par un locuteur natif avant la publication. */
|
/** Français. Traduction provisoire ; à faire relire par un locuteur natif avant la publication. */
|
||||||
const fr: Partial<Record<keyof typeof en, string>> = {
|
const fr: Partial<Record<keyof typeof en, string>> = {
|
||||||
|
"upd.preexistingCharacters": "Avant la mise à jour, {n} fiches de personnage n’avaient déjà pas de données de départ pour leur race/classe. Les fiches inchangées ont été conservées sans bloquer la mise à jour. Les détails sont dans le diagnostic ; ces incohérences anciennes n’ont pas été corrigées automatiquement.",
|
||||||
|
|
||||||
"races.unknownIds": "RaceID absents de ce catalogue : {ids}. Sauvegarder la liste vérifiée supprime ces anciennes restrictions.",
|
"races.unknownIds": "RaceID absents de ce catalogue : {ids}. Sauvegarder la liste vérifiée supprime ces anciennes restrictions.",
|
||||||
"races.reviewCatalog": "Le catalogue des races a changé ou n’a pas été vérifié. Vérifiez la liste et sauvegardez-la.",
|
"races.reviewCatalog": "Le catalogue des races a changé ou n’a pas été vérifié. Vérifiez la liste et sauvegardez-la.",
|
||||||
"races.available": "Races disponibles",
|
"races.available": "Races disponibles",
|
||||||
|
|||||||
@@ -2,6 +2,8 @@ import type en from "./en";
|
|||||||
|
|
||||||
/** Русский. Черновой перевод; требует проверки носителем перед релизом. */
|
/** Русский. Черновой перевод; требует проверки носителем перед релизом. */
|
||||||
const ru: Partial<Record<keyof typeof en, string>> = {
|
const ru: Partial<Record<keyof typeof en, string>> = {
|
||||||
|
"upd.preexistingCharacters": "До обновления у {n} записей персонажей уже отсутствовали стартовые данные расы/класса. Неизменившиеся записи сохранены и не заблокировали обновление. Подробности есть в диагностике; эти старые несоответствия автоматически не исправлялись.",
|
||||||
|
|
||||||
"races.unknownIds": "RaceID, которых больше нет в каталоге: {ids}. Сохранение проверенного списка удалит эти старые ограничения.",
|
"races.unknownIds": "RaceID, которых больше нет в каталоге: {ids}. Сохранение проверенного списка удалит эти старые ограничения.",
|
||||||
"races.reviewCatalog": "Каталог рас изменился или ещё не проверен. Проверьте список и сохраните его перед применением ограничений.",
|
"races.reviewCatalog": "Каталог рас изменился или ещё не проверен. Проверьте список и сохраните его перед применением ограничений.",
|
||||||
"races.available": "Доступные расы",
|
"races.available": "Доступные расы",
|
||||||
|
|||||||
@@ -1,5 +1,7 @@
|
|||||||
/** Simplified Chinese localization (zh-CN) */
|
/** Simplified Chinese localization (zh-CN) */
|
||||||
const zh = {
|
const zh = {
|
||||||
|
"upd.preexistingCharacters": "更新前已有 {n} 条角色记录缺少种族/职业初始数据。未变化的记录已保留,不会阻止更新。详情已保存到诊断报告;这些既有问题尚未自动修复。",
|
||||||
|
|
||||||
"races.unknownIds": "此目录中已不存在的种族 ID:{ids}。保存检查后的列表将移除这些旧限制。",
|
"races.unknownIds": "此目录中已不存在的种族 ID:{ids}。保存检查后的列表将移除这些旧限制。",
|
||||||
"races.reviewCatalog": "种族目录已更改或尚未验证。请检查列表并保存后再应用限制。",
|
"races.reviewCatalog": "种族目录已更改或尚未验证。请检查列表并保存后再应用限制。",
|
||||||
"races.available": "可用种族",
|
"races.available": "可用种族",
|
||||||
|
|||||||
+8
-2
@@ -1,4 +1,7 @@
|
|||||||
import { invoke } from "@tauri-apps/api/core";
|
import { invoke } from "@tauri-apps/api/core";
|
||||||
|
import { updateCheckQueue } from "./updateCheckQueue";
|
||||||
|
|
||||||
|
const queuedUpdateCheck = updateCheckQueue<UpdatePreview>();
|
||||||
|
|
||||||
export const REMOTE_CLIENT_ID = "@remote-client";
|
export const REMOTE_CLIENT_ID = "@remote-client";
|
||||||
export interface RemoteConnection { host: string; client_path: string | null }
|
export interface RemoteConnection { host: string; client_path: string | null }
|
||||||
@@ -539,10 +542,13 @@ export const api = {
|
|||||||
createAccount: (id: string, username: string, password: string, administrator: boolean) =>
|
createAccount: (id: string, username: string, password: string, administrator: boolean) =>
|
||||||
invoke<void>("create_account", { id, username, password, administrator }),
|
invoke<void>("create_account", { id, username, password, administrator }),
|
||||||
/** `background`: the repeating check, which must not start the database of a stopped server. */
|
/** `background`: the repeating check, which must not start the database of a stopped server. */
|
||||||
checkUpdate: (id: string, source?: string, background?: boolean) => invoke<UpdatePreview>("check_update", { id, source: source ?? null, background: background ?? false }),
|
checkUpdate: (id: string, source?: string, background?: boolean) => queuedUpdateCheck(
|
||||||
|
id, JSON.stringify([source ?? null, background ?? false]),
|
||||||
|
() => invoke<UpdatePreview>("check_update", { id, source: source ?? null, background: background ?? false }),
|
||||||
|
),
|
||||||
pendingUpdate: (id: string) => invoke<UpdateTxn | null>("pending_update", { id }),
|
pendingUpdate: (id: string) => invoke<UpdateTxn | null>("pending_update", { id }),
|
||||||
applyUpdate: (id: string, resolutions: Record<string, "keep" | "replace">, source?: string) =>
|
applyUpdate: (id: string, resolutions: Record<string, "keep" | "replace">, source?: string) =>
|
||||||
invoke<{ txn: UpdateTxn }>("apply_update", { id, source: source ?? null, resolutions }),
|
invoke<{ txn: UpdateTxn; preexisting_character_count?: number }>("apply_update", { id, source: source ?? null, resolutions }),
|
||||||
rollbackUpdate: (id: string, txn: string) => invoke<UpdateTxn>("rollback_update", { id, txn }),
|
rollbackUpdate: (id: string, txn: string) => invoke<UpdateTxn>("rollback_update", { id, txn }),
|
||||||
retryUpdateValidation: (id: string, txn: string) => invoke<UpdateTxn>("retry_update_validation", { id, txn }),
|
retryUpdateValidation: (id: string, txn: string) => invoke<UpdateTxn>("retry_update_validation", { id, txn }),
|
||||||
population: (id: string) => invoke<Population | null>("get_population", { id }),
|
population: (id: string) => invoke<Population | null>("get_population", { id }),
|
||||||
|
|||||||
@@ -21,7 +21,7 @@ export interface ServerUpdateState {
|
|||||||
stateError: UiError | null;
|
stateError: UiError | null;
|
||||||
stateRevision: number;
|
stateRevision: number;
|
||||||
/** How the last update ended; kept here so the Settings card can show it after the user left and came back. */
|
/** How the last update ended; kept here so the Settings card can show it after the user left and came back. */
|
||||||
result: { committed: string } | { pending: UpdateTxn } | null;
|
result: { committed: string; preexistingCharacters?: number } | { pending: UpdateTxn } | null;
|
||||||
}
|
}
|
||||||
|
|
||||||
const EMPTY: ServerUpdateState = { preview: null, available: false, checking: false, applying: false, step: null, percent: 0, error: null, uiError: null, stateError: null, stateRevision: 0, result: null };
|
const EMPTY: ServerUpdateState = { preview: null, available: false, checking: false, applying: false, step: null, percent: 0, error: null, uiError: null, stateError: null, stateRevision: 0, result: null };
|
||||||
@@ -98,7 +98,7 @@ export async function applyServerUpdate(id: string, opts?: { choices: Record<str
|
|||||||
}
|
}
|
||||||
try {
|
try {
|
||||||
const out = await api.applyUpdate(id, opts?.choices ?? {}, opts?.source);
|
const out = await api.applyUpdate(id, opts?.choices ?? {}, opts?.source);
|
||||||
set(id, { result: out.txn.state === "committed" ? { committed: out.txn.to_version ?? "" } : { pending: out.txn } });
|
set(id, { result: out.txn.state === "committed" ? { committed: out.txn.to_version ?? "", ...(out.preexisting_character_count ? { preexistingCharacters: out.preexisting_character_count } : {}) } : { pending: out.txn } });
|
||||||
if (out.txn.state === "committed" && !wasRunning && !startAfterUpdate("server", id)) await api.stop(id).catch(() => undefined);
|
if (out.txn.state === "committed" && !wasRunning && !startAfterUpdate("server", id)) await api.stop(id).catch(() => undefined);
|
||||||
return true;
|
return true;
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
|
|||||||
@@ -0,0 +1,19 @@
|
|||||||
|
export function updateCheckQueue<T>() {
|
||||||
|
const requests = new Map<string, Promise<T>>();
|
||||||
|
const servers = new Map<string, Promise<unknown>>();
|
||||||
|
return (server: string, request: string, run: () => Promise<T>): Promise<T> => {
|
||||||
|
const key = JSON.stringify([server, request]);
|
||||||
|
const existing = requests.get(key);
|
||||||
|
if (existing) return existing;
|
||||||
|
const previous = servers.get(server) ?? Promise.resolve();
|
||||||
|
const result = previous.catch(() => undefined).then(run);
|
||||||
|
requests.set(key, result);
|
||||||
|
servers.set(server, result);
|
||||||
|
const clear = () => {
|
||||||
|
if (requests.get(key) === result) requests.delete(key);
|
||||||
|
if (servers.get(server) === result) servers.delete(server);
|
||||||
|
};
|
||||||
|
void result.then(clear, clear);
|
||||||
|
return result;
|
||||||
|
};
|
||||||
|
}
|
||||||
@@ -554,6 +554,7 @@ export function Overview({ server, companions = true, onForget, onOpenUpdates, o
|
|||||||
<Button size="sm" variant="ghost" onClick={() => void startClientUpdate(server.id)}>{t("client.dl.retry")}</Button>
|
<Button size="sm" variant="ghost" onClick={() => void startClientUpdate(server.id)}>{t("client.dl.retry")}</Button>
|
||||||
</p>
|
</p>
|
||||||
)}
|
)}
|
||||||
|
{upd.result && "committed" in upd.result && !!upd.result.preexistingCharacters && <p className="mt-3 text-sm text-warn" role="status">{t("upd.preexistingCharacters", { n: upd.result.preexistingCharacters })}</p>}
|
||||||
{upd.available && upd.preview && (
|
{upd.available && upd.preview && (
|
||||||
<div className="mt-4 rounded-md border border-gold/40 bg-gold/5 p-3 text-sm">
|
<div className="mt-4 rounded-md border border-gold/40 bg-gold/5 p-3 text-sm">
|
||||||
<p>{t("overview.updateAvail", { to: upd.preview.to_version, from: upd.preview.from_version ?? "?" })}</p>
|
<p>{t("overview.updateAvail", { to: upd.preview.to_version, from: upd.preview.from_version ?? "?" })}</p>
|
||||||
|
|||||||
@@ -210,6 +210,7 @@ export function SettingsHome({ serverId, serverName = "", path, onForget }: { se
|
|||||||
)}
|
)}
|
||||||
|
|
||||||
{done && pendingChecked && !pendingStateError && <p className="mt-4 text-sm text-ok" role="status">{done}</p>}
|
{done && pendingChecked && !pendingStateError && <p className="mt-4 text-sm text-ok" role="status">{done}</p>}
|
||||||
|
{upd.result && "committed" in upd.result && !!upd.result.preexistingCharacters && <p className="mt-3 text-sm text-warn" role="status">{t("upd.preexistingCharacters", { n: upd.result.preexistingCharacters })}</p>}
|
||||||
{error && (
|
{error && (
|
||||||
<div className="mt-4" role="alert">
|
<div className="mt-4" role="alert">
|
||||||
<p className="selectable whitespace-pre-wrap break-words text-sm text-bad">
|
<p className="selectable whitespace-pre-wrap break-words text-sm text-bad">
|
||||||
|
|||||||
@@ -284,8 +284,8 @@ export function SettingsPage(props: {
|
|||||||
const q = query.trim().toLowerCase();
|
const q = query.trim().toLowerCase();
|
||||||
const searching = q !== "";
|
const searching = q !== "";
|
||||||
const hit = (...parts: string[]) => parts.some((x) => x.toLowerCase().includes(q));
|
const hit = (...parts: string[]) => parts.some((x) => x.toLowerCase().includes(q));
|
||||||
const curatedKeys = new Set(view.settings.map((s) => s.key));
|
|
||||||
const collections = collectionsOf(cols);
|
const collections = collectionsOf(cols);
|
||||||
|
const curatedKeys = new Set([...view.settings.map((s) => s.key), ...collections.map((c) => c.item.key)]);
|
||||||
const curatedHits = searching ? view.settings.filter((s) => hit(s.key, sx.title(s), sx.description(s))) : [];
|
const curatedHits = searching ? view.settings.filter((s) => hit(s.key, sx.title(s), sx.description(s))) : [];
|
||||||
const collectionHits = searching ? collections.filter((c) => hit(c.item.key, t(c.label), t(c.text))) : [];
|
const collectionHits = searching ? collections.filter((c) => hit(c.item.key, t(c.label), t(c.text))) : [];
|
||||||
const rawHits = (raw ?? []).filter(
|
const rawHits = (raw ?? []).filter(
|
||||||
|
|||||||
@@ -15,6 +15,10 @@ const stubs = {
|
|||||||
"@/lib/clientJob": `export const dismissClientJob=()=>{}; export const startClientUpdate=()=>{}; export const stopClientJob=()=>{}; export const syncClient=()=>{}; export const useClientJob=()=>({phase:'idle'});`,
|
"@/lib/clientJob": `export const dismissClientJob=()=>{}; export const startClientUpdate=()=>{}; export const stopClientJob=()=>{}; export const syncClient=()=>{}; export const useClientJob=()=>({phase:'idle'});`,
|
||||||
"@/lib/clientUpdate": `export const checkClient=()=>{}; export const useClientStatus=()=>({status:null});`,
|
"@/lib/clientUpdate": `export const checkClient=()=>{}; export const useClientStatus=()=>({status:null});`,
|
||||||
"@/lib/autoRestartPrefs": `export const useAutoRestart=()=>[false,()=>{}];`,
|
"@/lib/autoRestartPrefs": `export const useAutoRestart=()=>[false,()=>{}];`,
|
||||||
|
"@/screens/PublishCard": `export const ListingChip=()=>null;`,
|
||||||
|
"@/screens/PublishDialog": `export const PublishRealmDialog=()=>null;`,
|
||||||
|
"@/lib/registry": `export const useRegistryStatus=()=>({status:null});`,
|
||||||
|
"@/lib/publishRealms": `export const usePublishRealms=()=>[];`,
|
||||||
"@/components/ui/button": `import {createElement} from 'react'; export const Button=({children,disabled,onClick,className})=>createElement('button',{disabled,onClick,className},children);`,
|
"@/components/ui/button": `import {createElement} from 'react'; export const Button=({children,disabled,onClick,className})=>createElement('button',{disabled,onClick,className},children);`,
|
||||||
"@/components/ui/card": `import {createElement} from 'react'; export const Card=({children,...props})=>createElement('div',props,children);`,
|
"@/components/ui/card": `import {createElement} from 'react'; export const Card=({children,...props})=>createElement('div',props,children);`,
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -52,6 +52,19 @@ test("refresh after recovery returns the latest disk state, then its absence", a
|
|||||||
assert.equal(await refreshServerUpdateState("recovery-case"), null);
|
assert.equal(await refreshServerUpdateState("recovery-case"), null);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
test("successful update keeps the existing-character warning across disk refresh", async () => {
|
||||||
|
const original = globalThis.__hotfixApi.applyUpdate;
|
||||||
|
try {
|
||||||
|
applyFailure = false;
|
||||||
|
stateFailure = false;
|
||||||
|
pending = null;
|
||||||
|
globalThis.__hotfixApi.applyUpdate = async () => ({ txn: { state: "committed", to_version: "2" }, preexisting_character_count: 174 });
|
||||||
|
assert.equal(await applyServerUpdate("old-character-warnings", { choices: {} }), true);
|
||||||
|
await refreshServerUpdateState("old-character-warnings");
|
||||||
|
assert.deepEqual(useServerUpdate("old-character-warnings").result, { committed: "2", preexistingCharacters: 174 });
|
||||||
|
} finally { globalThis.__hotfixApi.applyUpdate = original; }
|
||||||
|
});
|
||||||
|
|
||||||
test("a stopped server is left stopped after a successful update by default", async () => {
|
test("a stopped server is left stopped after a successful update by default", async () => {
|
||||||
calls.length = 0;
|
calls.length = 0;
|
||||||
serverRunning = false;
|
serverRunning = false;
|
||||||
|
|||||||
@@ -0,0 +1,123 @@
|
|||||||
|
import pathlib
|
||||||
|
import runpy
|
||||||
|
import sys
|
||||||
|
import tempfile
|
||||||
|
import unittest
|
||||||
|
from unittest.mock import patch
|
||||||
|
|
||||||
|
BRIDGE = pathlib.Path(__file__).resolve().parents[1] / 'crates/coa-core/src/launcher_bridge.py'
|
||||||
|
|
||||||
|
|
||||||
|
class LauncherBridgeTests(unittest.TestCase):
|
||||||
|
def launch(self, action, body):
|
||||||
|
with tempfile.TemporaryDirectory() as directory:
|
||||||
|
script = pathlib.Path(directory) / 'Scripts/manage.py'
|
||||||
|
script.parent.mkdir()
|
||||||
|
script.write_text(body, encoding='utf8')
|
||||||
|
original = runpy.run_path
|
||||||
|
def capture(*args, **kwargs):
|
||||||
|
self.launcher = original(*args, **kwargs)
|
||||||
|
return self.launcher
|
||||||
|
with patch.object(sys, 'argv', ['bridge', str(script), action]), patch.object(runpy, 'run_path', side_effect=capture):
|
||||||
|
return original(str(BRIDGE))
|
||||||
|
|
||||||
|
def shutdown_fixture(self, *, console_error='RuntimeError', stopped=True, foreign=False, same=True, modern=False, terminate_error=False):
|
||||||
|
return f'''
|
||||||
|
from pathlib import Path
|
||||||
|
from contextlib import nullcontext
|
||||||
|
calls = []
|
||||||
|
world = {{'pid': 123, 'created': 456, 'exe': str(Path(__file__).resolve().parents[1] / {'"foreign.exe"' if foreign else '"Core/worldserver.exe"'})}}
|
||||||
|
def wait_ready(*args): pass
|
||||||
|
def start_mysql(): raise AssertionError('must not start')
|
||||||
|
def main(): raise AssertionError('must not prepare')
|
||||||
|
def settings(): return {{}}
|
||||||
|
def control_lock(): return nullcontext()
|
||||||
|
def process(name): return world if name == 'world' else None
|
||||||
|
def same_process(record): return {same!r}
|
||||||
|
def ra(command, config):
|
||||||
|
calls.append('console')
|
||||||
|
{'raise '+console_error+'("Start this repack worldserver first")' if console_error else 'return "Graceful shutdown"'}
|
||||||
|
def terminate(record):
|
||||||
|
assert record is world
|
||||||
|
calls.append('terminate')
|
||||||
|
{'raise RuntimeError("identity changed")' if terminate_error else 'pass'}
|
||||||
|
def wait_stopped(record, seconds):
|
||||||
|
assert record is world
|
||||||
|
calls.append('wait')
|
||||||
|
return {stopped!r}
|
||||||
|
def stop_all(config):
|
||||||
|
record = process('world')
|
||||||
|
if record:
|
||||||
|
if {modern!r}:
|
||||||
|
try: ra('server shutdown 1s 0', config)
|
||||||
|
except (OSError, RuntimeError): terminate(record)
|
||||||
|
else:
|
||||||
|
ra('server shutdown 1s 0', config)
|
||||||
|
if not wait_stopped(record, 60): raise RuntimeError('world still alive')
|
||||||
|
calls.append('mysql-shutdown')
|
||||||
|
'''
|
||||||
|
|
||||||
|
def test_unavailable_console_in_restored_legacy_launcher_stops_owned_world_before_mysql(self):
|
||||||
|
for error in ['RuntimeError', 'OSError']:
|
||||||
|
with self.subTest(error=error):
|
||||||
|
result = self.launch('stop-all', self.shutdown_fixture(console_error=error))
|
||||||
|
self.assertEqual(result['launcher']['calls'], ['console', 'terminate', 'wait', 'wait', 'mysql-shutdown'])
|
||||||
|
|
||||||
|
def test_healthy_console_keeps_graceful_shutdown(self):
|
||||||
|
result = self.launch('stop-all', self.shutdown_fixture(console_error=None))
|
||||||
|
self.assertEqual(result['launcher']['calls'], ['console', 'wait', 'mysql-shutdown'])
|
||||||
|
|
||||||
|
def test_foreign_or_reused_process_is_never_terminated_even_by_a_modern_launcher_catch(self):
|
||||||
|
for modern in [False, True]:
|
||||||
|
for identity in [{'foreign': True}, {'same': False}]:
|
||||||
|
with self.subTest(modern=modern, **identity):
|
||||||
|
with self.assertRaisesRegex(Exception, 'ownership could not be verified'):
|
||||||
|
self.launch('stop-all', self.shutdown_fixture(modern=modern, **identity))
|
||||||
|
self.assertEqual(self.launcher['calls'], ['console'])
|
||||||
|
|
||||||
|
def test_world_that_stays_alive_blocks_database_shutdown(self):
|
||||||
|
for modern in [False, True]:
|
||||||
|
with self.subTest(modern=modern):
|
||||||
|
with self.assertRaisesRegex(Exception, 'database was left running'):
|
||||||
|
self.launch('stop-all', self.shutdown_fixture(stopped=False, modern=modern))
|
||||||
|
self.assertEqual(self.launcher['calls'], ['console', 'terminate', 'wait'])
|
||||||
|
|
||||||
|
def test_termination_identity_failure_leaves_mysql_untouched(self):
|
||||||
|
for modern in [False, True]:
|
||||||
|
with self.subTest(modern=modern):
|
||||||
|
with self.assertRaisesRegex(Exception, 'could not be stopped safely'):
|
||||||
|
self.launch('stop-all', self.shutdown_fixture(terminate_error=True, modern=modern))
|
||||||
|
self.assertEqual(self.launcher['calls'], ['console', 'terminate'])
|
||||||
|
|
||||||
|
def test_slow_mysql_gets_time_to_finish_but_other_waits_are_unchanged(self):
|
||||||
|
result = self.launch('start-mysql', '''
|
||||||
|
calls = []
|
||||||
|
def wait_ready(name, port, seconds=180):
|
||||||
|
calls.append((name, seconds))
|
||||||
|
if name == 'mysql' and seconds < 162:
|
||||||
|
raise RuntimeError('mysql is still starting')
|
||||||
|
def start_mysql():
|
||||||
|
wait_ready('mysql', 12345, 60)
|
||||||
|
def main():
|
||||||
|
start_mysql()
|
||||||
|
wait_ready('world', 23456, 180)
|
||||||
|
wait_ready('mysql', 12345, 900)
|
||||||
|
''')
|
||||||
|
self.assertEqual(result['launcher']['calls'], [('mysql', 300), ('world', 180), ('mysql', 900)])
|
||||||
|
|
||||||
|
def test_stop_dispatch_does_not_prepare_or_start_anything(self):
|
||||||
|
result = self.launch('stop-all', '''
|
||||||
|
from contextlib import nullcontext
|
||||||
|
calls = []
|
||||||
|
def wait_ready(*args): raise AssertionError('must not wait')
|
||||||
|
def start_mysql(): raise AssertionError('must not start')
|
||||||
|
def main(): raise AssertionError('must not prepare')
|
||||||
|
def settings(): return {'mysqlPort': 12345}
|
||||||
|
def control_lock(): return nullcontext()
|
||||||
|
def stop_all(config): calls.append(config['mysqlPort'])
|
||||||
|
''')
|
||||||
|
self.assertEqual(result['launcher']['calls'], [12345])
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == '__main__':
|
||||||
|
unittest.main()
|
||||||
@@ -0,0 +1,32 @@
|
|||||||
|
import assert from "node:assert/strict";
|
||||||
|
import test from "node:test";
|
||||||
|
import { updateCheckQueue } from "../src/lib/updateCheckQueue.ts";
|
||||||
|
|
||||||
|
test("duplicate checks share one result and foreground waits for background on the same server", async () => {
|
||||||
|
const check = updateCheckQueue();
|
||||||
|
let release;
|
||||||
|
let calls = 0;
|
||||||
|
const background = check("server", "background", () => { calls++; return new Promise(resolve => { release = resolve; }); });
|
||||||
|
assert.equal(check("server", "background", () => { throw Error("duplicate"); }), background);
|
||||||
|
const foreground = check("server", "foreground", async () => { calls++; return "full preview"; });
|
||||||
|
await Promise.resolve();
|
||||||
|
await Promise.resolve();
|
||||||
|
assert.equal(calls, 1);
|
||||||
|
release("background preview");
|
||||||
|
assert.equal(await background, "background preview");
|
||||||
|
assert.equal(await foreground, "full preview");
|
||||||
|
assert.equal(calls, 2);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("one server's failure releases its queue and does not block other servers", async () => {
|
||||||
|
const check = updateCheckQueue();
|
||||||
|
let fail;
|
||||||
|
const first = check("one", "a", () => new Promise((_, reject) => { fail = reject; }));
|
||||||
|
const failed = assert.rejects(first, /offline/);
|
||||||
|
const next = check("one", "b", async () => "retry");
|
||||||
|
assert.equal(await check("two", "a", async () => "independent"), "independent");
|
||||||
|
fail(Error("offline"));
|
||||||
|
await failed;
|
||||||
|
assert.equal(await next, "retry");
|
||||||
|
assert.equal(await check("one", "a", async () => "recovered"), "recovered");
|
||||||
|
});
|
||||||
Reference in new issue
Block a user