mirror of
https://github.com/Corfirean/coa-server-manager.git
synced 2026-11-19 03:25:56 +00:00
Compare commits
22
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
fac6ce469a | ||
|
|
f22cedd963 | ||
|
|
0b5f12941c | ||
|
|
f3fc14b55a | ||
|
|
beaec7d27e | ||
|
|
8490dc9983 | ||
|
|
3f8abcbbe8 | ||
|
|
b3c50a7b39 | ||
|
|
bbdad37e40 | ||
|
|
0ed4d5e268 | ||
|
|
b13ee55bb9 | ||
|
|
51a45db8cb | ||
|
|
3f700ee8f4 | ||
|
|
277ebba847 | ||
|
|
9a0b815937 | ||
|
|
78b84e11c2 | ||
|
|
6aea9011f9 | ||
|
|
171d9a2bf8 | ||
|
|
0d6d8a0db8 | ||
|
|
3940506987 | ||
|
|
f25a1d425d | ||
|
|
b5e4a38d7d |
No files matched your search
@@ -12,32 +12,16 @@ permissions:
|
||||
|
||||
jobs:
|
||||
installer:
|
||||
runs-on: [self-hosted, Windows, X64, coa-update-acceptance]
|
||||
timeout-minutes: 1440
|
||||
runs-on: windows-latest
|
||||
timeout-minutes: 60
|
||||
steps:
|
||||
- uses: actions/checkout@v7
|
||||
- uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: 26.10.0
|
||||
node-version: 22
|
||||
- run: npm ci
|
||||
- name: Tests
|
||||
run: cargo test --workspace --locked -- --test-threads=1
|
||||
- name: Windows server upgrade and recovery gate
|
||||
shell: pwsh
|
||||
env:
|
||||
GH_TOKEN: ${{ github.token }}
|
||||
run: |
|
||||
cargo build -p coa-release --locked
|
||||
if ($LASTEXITCODE) { throw 'Verification tools failed to build.' }
|
||||
gh release download base --repo Corfirean/coa-server-build --dir _acceptance-base
|
||||
if ($LASTEXITCODE) { throw 'Signed base download failed.' }
|
||||
& target/debug/coa-release.exe resolve --source https://github.com/Corfirean/coa-server-build/releases/download/edge --out _candidate-manifest.json
|
||||
if ($LASTEXITCODE) { throw 'Cannot pin the candidate server release.' }
|
||||
$version = (Get-Content _candidate-manifest.json -Raw | ConvertFrom-Json).version
|
||||
gh release download "server-$version" --repo Corfirean/coa-server-build --dir _acceptance-candidate
|
||||
if ($LASTEXITCODE) { throw 'Candidate download failed.' }
|
||||
& tools/update-chaos-matrix.ps1 -BasePackage _acceptance-base -CandidatePackage _acceptance-candidate
|
||||
if ($LASTEXITCODE) { throw 'Update/recovery acceptance failed; manager will not be published.' }
|
||||
run: cargo test --workspace -- --test-threads=1
|
||||
- name: Build, sign and publish
|
||||
uses: tauri-apps/tauri-action@v0
|
||||
env:
|
||||
@@ -48,29 +32,7 @@ jobs:
|
||||
tagName: ${{ github.ref_name }}
|
||||
releaseName: CoA Server Manager ${{ github.ref_name }}
|
||||
releaseBody: See the assets to download the installer. Existing installations update themselves.
|
||||
releaseDraft: true
|
||||
releaseDraft: false
|
||||
prerelease: false
|
||||
args: --bundles nsis
|
||||
includeUpdaterJson: true
|
||||
- name: Verify the exact packaged installer
|
||||
shell: pwsh
|
||||
run: |
|
||||
$installer = Get-ChildItem target/release/bundle/nsis/*-setup.exe | Select-Object -First 1
|
||||
if (-not $installer) { throw 'Built installer is missing.' }
|
||||
$destination = Join-Path $env:RUNNER_TEMP ('coa-manager-installer-' + [guid]::NewGuid().ToString('N'))
|
||||
$process = Start-Process -FilePath $installer.FullName -ArgumentList @('/S', "/D=$destination") -WindowStyle Hidden -Wait -PassThru
|
||||
if ($process.ExitCode) { throw 'Silent installer failed.' }
|
||||
$installed = Join-Path $destination 'coa-server-manager.exe'
|
||||
if (-not (Test-Path $installed)) { throw 'Installed manager binary is missing.' }
|
||||
if ((Get-FileHash $installed).Hash -ne (Get-FileHash target/release/coa-server-manager.exe).Hash) { throw 'Installer contains a different manager binary.' }
|
||||
$report = @{ installerSha256 = (Get-FileHash $installer.FullName).Hash.ToLower(); managerSha256 = (Get-FileHash $installed).Hash.ToLower(); source = '${{ github.sha }}'; serverManifestSha256 = (Get-FileHash _acceptance-candidate/manifest.json).Hash.ToLower(); result = 'passed' }
|
||||
$report | ConvertTo-Json | Set-Content installer-acceptance.json -Encoding utf8NoBOM
|
||||
- name: Publish validated draft
|
||||
shell: pwsh
|
||||
env:
|
||||
GH_TOKEN: ${{ github.token }}
|
||||
run: |
|
||||
gh release upload '${{ github.ref_name }}' installer-acceptance.json --clobber
|
||||
if ($LASTEXITCODE) { throw 'Acceptance report upload failed.' }
|
||||
gh release edit '${{ github.ref_name }}' --draft=false
|
||||
if ($LASTEXITCODE) { throw 'Validated draft publication failed.' }
|
||||
Generated
+14
-6
@@ -491,7 +491,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "coa-core"
|
||||
version = "0.6.5"
|
||||
version = "0.6.6"
|
||||
dependencies = [
|
||||
"base64 0.22.1",
|
||||
"chrono",
|
||||
@@ -499,6 +499,7 @@ dependencies = [
|
||||
"ed25519-dalek",
|
||||
"fs4",
|
||||
"hex",
|
||||
"if-addrs",
|
||||
"num-bigint",
|
||||
"rand_core",
|
||||
"reqwest 0.12.28",
|
||||
@@ -519,19 +520,16 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "coa-release"
|
||||
version = "0.6.5"
|
||||
version = "0.6.6"
|
||||
dependencies = [
|
||||
"base64 0.22.1",
|
||||
"chrono",
|
||||
"coa-core",
|
||||
"ed25519-dalek",
|
||||
"serde_json",
|
||||
"tempfile",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "coa-server-manager"
|
||||
version = "0.6.5"
|
||||
version = "0.6.6"
|
||||
dependencies = [
|
||||
"coa-core",
|
||||
"serde",
|
||||
@@ -1916,6 +1914,16 @@ dependencies = [
|
||||
"icu_properties",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "if-addrs"
|
||||
version = "0.15.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "c0a05c691e1fae256cf7013d99dad472dc52d5543322761f83ec8d47eab40d2b"
|
||||
dependencies = [
|
||||
"libc",
|
||||
"windows-sys 0.61.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "indexmap"
|
||||
version = "1.9.3"
|
||||
|
||||
+1
-1
@@ -3,7 +3,7 @@ resolver = "2"
|
||||
members = ["crates/coa-core", "crates/coa-release", "src-tauri"]
|
||||
|
||||
[workspace.package]
|
||||
version = "0.6.5"
|
||||
version = "0.6.6"
|
||||
edition = "2021"
|
||||
license = "AGPL-3.0-only"
|
||||
|
||||
|
||||
@@ -0,0 +1,104 @@
|
||||
# Urgent update hotfix
|
||||
|
||||
Deadline: 2026-10-06. This checkout starts at the exact v0.6.4 tag, commit
|
||||
6c771fa, and excludes the ongoing isolated-trial/recovery redesign.
|
||||
|
||||
The client accepts checksum compatibility only from a verified signed manifest and only
|
||||
for an Applied migration. It never updates the historical checksum, reruns historical
|
||||
SQL, or excuses a Running/Failed ledger row. A server package must explicitly list the
|
||||
verified published variants and append corrections under new migration IDs.
|
||||
|
||||
Current local evidence: the locked workspace tests passed, including 252 core tests
|
||||
run serially. Six frontend logic tests and the frontend production build passed.
|
||||
The hotfix runtime was tested against the exact signed candidate manifest on the marked
|
||||
CoA/Wildcard fixture. Both published repair checksums were accepted independently in
|
||||
both worlds, with zero migration executions, unchanged historical checksums, and unchanged
|
||||
account, character and inventory counts. The original ledger rows were restored after
|
||||
the test, and all fixture processes were stopped. A real Running or Failed repair row in
|
||||
either world was rejected before staging or creating a transaction, with unchanged world
|
||||
executable and installation metadata. Tests use independent hotfix metadata so experimental
|
||||
transaction formats are not confused with the 0.6.4 upgrade path. Windows journal writes also use flushed
|
||||
atomic replacement with long-path support. Changelog validation passed.
|
||||
|
||||
Additional guards implemented:
|
||||
|
||||
- Read migration history without creating its ledger before downloading or replacing files.
|
||||
- Reject missing journals, invalid identities, paths, hashes and inconsistent operations.
|
||||
Durable completed-cleanup markers distinguish interrupted pruning from a lost journal.
|
||||
- Preserve all backups while an update is unfinished or its journal is damaged.
|
||||
- Verify saved-file hashes and the complete database/configuration recovery point before
|
||||
stopping services or changing files/databases. New snapshots include configuration hashes;
|
||||
update journals bind their backup metadata to a hash.
|
||||
- Surface state-reading errors in Settings and disable applying until the disk state is
|
||||
successfully read. Checking again refreshes that state.
|
||||
- Verify every extracted SQL artifact before taking the update snapshot or replacing
|
||||
server files; missing files, invalid IDs, duplicate migrations and checksum disagreements
|
||||
reject the update early. SQL application repeats the integrity check immediately before use.
|
||||
- Count unapplied migrations in the active and secondary realms, counting shared auth once.
|
||||
Matching versions and files do not hide remaining database work. Preview reads history
|
||||
under the installation lock; a stopped database is temporarily started for inspection
|
||||
and stopped again when no game services are running.
|
||||
- Reread the disk state after every update/recovery attempt, including failed attempts and
|
||||
background updates. Unfinished or unreadable state blocks another application in the UI.
|
||||
- Acquire the installation lock before checking and deleting a backup.
|
||||
|
||||
Latest real-runtime test used the independently copied, doubly marked fixture
|
||||
`C:\games\coa-schema-fixture-chaos-20261005-v1` and signed candidate `0.261005.24`, manifest SHA-256
|
||||
`1284b1273815209c9621b6d173a2211bae316f33462ccbe8b578e53b8d26fb5b`.
|
||||
All 1748 SQL artifacts passed verification after authenticated archive extraction.
|
||||
Removing one repair record separately in CoA and Wildcard increased the pending count
|
||||
by exactly one; restoring its original record restored the original count. No migrations
|
||||
were executed, player counts were preserved and fixture services were stopped afterward.
|
||||
The source checkout remains uncommitted; these results are not an installer acceptance report.
|
||||
|
||||
Additional acceptance on 2026-10-06: a new independent installation/database copy at
|
||||
`C:\games\coa-schema-fixture-chaos-064-transition-20261006` received the authenticated
|
||||
published `0.261005.22` program files, original CRLF repair checksum, and a deliberately
|
||||
missing Wildcard table in both realms. The production hotfix update pipeline committed
|
||||
signed candidate `0.261005.24`, repaired both realms, passed schema checks and actual
|
||||
bundled-Python server startup, and preserved the selected account, character, item and
|
||||
inventory fields byte-for-byte. The fixture was stopped afterward. The harness explicitly
|
||||
instruments the launcher to prevent relay submissions and bind to localhost; this is not
|
||||
proof of packaged UI behavior or operating-system network containment.
|
||||
|
||||
Local installer `C:\games\source\manager-065-local-installer-20261006\CoA Server Manager_0.6.5_x64-setup.exe`
|
||||
has SHA-256 `520ee0391d923b92da0a20591e30006c048cdb60156275d7a829918bf1b77491`.
|
||||
Its updater signature and the published 0.6.4 installer's signature passed independent
|
||||
verification with the configured updater public key. Both executables extracted from
|
||||
their exact NSIS packages started, created responsive windows, and were stopped using
|
||||
an independent application/WebView profile. No installer was executed over a user's
|
||||
installation, and no UI update operation was exercised.
|
||||
|
||||
Legacy limitation: old 0.6.4 transaction copies and configuration snapshots without recorded
|
||||
hashes can be checked for presence and declared database hashes, but their original file
|
||||
contents cannot be authenticated retroactively. Missing copies block restoration. This
|
||||
hotfix does not claim that old unchecksummed copies received full integrity verification.
|
||||
|
||||
Remaining release requirements: reproduce the existing-user failures through the published
|
||||
0.6.4 interface, verify legacy unfinished transaction handling on real-runtime fixtures,
|
||||
and execute the exact installer over 0.6.4 in an isolated Windows environment with UI
|
||||
state/settings/server-list verification. Windows native UI automation is unavailable in
|
||||
this session. Packaged startup and signature checks do not satisfy that installer gate.
|
||||
No public release has been made.
|
||||
|
||||
The user subsequently exercised the packaged UI: candidate 0.261005.24 committed and
|
||||
both CoA and Wildcard were shown running. Repeat-check/restart acceptance is still pending.
|
||||
The screenshots exposed an older published package being offered after the local candidate
|
||||
was installed. Follow-up changes reject older packages before preview/database inspection
|
||||
and application and clear a cached offer after a failed recheck. All 253 core tests and
|
||||
seven frontend tests passed. The earlier installer hash above does not include this follow-up;
|
||||
a separately recorded revision is required. Native UI control was subsequently initialized
|
||||
through the deferred node_repl tool, then the user stopped automation with Escape and
|
||||
performed the UI check manually.
|
||||
|
||||
Another user repeat-check exposed the already installed launcher being offered again.
|
||||
The preview now verifies canonical launcher bytes against the current signed package,
|
||||
caches those bytes by SHA-256, and compares only recognized Manager transformations.
|
||||
The actual disposable fixture's repeat preview passed with all 104 files skipped and
|
||||
zero pending SQL. User edits, recorded custom content, and a package with different
|
||||
launcher bytes are not mistaken for that integration. All 254 core tests passed;
|
||||
the strengthened regression test and seven frontend tests also passed. The first
|
||||
preview of a managed launcher may download/extract its authenticated package to build
|
||||
the optional canonical cache. Earlier installer revisions do not include this fix.
|
||||
|
||||
Do not recommend deleting an installation or replacing its player databases.
|
||||
@@ -0,0 +1,7 @@
|
||||
---
|
||||
area: manager
|
||||
type: added
|
||||
audience: admins
|
||||
title: Install a server from a package on Linux, running in Docker (experimental)
|
||||
---
|
||||
Experimental. The Manager creates the database, imports the packaged baseline and starts the server in Docker containers. It needs a Linux server package and your own game data folder.
|
||||
@@ -1,7 +0,0 @@
|
||||
---
|
||||
area: manager
|
||||
type: changed
|
||||
audience: admins
|
||||
title: Server updates are tested on a private copy and automatically restored after failure
|
||||
---
|
||||
Updates keep a fixed verified package, preserve migration history, and recover interrupted changes before starting the server. Recovery problems show a specific reason and keep the available backups.
|
||||
@@ -0,0 +1,7 @@
|
||||
---
|
||||
area: manager
|
||||
type: fixed
|
||||
audience: admins
|
||||
title: Server updates accept verified published migration variants without rerunning them
|
||||
---
|
||||
Signed updates can recognise known published checksums without changing your migration history. Interrupted or failed SQL still requires recovery before retrying.
|
||||
@@ -0,0 +1,7 @@
|
||||
---
|
||||
area: manager
|
||||
type: fixed
|
||||
audience: admins
|
||||
title: Server updates replace older launchers adapted by the Manager for Wildcard
|
||||
---
|
||||
Updates recognize the Manager’s own realm and import adjustments even when older metadata still records the original launcher. New server binaries receive their matching launcher; genuine custom edits still require your decision.
|
||||
@@ -0,0 +1,8 @@
|
||||
---
|
||||
area: manager
|
||||
type: changed
|
||||
audience: admins
|
||||
title: The Auction House Bot card no longer asks for a character GUID
|
||||
---
|
||||
Turning the module and the seller on is enough: a server build with the automatic auction character creates its own account and character. The GUID field moved to the advanced settings.
|
||||
The buyer option hint no longer says it spends the auction character's gold.
|
||||
@@ -0,0 +1,7 @@
|
||||
---
|
||||
area: manager
|
||||
type: fixed
|
||||
audience: admins
|
||||
title: Choose and remember the local network address friends use to connect
|
||||
---
|
||||
Select an adapter or custom IPv4 address when sharing on LAN. Your choice survives restarts and mode changes; unavailable addresses show a warning instead of silently switching adapters.
|
||||
@@ -0,0 +1,7 @@
|
||||
---
|
||||
area: manager
|
||||
type: added
|
||||
audience: admins
|
||||
title: The NPC Enchanter card explains how to place and remove the NPC
|
||||
---
|
||||
The card now shows the two commands: `.npc add 601015` where you stand, and `.npc delete` on the targeted NPC.
|
||||
@@ -0,0 +1,7 @@
|
||||
---
|
||||
area: manager
|
||||
type: fixed
|
||||
audience: admins
|
||||
title: Older server packages cannot replace a newer installation
|
||||
---
|
||||
Update checks stop offering stale packages after an update. To undo an update, use its recovery point instead of applying an older server package.
|
||||
@@ -0,0 +1,7 @@
|
||||
---
|
||||
area: manager
|
||||
type: fixed
|
||||
audience: admins
|
||||
title: Checking again no longer offers an already installed launcher update
|
||||
---
|
||||
The Manager recognizes its own launcher integration while still detecting user edits and changes in newer signed packages.
|
||||
@@ -0,0 +1,7 @@
|
||||
---
|
||||
area: manager
|
||||
type: fixed
|
||||
audience: admins
|
||||
title: Large SQUID database imports have more time to finish on first startup
|
||||
---
|
||||
The Manager allows up to 45 minutes when SQUID Playerbots is enabled, covering its initial database import and bot creation. Ordinary server startup and shutdown keep their existing deadlines.
|
||||
@@ -0,0 +1,7 @@
|
||||
---
|
||||
area: manager
|
||||
type: fixed
|
||||
audience: admins
|
||||
title: Update history conflicts are detected before server files change
|
||||
---
|
||||
Damaged update records block changes and remain visible. Recovery checks saved copies before restoring, and unfinished updates protect backups from deletion and cleanup.
|
||||
@@ -0,0 +1,7 @@
|
||||
---
|
||||
area: manager
|
||||
type: fixed
|
||||
audience: admins
|
||||
title: Pending database updates remain visible when the server version matches
|
||||
---
|
||||
SQL files are checked before replacing server files. Update and recovery attempts refresh their saved status, including errors. Backup deletion cannot race with an update.
|
||||
@@ -0,0 +1,7 @@
|
||||
---
|
||||
area: manager
|
||||
type: fixed
|
||||
audience: admins
|
||||
title: Diagnostic files with database checks stay readable after secrets are removed
|
||||
---
|
||||
Removing a line that mentioned a secret could break the JSON files in a diagnostic package. Secret values are now replaced instead, so the files stay valid.
|
||||
@@ -0,0 +1,7 @@
|
||||
---
|
||||
area: manager
|
||||
type: added
|
||||
audience: admins
|
||||
title: One button collects all diagnostics, including crashes and Windows crash records
|
||||
---
|
||||
Report a problem collects logs, crash reports and small dumps, Windows crash records, update journals and the running server programs in one file, then shows its folder. Crashes without a server crash report are no longer missing.
|
||||
@@ -0,0 +1,7 @@
|
||||
---
|
||||
area: manager
|
||||
type: added
|
||||
audience: admins
|
||||
title: Problem reports go to the right project
|
||||
---
|
||||
Choose what the problem is about: Manager and other modules, CoA Companions, or SQUID Playerbots. The report opens in that project's GitHub page with the versions filled in. The bot system that is switched on is preselected.
|
||||
@@ -25,6 +25,7 @@ zip = { version = "2", default-features = false, features = ["deflate"] }
|
||||
sha1 = "0.10"
|
||||
tracing-subscriber = { version = "0.3", default-features = false, features = ["fmt", "std"] }
|
||||
tempfile = "3"
|
||||
if-addrs = "0.15"
|
||||
|
||||
[dev-dependencies]
|
||||
rand_core = { version = "0.6", features = ["getrandom"] }
|
||||
|
||||
@@ -0,0 +1,38 @@
|
||||
use std::{fs, path::PathBuf};
|
||||
use coa_core::{manifest::{Kind, Manifest}, package::{self, BuildOptions}, pkgsource::{self, Source}, release, signing, Result};
|
||||
|
||||
fn main() -> Result<()> {
|
||||
let args: Vec<String> = std::env::args().skip(1).collect();
|
||||
let source = Source::Dir(args[1].clone().into());
|
||||
let (previous, _) = pkgsource::fetch_manifest(&source, signing::EMBEDDED_PUBLIC_KEY)?;
|
||||
let tree = PathBuf::from(&args[2]);
|
||||
if args[0] == "extract" {
|
||||
assert!(!tree.exists(), "Use a new release tree");
|
||||
package::extract(&PathBuf::from(&args[1]), &previous, &tree, &|_, _| {})?;
|
||||
println!("Verified and extracted {}: {} historical migrations", previous.version, previous.migrations.len());
|
||||
return Ok(());
|
||||
}
|
||||
assert_eq!(args[0], "pack");
|
||||
let out = PathBuf::from(&args[3]);
|
||||
assert!(!out.exists(), "Release addresses must be immutable");
|
||||
for migration in &previous.migrations {
|
||||
let entry = previous.files.iter().find(|file| file.path.starts_with("_migrations/") && file.sha256 == migration.sha256).expect("Historical SQL entry");
|
||||
assert_eq!(coa_core::fsx::sha256_file(&tree.join(&entry.path))?, entry.sha256, "Historical SQL changed: {}", migration.id);
|
||||
}
|
||||
let mut manifest = package::build(&tree, &out, &BuildOptions {
|
||||
kind: Kind::Update, version: args[4].clone(), core_commit: Some(args[5].clone()),
|
||||
bots_commit: previous.bots.and_then(|revision| revision.commit),
|
||||
built_at: chrono::Utc::now().to_rfc3339(), part_size: package::DEFAULT_PART_SIZE,
|
||||
migrations: previous.migrations.clone(),
|
||||
}, &|line| println!("{line}"))?;
|
||||
manifest.min_manager_version = "0.6.5".into();
|
||||
manifest.validate()?;
|
||||
coa_core::fsx::atomic_write(&out.join("manifest.json"), &serde_json::to_vec_pretty(&manifest)?)?;
|
||||
let key_path = PathBuf::from(std::env::var("USERPROFILE").unwrap()).join(".coa-manager/signing/manifest-signing.key");
|
||||
release::sign_manifest(&out, &fs::read_to_string(key_path)?)?;
|
||||
coa_core::release_schema::verify_package(&out, signing::EMBEDDED_PUBLIC_KEY)?;
|
||||
let reread: Manifest = serde_json::from_slice(&fs::read(out.join("manifest.json"))?)?;
|
||||
assert_eq!(serde_json::to_value(reread.migrations)?, serde_json::to_value(previous.migrations)?);
|
||||
println!("PASS: signed {}; all historical migration bytes, checksums, aliases and order preserved", manifest.version);
|
||||
Ok(())
|
||||
}
|
||||
@@ -0,0 +1,70 @@
|
||||
use std::path::{Path, PathBuf};
|
||||
use coa_core::{backup, driver, fsx, Result};
|
||||
|
||||
fn set(root: &Path, filename: &str, values: &[(&str, &str)]) -> Result<()> {
|
||||
let path = root.join("Core/configs/modules").join(filename);
|
||||
let mut config = coa_core::config::parser::ConfFile::parse_bytes(&std::fs::read(&path)?)?;
|
||||
for (key, value) in values { config.set(key, value, &[]); }
|
||||
fsx::atomic_write(&path, config.to_text().as_bytes())
|
||||
}
|
||||
|
||||
fn ledgers(root: &Path) -> Result<Vec<String>> {
|
||||
backup::with_database(root, |db| ["acore_playerbots", "acore_world", "acore_characters"].into_iter()
|
||||
.map(|schema| db.query(&format!("SELECT path,sha256 FROM `{schema}`.coa_squid_migrations ORDER BY path;"))).collect())
|
||||
}
|
||||
|
||||
fn exercise(root: &Path) -> Result<()> {
|
||||
let meta = coa_core::registry::metadata_dir_for(root)?;
|
||||
let point = backup::create(root, &meta, backup::Kind::Full, backup::Trigger::Manual, Some("Disposable SQUID acceptance".into()), &|stage| println!("{stage}"))?;
|
||||
assert!(backup::verify(&meta, &point.id)?.ok);
|
||||
let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| -> Result<()> {
|
||||
backup::with_database(root, |db| db.query("DROP DATABASE IF EXISTS acore_playerbots;").map(|_| ()))?;
|
||||
assert!(driver::run(root, driver::Verb::StartAll)?.ok, "Disabled SQUID must start without its database");
|
||||
assert!(driver::run(root, driver::Verb::StopAll)?.ok);
|
||||
coa_core::multiworld::set_enabled(root, false)?;
|
||||
coa_core::realms::select(root, coa_core::realms::Mode::Coa)?;
|
||||
set(root, "mod_coa_playerbots.conf", &[("CoaBots.Enable", "0")])?;
|
||||
set(root, "playerbots.conf", &[("AiPlayerbot.Enabled", "1"), ("AiPlayerbot.RandomBotAutologin", "0"), ("AiPlayerbot.MinRandomBots", "0"), ("AiPlayerbot.MaxRandomBots", "0"), ("AiPlayerbot.RandomBotGuildCount", "0"), ("AiPlayerbot.RandomBotAccountCount", "0")])?;
|
||||
let started = driver::run(root, driver::Verb::StartAll)?;
|
||||
assert!(started.ok, "Fresh SQUID startup: {}", coa_core::diag::redact(&started.output));
|
||||
let before = ledgers(root)?;
|
||||
assert!(!before[0].is_empty(), "Fresh SQUID history missing");
|
||||
assert!(driver::run(root, driver::Verb::StopAll)?.ok);
|
||||
let started = driver::run(root, driver::Verb::StartAll)?;
|
||||
assert!(started.ok, "Repeated SQUID startup: {}", coa_core::diag::redact(&started.output));
|
||||
assert_eq!(ledgers(root)?, before, "SQUID replay changed its migration history");
|
||||
println!("PASS: SQUID-disabled dual startup without its database; fresh enabled SQUID import and startup; repeated startup preserves all three histories");
|
||||
Ok(())
|
||||
}));
|
||||
assert!(driver::run(root, driver::Verb::StopAll)?.ok);
|
||||
restore(root, &meta, &point)?;
|
||||
result.map_err(|_| coa_core::Error::Invalid("SQUID acceptance failed; disposable databases and configurations restored".into()))?
|
||||
}
|
||||
|
||||
fn restore(root: &Path, meta: &Path, point: &backup::RecoveryPoint) -> Result<()> {
|
||||
assert!(backup::verify(meta, &point.id)?.ok);
|
||||
assert!(driver::run(root, driver::Verb::StopAll)?.ok);
|
||||
coa_core::realms::select(root, point.realm)?;
|
||||
for component in point.components.iter().filter(|component| component.name != "configs") {
|
||||
backup::restore_database(root, meta, &point.id, &component.name)?;
|
||||
}
|
||||
backup::restore_configs(root, meta, &point.id)?;
|
||||
assert!(driver::run(root, driver::Verb::StopAll)?.ok);
|
||||
println!("PASS: disposable SQUID acceptance databases and original realm configurations restored");
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn main() -> Result<()> {
|
||||
let root = PathBuf::from(std::env::args().nth(1).unwrap());
|
||||
assert!(root.file_name().unwrap().to_string_lossy().starts_with("coa-schema-fixture-chaos-064-transition-"));
|
||||
assert_eq!(std::fs::read(root.join(".transition-fixture"))?, b"disposable published-064 transition fixture");
|
||||
assert!(!root.join("Data").symlink_metadata()?.file_type().is_symlink());
|
||||
assert!(driver::run(&root, driver::Verb::StopAll)?.ok);
|
||||
if let Some(id) = std::env::args().nth(2) {
|
||||
let meta = coa_core::registry::metadata_dir_for(&root)?;
|
||||
return restore(&root, &meta, &backup::get(&meta, &id)?);
|
||||
}
|
||||
let result = exercise(&root);
|
||||
assert!(driver::run(&root, driver::Verb::StopAll)?.ok);
|
||||
result
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
use std::{collections::BTreeMap, path::PathBuf};
|
||||
use coa_core::{backup, driver, registry::MetaDir, update::{self, RepackEnv}, Result};
|
||||
|
||||
fn players(db: &coa_core::db::Db) -> Result<String> {
|
||||
db.query("SELECT CONCAT(id,':',username,':',HEX(salt),':',HEX(verifier)) FROM acore_auth.account WHERE id=900001; SELECT CONCAT(guid,':',account,':',name,':',level,':',money) FROM acore_characters.characters WHERE guid=900001; SELECT CONCAT(guid,':',itemEntry,':',owner_guid,':',enchantments) FROM acore_characters.item_instance WHERE guid=900001; SELECT CONCAT(guid,':',bag,':',slot,':',item) FROM acore_characters.character_inventory WHERE guid=900001;")
|
||||
}
|
||||
|
||||
fn exercise(root: &std::path::Path, package: &str) -> Result<()> {
|
||||
let meta_dir = coa_core::registry::metadata_dir_for(root)?;
|
||||
let (_, meta) = MetaDir::open(&meta_dir)?;
|
||||
let expected = backup::with_database(root, |db| [coa_core::realms::Mode::Coa, coa_core::realms::Mode::Wildcard].into_iter().map(|mode| players(&db.clone().for_realm(mode))).collect::<Result<Vec<_>>>())?;
|
||||
assert!(driver::run(root, driver::Verb::StopAll)?.ok);
|
||||
let source = coa_core::pkgsource::Source::Dir(package.into());
|
||||
let preview = update::preview(root, &meta, &source, coa_core::signing::EMBEDDED_PUBLIC_KEY, &BTreeMap::new())?;
|
||||
assert_eq!(preview.pending_migrations, 0, "Historical SQL must not replay");
|
||||
assert!(!preview.items.iter().any(|item| item.action == update::Action::Conflict), "Unresolved candidate files: {:?}", preview.items);
|
||||
let environment = RepackEnv { root, meta_dir: &meta_dir };
|
||||
let outcome = update::apply(&update::Params {
|
||||
root, meta_dir: &meta_dir, source, trusted_key: coa_core::signing::EMBEDDED_PUBLIC_KEY,
|
||||
resolutions: BTreeMap::new(), cancel: Default::default(), env: &environment, fail_after_ops: None,
|
||||
}, &|stage, progress| println!("{progress}% {stage}"))?;
|
||||
assert_eq!(outcome.txn.state, update::State::Committed, "{:?}", outcome.txn);
|
||||
backup::with_database(root, |db| {
|
||||
for (index, mode) in [coa_core::realms::Mode::Coa, coa_core::realms::Mode::Wildcard].into_iter().enumerate() {
|
||||
let realm = db.clone().for_realm(mode);
|
||||
assert_eq!(players(&realm)?, expected[index], "Player data changed in {mode:?}");
|
||||
let problems = coa_core::schema_check::check(&realm, root)?;
|
||||
assert!(problems.is_empty(), "{problems:?}");
|
||||
}
|
||||
Ok(())
|
||||
})?;
|
||||
let release = coa_core::squid::release(root).expect("SQUID release metadata");
|
||||
println!("SQUID metadata: {release:?}");
|
||||
assert_eq!(coa_core::squid::fields(root)?.len(), 40);
|
||||
let (_, installed) = MetaDir::open(&meta_dir)?;
|
||||
let repeated = update::preview(root, &installed, &coa_core::pkgsource::Source::Dir(package.into()), coa_core::signing::EMBEDDED_PUBLIC_KEY, &BTreeMap::new())?;
|
||||
assert_eq!(repeated.pending_migrations, 0);
|
||||
assert!(repeated.items.iter().all(|item| item.action == update::Action::Skip), "{:?}", repeated.items);
|
||||
println!("PASS: coordinated update committed, both realms started, player fields preserved, historical SQL skipped, repeated preview clean");
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn main() -> Result<()> {
|
||||
let args: Vec<String> = std::env::args().skip(1).collect();
|
||||
let root = PathBuf::from(&args[0]);
|
||||
assert!(root.file_name().unwrap().to_string_lossy().starts_with("coa-schema-fixture-chaos-064-transition-"));
|
||||
assert_eq!(std::fs::read(root.join(".transition-fixture"))?, b"disposable published-064 transition fixture");
|
||||
assert_eq!(std::fs::read(root.join(".release-schema-fixture"))?, b"disposable release-schema fixture");
|
||||
assert!(!root.join("Data").symlink_metadata()?.file_type().is_symlink());
|
||||
assert!(driver::run(&root, driver::Verb::StopAll)?.ok);
|
||||
let outcome = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| exercise(&root, &args[1])));
|
||||
assert!(driver::run(&root, driver::Verb::StopAll)?.ok, "Fixture shutdown failed");
|
||||
outcome.map_err(|_| coa_core::Error::Invalid("Disposable coordinated acceptance failed; stopped services and retained recovery copies".into()))?
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
//! Install a new Docker server from a package folder, for a manual end-to-end check on Linux (needs docker).
|
||||
//! usage: docker_install <package folder> <destination> <game data folder> <public key (base64)>
|
||||
//! The key is the one the package was signed with (the production key is only used by the Manager itself).
|
||||
use coa_core::docker::install::{install, Params};
|
||||
use coa_core::download::Cancel;
|
||||
use coa_core::install::Source;
|
||||
use coa_core::registry::Registry;
|
||||
use std::path::PathBuf;
|
||||
|
||||
fn main() {
|
||||
let a: Vec<String> = std::env::args().skip(1).collect();
|
||||
assert!(a.len() == 4, "usage: docker_install <package folder> <destination> <game data folder> <public key>");
|
||||
let registry = Registry::at(std::env::temp_dir().join("coa-docker-install/installs.json"));
|
||||
let t = std::time::Instant::now();
|
||||
let done = install(
|
||||
&Params { source: Source::Dir(PathBuf::from(&a[0])), dest: PathBuf::from(&a[1]), data_dir: PathBuf::from(&a[2]), trusted_key: &a[3], registry: ®istry, cancel: Cancel::default() },
|
||||
&|s| eprintln!(" {:>3}% {} {}", s.percent, s.step, s.detail.unwrap_or_default()),
|
||||
)
|
||||
.unwrap_or_else(|e| panic!("install failed: {e}"));
|
||||
println!("installed {} at {} in {:?}", done.version, done.path, t.elapsed());
|
||||
}
|
||||
@@ -0,0 +1,93 @@
|
||||
//! Verify published checksum compatibility on a disposable real database, without running SQL migrations.
|
||||
use std::{path::{Path, PathBuf}, sync::atomic::{AtomicUsize, Ordering}};
|
||||
use coa_core::{backup, db::Db, migrations::{self, LedgerRow, Status, Store}, pkgsource::{self, Source}, Result};
|
||||
|
||||
struct Observed<'a> { db: &'a Db, executions: AtomicUsize }
|
||||
impl Store for Observed<'_> {
|
||||
fn load(&self) -> Result<Vec<LedgerRow>> { self.db.load() }
|
||||
fn put(&self, row: &LedgerRow) -> Result<()> { self.db.put(row) }
|
||||
fn run_file(&self, _: &str, _: &Path) -> Result<()> {
|
||||
self.executions.fetch_add(1, Ordering::SeqCst);
|
||||
panic!("Historical SQL must never be replayed");
|
||||
}
|
||||
}
|
||||
|
||||
fn main() -> Result<()> {
|
||||
let args: Vec<_> = std::env::args().skip(1).collect();
|
||||
let root = PathBuf::from(&args[0]);
|
||||
assert!(root.file_name().unwrap().to_string_lossy().starts_with("coa-schema-fixture-chaos-"));
|
||||
assert_eq!(std::fs::read(root.join(".coa-chaos-fixture"))?, b"disposable update chaos fixture");
|
||||
assert_eq!(std::fs::read(root.join(".release-schema-fixture"))?, b"disposable release-schema fixture");
|
||||
let source = Source::Dir(PathBuf::from(&args[1]));
|
||||
let package = pkgsource::fetch_manifest(&source, coa_core::signing::EMBEDDED_PUBLIC_KEY)?.0;
|
||||
let staging = tempfile::tempdir()?;
|
||||
let parts = pkgsource::fetch_parts(&source, &package, &staging.path().join("download"), &Default::default(), &|_, _| {})?;
|
||||
coa_core::package::extract(&parts, &package, &staging.path().join("tree"), &|_, _| {})?;
|
||||
migrations::verify_files(&package.migrations, &staging.path().join("tree/_migrations"))?;
|
||||
println!("PASS: all {} signed-package SQL artifacts verified before any database mutation", package.migrations.len());
|
||||
let migration = package.migrations.iter().find(|m| m.id == "manager_repair__20261005_missing_wildcard_tables").unwrap();
|
||||
let hashes = ["c1d8dbf2271234283a48a39e4b4aea1106b83b70581f1e3c4aa9fff438e8e4d2", "9e4a36245c3f83255415c122c01f08ceb3e3b83898d3d427ac4e2fbcf61e9638"];
|
||||
for hash in hashes { assert!(migration.sha256 == hash || migration.compatible_sha256.iter().any(|h| h == hash)); }
|
||||
let fixture_meta = coa_core::registry::metadata_dir_for(&root)?;
|
||||
let test_meta = tempfile::tempdir()?;
|
||||
coa_core::fsx::atomic_write(&test_meta.path().join("install.json"), &std::fs::read(fixture_meta.join("install.json"))?)?;
|
||||
coa_core::registry::MetaDir::open(test_meta.path())?;
|
||||
std::fs::create_dir_all(test_meta.path().join("updates"))?;
|
||||
let result = backup::with_database(&root, |db| {
|
||||
let mut modes = vec![coa_core::realms::Mode::Coa];
|
||||
if coa_core::realms::state(&root)?.wildcard_created { modes.push(coa_core::realms::Mode::Wildcard); }
|
||||
for mode in modes {
|
||||
let db = db.clone().for_realm(mode);
|
||||
let saved = db.load()?.into_iter().find(|row| row.id == migration.id && row.db == migration.db).expect("Published repair must already be applied");
|
||||
assert_eq!(saved.status, Status::Applied);
|
||||
let counts = db.query("SELECT CONCAT((SELECT COUNT(*) FROM acore_characters.characters),':',(SELECT COUNT(*) FROM acore_characters.item_instance),':',(SELECT COUNT(*) FROM acore_auth.account));")?;
|
||||
let check = || -> Result<()> {
|
||||
for hash in hashes {
|
||||
db.put(&LedgerRow { sha256: hash.into(), ..saved.clone() })?;
|
||||
let observed = Observed { db: &db, executions: AtomicUsize::new(0) };
|
||||
migrations::preflight(&db, std::slice::from_ref(migration))?;
|
||||
let report = migrations::apply_pending(&observed, std::slice::from_ref(migration), &root.join(".unused-hotfix-sql"), &|| panic!("Already applied SQL needs no snapshot"))?;
|
||||
assert!(report.applied.is_empty());
|
||||
assert_eq!(observed.executions.load(Ordering::SeqCst), 0);
|
||||
assert_eq!(db.load()?.into_iter().find(|r| r.id == migration.id && r.db == migration.db).unwrap().sha256, hash);
|
||||
}
|
||||
let meta = test_meta.path();
|
||||
let file_hash = coa_core::fsx::sha256_file(&root.join("Core/worldserver.exe"))?;
|
||||
let install_hash = coa_core::fsx::sha256_file(&meta.join("install.json"))?;
|
||||
let transaction_count = std::fs::read_dir(meta.join("updates"))?.count();
|
||||
for status in [Status::Running, Status::Failed] {
|
||||
db.put(&LedgerRow { status, ..saved.clone() })?;
|
||||
let env = coa_core::update::RepackEnv { root: &root, meta_dir: meta };
|
||||
let rejected = coa_core::update::apply(&coa_core::update::Params {
|
||||
root: &root, meta_dir: meta, source: Source::Dir(PathBuf::from(&args[1])),
|
||||
trusted_key: coa_core::signing::EMBEDDED_PUBLIC_KEY, cancel: Default::default(),
|
||||
resolutions: Default::default(), env: &env, fail_after_ops: None,
|
||||
}, &|_, _| {});
|
||||
let message = rejected.unwrap_err().to_string();
|
||||
assert!(message.contains("partially applied"), "Unexpected rejection: {message}");
|
||||
assert_eq!(std::fs::read_dir(meta.join("updates"))?.count(), transaction_count);
|
||||
assert_eq!(coa_core::fsx::sha256_file(&root.join("Core/worldserver.exe"))?, file_hash);
|
||||
assert_eq!(coa_core::fsx::sha256_file(&meta.join("install.json"))?, install_hash);
|
||||
}
|
||||
db.put(&saved)?;
|
||||
let env = coa_core::update::RepackEnv { root: &root, meta_dir: meta };
|
||||
let pending_before = env.pending_migrations(&package)?;
|
||||
db.query("DELETE FROM acore_world.coa_manager_migrations WHERE db='characters' AND id='manager_repair__20261005_missing_wildcard_tables';")?;
|
||||
assert_eq!(env.pending_migrations(&package)?, pending_before + 1,
|
||||
"Missing history in either realm must remain visible even with identical server files");
|
||||
db.put(&saved)?;
|
||||
assert_eq!(env.pending_migrations(&package)?, pending_before);
|
||||
Ok(())
|
||||
};
|
||||
let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(check));
|
||||
db.put(&saved)?;
|
||||
result.map_err(|_| coa_core::Error::Invalid("History regression assertion failed; the injected ledger row was restored.".into()))??;
|
||||
assert_eq!(db.query("SELECT CONCAT((SELECT COUNT(*) FROM acore_characters.characters),':',(SELECT COUNT(*) FROM acore_characters.item_instance),':',(SELECT COUNT(*) FROM acore_auth.account));")?, counts);
|
||||
println!("PASS: {} published checksums; Running/Failed rejected before staging; missing migration counted; zero SQL replays; history and player counts preserved", mode.name());
|
||||
}
|
||||
Ok(())
|
||||
});
|
||||
assert!(coa_core::driver::run(&root, coa_core::driver::Verb::StopAll)?.ok);
|
||||
result?;
|
||||
Ok(())
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
//! Read-only update preview against the marked disposable acceptance fixture.
|
||||
use std::{collections::BTreeMap,path::PathBuf};
|
||||
fn main()->coa_core::Result<()> {
|
||||
let args:Vec<_>=std::env::args().skip(1).collect();
|
||||
let root=PathBuf::from(&args[0]);
|
||||
assert!(root.file_name().unwrap().to_string_lossy().starts_with("coa-schema-fixture-chaos-064-transition-"));
|
||||
assert_eq!(std::fs::read(root.join(".transition-fixture"))?,b"disposable published-064 transition fixture");
|
||||
let meta_dir=coa_core::registry::metadata_dir_for(&root)?;
|
||||
let (_,meta)=coa_core::registry::MetaDir::open(&meta_dir)?;
|
||||
let preview=coa_core::update::preview(&root,&meta,&coa_core::pkgsource::Source::Dir(args[1].clone().into()),coa_core::signing::EMBEDDED_PUBLIC_KEY,&BTreeMap::new())?;
|
||||
assert_eq!(preview.from_version.as_deref(),Some(preview.to_version.as_str()));
|
||||
assert_eq!(preview.pending_migrations,0);
|
||||
assert!(preview.items.iter().all(|item|item.action==coa_core::update::Action::Skip),"{:?}",preview.items.iter().filter(|item|item.action!=coa_core::update::Action::Skip).collect::<Vec<_>>());
|
||||
println!("PASS: real fixture repeated preview: {} files unchanged, zero pending SQL, no update offered",preview.items.len());
|
||||
Ok(())
|
||||
}
|
||||
@@ -0,0 +1,165 @@
|
||||
//! Real signed-package transition on an independent, explicitly marked disposable copy.
|
||||
//! The Env wrapper instruments only launcher isolation; migration/backup/update code is production code.
|
||||
use std::{collections::BTreeMap, path::{Path, PathBuf}};
|
||||
use coa_core::{backup, driver, fsx, migrations, pkgsource::{self, Source}, registry::{InstallMeta, MetaDir}, update::{self, Env, RepackEnv}, Result};
|
||||
|
||||
struct Offline<'a>(RepackEnv<'a>);
|
||||
impl Env for Offline<'_> {
|
||||
fn ensure_stopped(&self) -> Result<()> { self.0.ensure_stopped() }
|
||||
fn preflight(&self, m: &coa_core::manifest::Manifest) -> Result<()> { self.0.preflight(m) }
|
||||
fn verify_snapshot(&self, id: &str) -> Result<()> { self.0.verify_snapshot(id) }
|
||||
fn snapshot(&self) -> Result<String> { self.0.snapshot() }
|
||||
fn restore_snapshot(&self, id: &str) -> Result<()> { self.0.restore_snapshot(id) }
|
||||
fn migrate(&self, m: &coa_core::manifest::Manifest, p: &Path) -> Result<migrations::ApplyReport> { self.0.migrate(m,p) }
|
||||
fn validate(&self) -> Result<()> {
|
||||
let path=self.0.root.join("Scripts/manage.py");
|
||||
let source=std::fs::read_to_string(&path)?.replace("\r\n", "\n");
|
||||
// Explicit test instrumentation prevents relay transmissions and binds services locally.
|
||||
let guarded=source.replace("def spawn(name, command, cwd, log):\n", "def spawn(name, command, cwd, log):\n for filename in ('worldserver.conf', 'authserver.conf'):\n path = ROOT / 'Core/configs' / filename\n if path.exists():\n text = path.read_text(encoding='utf-8-sig')\n for key, value in (('BindIP', '\"127.0.0.1\"'), ('Ra.IP', '\"127.0.0.1\"'), ('SOAP.Enabled', '0')):\n text = re.sub(r'(?m)^\\s*' + re.escape(key) + r'\\s*=.*$', '', text)\n text += '\\n' + key + ' = ' + value + '\\n'\n path.write_text(text, encoding='utf-8')\n").replace("def relay_worker():\n", "def relay_worker():\n save_process('relay-ready', os.getpid())\n while not (STATE / 'stop-relay').exists():\n time.sleep(0.5)\n return\n");
|
||||
assert_ne!(source,guarded,"Fixture launcher isolation failed");
|
||||
fsx::atomic_write(&path,guarded.as_bytes())?;
|
||||
self.0.validate()
|
||||
}
|
||||
}
|
||||
fn players(db: &coa_core::db::Db) -> Result<String> {
|
||||
db.query("SELECT CONCAT(id,':',username,':',HEX(salt),':',HEX(verifier)) FROM acore_auth.account WHERE id=900001; SELECT CONCAT(guid,':',account,':',name,':',level,':',money) FROM acore_characters.characters WHERE guid=900001; SELECT CONCAT(guid,':',itemEntry,':',owner_guid,':',enchantments) FROM acore_characters.item_instance WHERE guid=900001; SELECT CONCAT(guid,':',bag,':',slot,':',item) FROM acore_characters.character_inventory WHERE guid=900001;")
|
||||
}
|
||||
fn main() -> Result<()> {
|
||||
let args:Vec<_>=std::env::args().skip(1).collect();
|
||||
let root=PathBuf::from(&args[0]);
|
||||
assert!(root.file_name().unwrap().to_string_lossy().starts_with("coa-schema-fixture-chaos-064-transition-"));
|
||||
assert_eq!(std::fs::read(root.join(".transition-fixture"))?,b"disposable published-064 transition fixture");
|
||||
if args.get(3).is_some_and(|mode| mode=="legacy-recovery") {
|
||||
return run_fixture(&root,||legacy_recovery(&root));
|
||||
}
|
||||
assert!(!root.join(".transition-started").exists(),"Use a new independent fixture");
|
||||
fsx::atomic_write(&root.join(".transition-started"),b"started")?;
|
||||
let meta=coa_core::registry::metadata_dir_for(&root)?;
|
||||
assert!(!meta.exists(),"Do not reuse experimental or user metadata");
|
||||
run_fixture(&root,||exercise(&root,&meta,&args[1],&args[2]))
|
||||
}
|
||||
fn run_fixture(root:&Path,operation:impl FnOnce()->Result<()>)->Result<()> {
|
||||
let result=std::panic::catch_unwind(std::panic::AssertUnwindSafe(operation));
|
||||
assert!(driver::run(root,driver::Verb::StopAll)?.ok,"Fixture shutdown failed");
|
||||
result.map_err(|_|coa_core::Error::Invalid("Disposable acceptance assertion failed; services were stopped and recovery copies retained.".into()))?
|
||||
}
|
||||
fn legacy_recovery(root:&Path)->Result<()> {
|
||||
let meta=coa_core::registry::metadata_dir_for(root)?;
|
||||
assert!(driver::run(root,driver::Verb::StopAll)?.ok);
|
||||
let expected=backup::with_database(root,|db| [coa_core::realms::Mode::Coa,coa_core::realms::Mode::Wildcard].into_iter().map(|mode|players(&db.clone().for_realm(mode))).collect::<Result<Vec<_>>>())?;
|
||||
assert!(driver::run(root,driver::Verb::StopAll)?.ok);
|
||||
let dirs=std::fs::read_dir(meta.join("updates"))?.collect::<std::io::Result<Vec<_>>>()?;
|
||||
assert_eq!(dirs.len(),1,"Requires exactly the preceding successful disposable transition");
|
||||
let txn_dir=dirs[0].path();
|
||||
let journal=txn_dir.join("txn.json");
|
||||
let mut legacy:serde_json::Value=fsx::read_json(&journal)?;
|
||||
assert_eq!(legacy["state"],"committed");
|
||||
let point=legacy["recovery_point"].as_str().unwrap().to_string();
|
||||
let point_path=meta.join("backups").join(&point).join("backup.json");
|
||||
let mut point_json:serde_json::Value=fsx::read_json(&point_path)?;
|
||||
point_json["manager_version"]="0.6.4".into();
|
||||
for component in point_json["components"].as_array_mut().unwrap() { component.as_object_mut().unwrap().remove("file_sha256"); }
|
||||
fsx::atomic_write_json(&point_path,&point_json)?;
|
||||
legacy.as_object_mut().unwrap().remove("recovery_hashes");
|
||||
legacy.as_object_mut().unwrap().remove("databases_started");
|
||||
legacy["state"]="applied".into();
|
||||
fsx::atomic_write_json(&journal,&legacy)?;
|
||||
assert!(update::ensure_recovered(&meta).is_err(),"Legacy unfinished update must block startup");
|
||||
let id=legacy["id"].as_str().unwrap();
|
||||
let env=RepackEnv {root,meta_dir:&meta};
|
||||
println!("Recovering legacy-format transaction and recovery point on disposable installation");
|
||||
assert_eq!(update::rollback(root,&meta,id,&env)?.state,update::State::RolledBack);
|
||||
for op in legacy["ops"].as_array().unwrap() {
|
||||
let relative=op["path"].as_str().unwrap();
|
||||
if op["had_previous"]==true {
|
||||
assert_eq!(fsx::sha256_file(&fsx::safe_join(root,relative)?)?,fsx::sha256_file(&fsx::safe_join(&txn_dir.join("before"),relative)?)?,"Legacy file restoration mismatch: {relative}");
|
||||
} else { assert!(!fsx::safe_join(root,relative)?.exists()); }
|
||||
}
|
||||
assert_eq!(std::fs::read(meta.join("install.json"))?,std::fs::read(txn_dir.join("before/manager-install.json"))?);
|
||||
backup::with_database(root,|db| {
|
||||
for (index,mode) in [coa_core::realms::Mode::Coa,coa_core::realms::Mode::Wildcard].into_iter().enumerate() {
|
||||
let db=db.clone().for_realm(mode);
|
||||
assert_eq!(players(&db)?,expected[index]);
|
||||
assert_eq!(db.query("SELECT COUNT(*) FROM acore_world.coa_manager_migrations WHERE id IN ('manager_repair__20261005_reconcile_wildcard_tables','manager_repair__20261005_reconcile_missing_class_starts');")?,"0");
|
||||
assert_eq!(db.query("SELECT sha256 FROM acore_world.coa_manager_migrations WHERE id='manager_repair__20261005_missing_wildcard_tables';")?,"9e4a36245c3f83255415c122c01f08ceb3e3b83898d3d427ac4e2fbcf61e9638");
|
||||
}
|
||||
Ok(())
|
||||
})?;
|
||||
assert!(driver::run(root,driver::Verb::StopAll)?.ok);
|
||||
assert!(update::pending_checked(&meta)?.is_none());
|
||||
assert!(update::rollback(root,&meta,id,&env).is_err(),"Completed recovery must not run again");
|
||||
println!("PASS: legacy journal blocked startup; old files, metadata, migration histories and player fields restored; completed recovery rejects replay. Original baseline had a missing table, so healthy startup is not claimed after rollback.");
|
||||
Ok(())
|
||||
}
|
||||
fn exercise(root:&Path,meta:&Path,baseline:&str,candidate:&str)->Result<()> {
|
||||
let mut install:InstallMeta=fsx::read_json(&PathBuf::from("C:/games/coa-schema-fixture-chaos-20261005-v1.manager/install.json"))?;
|
||||
install.server_path=root.to_string_lossy().into_owned();
|
||||
install.id=uuid::Uuid::new_v4().to_string();
|
||||
install.manager_version="0.6.4".into();
|
||||
MetaDir::create(root,&install)?;
|
||||
// Private ports, and no inherited PID records or paths to the source database.
|
||||
let mut cfg:serde_json::Value=fsx::read_json(&root.join("Settings/repack.json"))?;
|
||||
let mut listeners=Vec::new();
|
||||
for key in ["mysqlPort","authPort","worldPort","raPort"] {
|
||||
let listener=std::net::TcpListener::bind("127.0.0.1:0")?;
|
||||
cfg[key]=listener.local_addr()?.port().into(); listeners.push(listener);
|
||||
}
|
||||
fsx::atomic_write_json(&root.join("Settings/repack.json"),&cfg)?;
|
||||
let mut profile:serde_json::Value=fsx::read_json(&root.join("Settings/realm-profile.json"))?;
|
||||
for key in ["secondary_world_port","secondary_ra_port"] {
|
||||
let listener=std::net::TcpListener::bind("127.0.0.1:0")?;
|
||||
profile[key]=listener.local_addr()?.port().into(); listeners.push(listener);
|
||||
}
|
||||
fsx::atomic_write_json(&root.join("Settings/realm-profile.json"),&profile)?;
|
||||
drop(listeners);
|
||||
let state=root.join(".state");
|
||||
if state.exists() { std::fs::remove_dir_all(&state)?; }
|
||||
let secondary_state=root.join(".realms/secondary/.state");
|
||||
if secondary_state.exists() { std::fs::remove_dir_all(&secondary_state)?; }
|
||||
let source=Source::Dir(baseline.into());
|
||||
let (manifest,_)=pkgsource::fetch_manifest(&source,coa_core::signing::EMBEDDED_PUBLIC_KEY)?;
|
||||
let temp=tempfile::tempdir()?;
|
||||
let parts=pkgsource::fetch_parts(&source,&manifest,&temp.path().join("download"),&Default::default(),&|_,_|{})?;
|
||||
let tree=temp.path().join("tree");
|
||||
coa_core::package::extract(&parts,&manifest,&tree,&|_,_|{})?;
|
||||
for file in &manifest.files {
|
||||
if file.path.starts_with("_migrations/") {continue;}
|
||||
fsx::atomic_write(&fsx::safe_join(root,&file.path)?,&std::fs::read(fsx::safe_join(&tree,&file.path)?)?)?;
|
||||
install.original_hashes.insert(file.path.clone(),file.sha256.clone());
|
||||
}
|
||||
install.core.version=Some(manifest.version);
|
||||
fsx::atomic_write_json(&meta.join("install.json"),&install)?;
|
||||
// Both worlds must remain local, including generated secondary configuration.
|
||||
for relative in ["Settings/worldserver.conf.template","Settings/authserver.conf.template"] {
|
||||
let p=root.join(relative);
|
||||
let mut conf=coa_core::config::parser::ConfFile::parse_bytes(&std::fs::read(&p)?)?;
|
||||
conf.set("BindIP","\"127.0.0.1\"",&[]); conf.set("Ra.IP","\"127.0.0.1\"",&[]); conf.set("SOAP.Enabled","0",&[]);
|
||||
fsx::atomic_write(&p,conf.to_text().as_bytes())?;
|
||||
}
|
||||
let expected=backup::with_database(root,|db| {
|
||||
let mut saved=Vec::new();
|
||||
for mode in [coa_core::realms::Mode::Coa,coa_core::realms::Mode::Wildcard] {
|
||||
let db=db.clone().for_realm(mode);
|
||||
saved.push(players(&db)?);
|
||||
db.query("DROP TABLE IF EXISTS acore_characters.coa_wildcard_skill_card; DELETE FROM acore_world.coa_manager_migrations WHERE id IN ('manager_repair__20261005_reconcile_wildcard_tables','manager_repair__20261005_reconcile_missing_class_starts'); UPDATE acore_world.coa_manager_migrations SET sha256='9e4a36245c3f83255415c122c01f08ceb3e3b83898d3d427ac4e2fbcf61e9638' WHERE id='manager_repair__20261005_missing_wildcard_tables' AND status='applied';")?;
|
||||
}
|
||||
Ok(saved)
|
||||
})?;
|
||||
let source=Source::Dir(candidate.into());
|
||||
let candidate_manifest=pkgsource::fetch_manifest(&source,coa_core::signing::EMBEDDED_PUBLIC_KEY)?.0;
|
||||
let choices:BTreeMap<_,_>=update::plan(root,&install,&candidate_manifest,&BTreeMap::new(),None)?.into_iter().filter(|p|p.action==update::Action::Conflict).map(|p|(p.path,update::Resolution::Replace)).collect();
|
||||
let env=Offline(RepackEnv{root,meta_dir:meta});
|
||||
let outcome=update::apply(&update::Params {root,meta_dir:meta,source,trusted_key:coa_core::signing::EMBEDDED_PUBLIC_KEY,cancel:Default::default(),resolutions:choices,env:&env,fail_after_ops:None},&|stage,pct|println!("{pct}% {stage}"))?;
|
||||
assert_eq!(outcome.txn.state,update::State::Committed,"{:?}",outcome.txn.message);
|
||||
backup::with_database(root,|db| {
|
||||
for (index,mode) in [coa_core::realms::Mode::Coa,coa_core::realms::Mode::Wildcard].into_iter().enumerate() {
|
||||
let db=db.clone().for_realm(mode);
|
||||
assert_eq!(players(&db)?,expected[index],"Player data changed in {}",mode.name());
|
||||
assert!(coa_core::schema_check::check(&db,root)?.is_empty());
|
||||
assert_eq!(migrations::pending_count(&db,&candidate_manifest.migrations)?,0);
|
||||
}
|
||||
Ok(())
|
||||
})?;
|
||||
println!("PASS: signed historical package to candidate; missing Wildcard table repaired in both realms; player fields and inventory preserved; schema and startup verified. Launcher isolation was test instrumentation, not packaged UI acceptance.");
|
||||
Ok(())
|
||||
}
|
||||
@@ -51,7 +51,7 @@ pub struct Component {
|
||||
pub sha256: Option<String>,
|
||||
pub tables: Option<usize>,
|
||||
pub files: Option<Vec<String>>,
|
||||
#[serde(default, skip_serializing_if = "std::collections::BTreeMap::is_empty")]
|
||||
#[serde(default)]
|
||||
pub file_sha256: std::collections::BTreeMap<String, String>,
|
||||
}
|
||||
|
||||
@@ -93,8 +93,7 @@ pub fn list(meta: &Path) -> Vec<RecoveryPoint> {
|
||||
}
|
||||
|
||||
pub fn get(meta: &Path, id: &str) -> Result<RecoveryPoint> {
|
||||
let path = fsx::ensure_within(meta, &point_dir(meta, id)?.join("backup.json"))?;
|
||||
let point: RecoveryPoint = fsx::read_json(&path).map_err(|_| Error::Invalid(format!("backup {id} was not found or its metadata is damaged")))?;
|
||||
let point: RecoveryPoint = fsx::read_json(&fsx::ensure_within(meta, &point_dir(meta, id)?.join("backup.json"))?).map_err(|_| Error::Invalid(format!("backup {id} was not found or its metadata is damaged")))?;
|
||||
if point.id != id || point.schema != 1 { return Err(Error::Invalid(format!("Backup {id} has inconsistent identity or an unsupported schema."))); }
|
||||
Ok(point)
|
||||
}
|
||||
@@ -137,7 +136,6 @@ pub fn config_files(root: &Path) -> Vec<String> {
|
||||
walk(root, &root.join("Settings/realm-profiles"), &mut out);
|
||||
if root.join("Settings/realm-profile.json").is_file() { out.push("Settings/realm-profile.json".into()); }
|
||||
out.sort();
|
||||
out.dedup();
|
||||
out
|
||||
}
|
||||
|
||||
@@ -149,11 +147,10 @@ fn copy_configs(root: &Path, dir: &Path) -> Result<Component> {
|
||||
for rel in &files {
|
||||
let src = fsx::safe_join(root, rel)?;
|
||||
let dst = fsx::safe_join(&target, rel)?;
|
||||
fs::create_dir_all(dst.parent().unwrap())?;
|
||||
let contents = fs::read(&src)?;
|
||||
fsx::atomic_write(&dst, &contents)?;
|
||||
bytes += contents.len() as u64;
|
||||
file_sha256.insert(rel.clone(), fsx::sha256_bytes(&contents));
|
||||
let content = fs::read(&src)?;
|
||||
fsx::atomic_write(&dst, &content)?;
|
||||
bytes += content.len() as u64;
|
||||
file_sha256.insert(rel.clone(), fsx::sha256_bytes(&content));
|
||||
}
|
||||
Ok(Component { name: "configs".into(), path: "files".into(), bytes, sha256: None, tables: None, files: Some(files), file_sha256 })
|
||||
}
|
||||
@@ -255,7 +252,7 @@ pub fn create(root: &Path, meta: &Path, kind: Kind, trigger: Trigger, label: Opt
|
||||
components,
|
||||
};
|
||||
fsx::atomic_write_json(&partial.join("backup.json"), &point)?;
|
||||
fsx::durable_replace(&partial, &final_dir)?;
|
||||
fs::rename(&partial, &final_dir)?;
|
||||
tracing::info!(%id, ?kind, ?trigger, "recovery point created");
|
||||
if trigger == Trigger::Automatic {
|
||||
prune_automatic(meta, 10);
|
||||
@@ -284,8 +281,21 @@ pub fn verify(meta: &Path, id: &str) -> Result<VerifyReport> {
|
||||
let point = get(meta, id)?;
|
||||
let dir = point_dir(meta, id)?;
|
||||
let mut problems = Vec::new();
|
||||
let mut names = std::collections::BTreeSet::new();
|
||||
let mut schemas = std::collections::BTreeSet::new();
|
||||
for c in &point.components {
|
||||
if !names.insert(&c.name) { problems.push(format!("{} appears more than once", c.name)); }
|
||||
let path = fsx::ensure_within(&dir, &fsx::safe_join(&dir, &c.path)?)?;
|
||||
if c.name != "configs" && (c.sha256.is_none() || c.tables.is_none()) { problems.push(format!("{} lacks database integrity metadata", c.name)); }
|
||||
if c.name == "configs" {
|
||||
if c.sha256.is_some() || c.files.is_none() { problems.push("configuration integrity metadata is inconsistent".into()); }
|
||||
} else {
|
||||
let schema = if c.name.contains('-') || c.name == "playerbots" { db::schema_of(&c.name) } else { point.realm.schema(&c.name) };
|
||||
match schema {
|
||||
Ok(schema) if schemas.insert(schema) => {}
|
||||
_ => problems.push(format!("{} has an unknown or duplicate database target", c.name)),
|
||||
}
|
||||
}
|
||||
match (&c.sha256, &c.files) {
|
||||
(Some(sha), _) => match fsx::sha256_file(&path) {
|
||||
Ok(actual) if actual.eq_ignore_ascii_case(sha) => {}
|
||||
@@ -294,14 +304,16 @@ pub fn verify(meta: &Path, id: &str) -> Result<VerifyReport> {
|
||||
},
|
||||
(None, Some(files)) => {
|
||||
for f in files {
|
||||
if !c.file_sha256.is_empty() && !c.file_sha256.contains_key(f) { problems.push(format!("configuration file {f} lacks its checksum")); }
|
||||
if !fsx::safe_join(&path, f).map(|p| p.is_file()).unwrap_or(false) {
|
||||
problems.push(format!("configuration file {f} is missing"));
|
||||
} else if let Some(expected) = c.file_sha256.get(f) {
|
||||
if fsx::sha256_file(&fsx::safe_join(&path, f)?).ok().as_deref() != Some(expected.as_str()) { problems.push(format!("configuration file {f} is damaged")); }
|
||||
let file = fsx::ensure_within(&dir, &fsx::safe_join(&path, f)?)?;
|
||||
if fsx::sha256_file(&file)?.as_str() != expected { problems.push(format!("configuration file {f} is damaged")); }
|
||||
}
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
_ => problems.push(format!("{} lacks an integrity inventory", c.name)),
|
||||
}
|
||||
}
|
||||
Ok(VerifyReport { ok: problems.is_empty(), problems })
|
||||
@@ -309,8 +321,7 @@ pub fn verify(meta: &Path, id: &str) -> Result<VerifyReport> {
|
||||
|
||||
/// Delete one recovery point (its own folder only).
|
||||
pub fn delete(meta: &Path, id: &str) -> Result<()> {
|
||||
// A damaged journal cannot reliably identify which copies recovery needs.
|
||||
// Preserve every available point until the installation is consistent.
|
||||
let _lock = crate::update::operation_lock(meta)?;
|
||||
crate::update::ensure_recovered(meta)?;
|
||||
if crate::update::unfinished(meta).is_some_and(|t| t.recovery_point.as_deref() == Some(id)) {
|
||||
return Err(Error::Invalid("This recovery point is required by an unfinished update and cannot be deleted.".into()));
|
||||
@@ -340,20 +351,6 @@ pub fn restore_configs(root: &Path, meta: &Path, id: &str) -> Result<RecoveryPoi
|
||||
Ok(safety)
|
||||
}
|
||||
|
||||
/// Transaction recovery has already protected the original state. Do not require a second backup.
|
||||
pub(crate) fn restore_update_configs(root: &Path, meta: &Path, id: &str) -> Result<()> {
|
||||
let point = get(meta, id)?;
|
||||
if !verify(meta, id)?.ok { return Err(Error::Invalid("The update recovery point is damaged.".into())); }
|
||||
let comp = point.components.iter().find(|c| c.name == "configs").ok_or_else(|| Error::Invalid("The update recovery point has no configuration.".into()))?;
|
||||
if comp.files.as_deref().unwrap_or_default().iter().any(|file| !comp.file_sha256.contains_key(file)) {
|
||||
return Err(Error::Invalid("This legacy recovery point has no configuration checksums. Automatic recovery cannot verify the original settings; copies were preserved for inspection.".into()));
|
||||
}
|
||||
for rel in comp.files.as_deref().unwrap_or_default() {
|
||||
fsx::atomic_write(&fsx::ensure_within(root, &fsx::safe_join(root, rel)?)?, &fs::read(fsx::safe_join(&point_dir(meta, id)?.join(&comp.path), rel)?)?)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize)]
|
||||
pub struct DbRestore {
|
||||
/// The database the restore replaced, kept intact under this name.
|
||||
@@ -365,14 +362,6 @@ pub struct DbRestore {
|
||||
/// Restore one database from a recovery point without dropping anything:
|
||||
/// import into a staging schema, sanity-check it, then swap tables atomically and keep the old schema.
|
||||
pub fn restore_database(root: &Path, meta: &Path, id: &str, name: &str) -> Result<DbRestore> {
|
||||
restore_database_inner(root, meta, id, name, true)
|
||||
}
|
||||
|
||||
pub(crate) fn restore_update_database(root: &Path, meta: &Path, id: &str, name: &str) -> Result<DbRestore> {
|
||||
restore_database_inner(root, meta, id, name, false)
|
||||
}
|
||||
|
||||
fn restore_database_inner(root: &Path, meta: &Path, id: &str, name: &str, safety_copy: bool) -> Result<DbRestore> {
|
||||
let point = get(meta, id)?;
|
||||
if point.realm != crate::realms::state(root)?.active {
|
||||
return Err(Error::Invalid("Select the realm this backup belongs to before restoring it.".into()));
|
||||
@@ -388,48 +377,21 @@ fn restore_database_inner(root: &Path, meta: &Path, id: &str, name: &str, safety
|
||||
let live = if name.contains('-') || name == "playerbots" { db::schema_of(name)? } else { point.realm.schema(name)? };
|
||||
let expected_tables = comp.tables.unwrap_or(0);
|
||||
let dump = point_dir(meta, id)?.join(&comp.path);
|
||||
let reconstructed_hash = point_dir(meta, id)?.join(format!("restore-{name}.sha256"));
|
||||
let stamp = if safety_copy { uuid::Uuid::new_v4().simple().to_string()[..16].to_string() }
|
||||
else { fsx::sha256_bytes(format!("update-recovery:{id}:{name}").as_bytes())[..16].to_string() };
|
||||
let stamp = uuid::Uuid::new_v4().simple().to_string()[..16].to_string();
|
||||
|
||||
// 1. Safety copy of the current state, so even a wrong restore is reversible.
|
||||
let safety = if safety_copy { Some(create(root, meta, Kind::Database, Trigger::BeforeRestore, Some(format!("before restoring {name} from {id}")), &|_| {})?.id) } else { None };
|
||||
let safety = create(root, meta, Kind::Database, Trigger::BeforeRestore, Some(format!("before restoring {name} from {id}")), &|_| {})?;
|
||||
|
||||
with_database(root, |db| {
|
||||
let db = db.clone().for_realm(crate::realms::Mode::Coa);
|
||||
let staging = format!("{live}_restore_{stamp}");
|
||||
let old = format!("{live}_before_restore_{stamp}");
|
||||
if safety_copy && (db.schema_exists(&staging)? || db.schema_exists(&old)?) {
|
||||
if db.schema_exists(&staging)? || db.schema_exists(&old)? {
|
||||
return Err(Error::Invalid("A previous restore left its work schemas behind; try again in a moment.".into()));
|
||||
}
|
||||
if !safety_copy {
|
||||
if db.schema_exists(&old)? {
|
||||
// RENAME TABLE is atomic. An empty staging schema proves that the old tables
|
||||
// were moved out and the complete restored set was moved into live together.
|
||||
if reconstructed_hash.is_file() && db.schema_exists(&staging)? && db.tables(&staging)?.is_empty() && db.tables(live)?.len() == expected_tables {
|
||||
db.query(&format!("DROP DATABASE `{old}`; DROP DATABASE `{staging}`;"))?;
|
||||
return Ok(DbRestore { previous_schema: old, safety_backup: String::new(), tables_restored: expected_tables });
|
||||
}
|
||||
// A server crash can interrupt a rename involving MyISAM tables.
|
||||
// The original dump was verified above and is authoritative: discard only
|
||||
// this recovery's deterministic work schemas and import a complete set again.
|
||||
db.query(&format!("DROP DATABASE `{old}`;"))?;
|
||||
}
|
||||
if db.schema_exists(&staging)? { db.query(&format!("DROP DATABASE `{staging}`;"))?; }
|
||||
}
|
||||
// 2. Import into staging.
|
||||
db.query(&format!("CREATE DATABASE `{staging}` CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;"))?;
|
||||
db.import_from(&staging, &dump)?;
|
||||
if !safety_copy {
|
||||
// SHOW CREATE TABLE can make implicit character sets explicit on import.
|
||||
// Compare live against the independently reconstructed snapshot, keeping all
|
||||
// schema and row bytes rather than accepting a table-count approximation.
|
||||
let check = point_dir(meta, id)?.join(format!("restore-{name}.sql.zst"));
|
||||
let (_, hash) = db.dump_to(&staging, &check)?;
|
||||
fsx::atomic_write(&reconstructed_hash, hash.as_bytes())?;
|
||||
fs::remove_file(check)?;
|
||||
}
|
||||
crate::update_fault::checkpoint(root, &format!("restore-database:{name}:imported"));
|
||||
// 3. Sanity checks.
|
||||
let staged = db.tables(&staging)?;
|
||||
if comp.tables.is_some_and(|expected| staged.len() != expected) || (comp.tables.is_none() && staged.is_empty()) {
|
||||
@@ -449,11 +411,7 @@ fn restore_database_inner(root: &Path, meta: &Path, id: &str, name: &str, safety
|
||||
renames.push(format!("`{staging}`.`{t}` TO `{live}`.`{t}`"));
|
||||
}
|
||||
if !renames.is_empty() { db.query(&format!("RENAME TABLE {};", renames.join(", ")))?; }
|
||||
crate::update_fault::checkpoint(root, &format!("restore-database:{name}:swapped"));
|
||||
// For emergency recovery, completed temporary schemas are disposable. A crash before
|
||||
// cleanup leaves the original dump intact, and another recovery can repeat the swap.
|
||||
if !safety_copy { db.query(&format!("DROP DATABASE `{old}`; DROP DATABASE `{staging}`;"))?; }
|
||||
Ok(DbRestore { previous_schema: old, safety_backup: safety.clone().unwrap_or_default(), tables_restored: staged.len() })
|
||||
Ok(DbRestore { previous_schema: old, safety_backup: safety.id.clone(), tables_restored: staged.len() })
|
||||
})
|
||||
}
|
||||
|
||||
@@ -475,15 +433,33 @@ mod tests {
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn corrupt_update_journal_preserves_available_backups() {
|
||||
fn backup_deletion_obeys_the_installation_lock() {
|
||||
let (_d, root, meta) = setup();
|
||||
let point = create(&root, &meta, Kind::Config, Trigger::Manual, None, &|_| {}).unwrap();
|
||||
let lock = crate::update::operation_lock(&meta).unwrap();
|
||||
assert!(delete(&meta, &point.id).is_err());
|
||||
assert!(get(&meta, &point.id).is_ok());
|
||||
drop(lock);
|
||||
delete(&meta, &point.id).unwrap();
|
||||
assert!(get(&meta, &point.id).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn damaged_configuration_is_detected_before_restore_and_copies_are_retained() {
|
||||
let (_d, root, meta) = setup();
|
||||
let point = create(&root, &meta, Kind::Config, Trigger::Automatic, None, &|_| {}).unwrap();
|
||||
let updates = meta.join("updates").join("interrupted");
|
||||
fs::create_dir_all(&updates).unwrap();
|
||||
fs::write(updates.join("txn.json"), b"{damaged").unwrap();
|
||||
let file = point_dir(&meta, &point.id).unwrap().join("files/Core/configs/worldserver.conf");
|
||||
fs::write(&file, b"corrupted").unwrap();
|
||||
assert!(!verify(&meta, &point.id).unwrap().ok);
|
||||
let original = fs::read(root.join("Core/configs/worldserver.conf")).unwrap();
|
||||
assert!(restore_configs(&root, &meta, &point.id).is_err());
|
||||
assert_eq!(fs::read(root.join("Core/configs/worldserver.conf")).unwrap(), original);
|
||||
assert_eq!(list(&meta).len(), 1);
|
||||
fs::create_dir_all(meta.join("updates/broken")).unwrap();
|
||||
fs::write(meta.join("updates/broken/txn.json"), b"{damaged").unwrap();
|
||||
assert!(delete(&meta, &point.id).is_err());
|
||||
prune_automatic(&meta, 0);
|
||||
assert!(get(&meta, &point.id).is_ok());
|
||||
assert!(file.exists());
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -89,9 +89,6 @@ pub(crate) fn credentials(root: &Path) -> Result<(String, String)> {
|
||||
}
|
||||
|
||||
impl Db {
|
||||
pub(crate) fn native_root(&self) -> Option<PathBuf> {
|
||||
if self.container.is_some() { None } else { self.bin.parent().and_then(|p| p.parent()).map(Path::to_path_buf) }
|
||||
}
|
||||
pub fn from_repack(root: &Path, account: Account) -> Result<Db> {
|
||||
let creds: Credentials = fsx::read_json(&root.join("Settings/database.json"))
|
||||
.map_err(|_| Error::Invalid("The database settings of this server could not be read.".into()))?;
|
||||
@@ -268,7 +265,7 @@ impl Db {
|
||||
let file = File::create(out)?;
|
||||
let mut enc = zstd::Encoder::new(BufWriter::new(file), 3)?;
|
||||
let copy = std::io::copy(&mut stdout, &mut enc);
|
||||
let finish = enc.finish().and_then(|mut w| { w.flush()?; w.get_ref().sync_all() });
|
||||
let finish = enc.finish().and_then(|mut w| w.flush());
|
||||
let status = child.wait()?;
|
||||
let stderr_bytes = err_thread.join().unwrap_or_default();
|
||||
if !status.success() {
|
||||
@@ -283,8 +280,6 @@ impl Db {
|
||||
|
||||
/// Run a plain SQL file against `schema`; the first error aborts and is returned.
|
||||
pub fn run_sql_file(&self, schema: &str, file: &Path) -> Result<()> {
|
||||
let injected = if let Some(root) = self.native_root() { crate::update_fault::failing_sql(&root, file)? } else { None };
|
||||
let file = injected.as_ref().map(|f| f.path()).unwrap_or(file);
|
||||
let schema = self.realm_schema(schema);
|
||||
if !ident_ok(schema) {
|
||||
return Err(Error::Invalid("bad schema name".into()));
|
||||
|
||||
+261
-13
@@ -172,19 +172,158 @@ pub fn squash_repeated_config_warnings(text: &str) -> String {
|
||||
s
|
||||
}
|
||||
|
||||
const SENSITIVE: [&str; 7] = ["password", "passwd", "secret", "token", "apikey", "api_key", "databaseinfo"];
|
||||
|
||||
/// Remove things that must never leave the machine from log text.
|
||||
pub fn redact(text: &str) -> String {
|
||||
let mut out = Vec::new();
|
||||
for line in text.lines() {
|
||||
let l = line.to_lowercase();
|
||||
let sensitive = ["password", "passwd", "secret", "token", "apikey", "api_key", "databaseinfo"].iter().any(|k| l.contains(k));
|
||||
let sensitive = SENSITIVE.iter().any(|k| l.contains(k));
|
||||
out.push(if sensitive { "[line removed: may contain a secret]".to_string() } else { line.to_string() });
|
||||
}
|
||||
out.join("\n")
|
||||
}
|
||||
|
||||
/// The same for JSON: values under a sensitive key and strings that look like `password=...` are replaced, and the
|
||||
/// result stays valid JSON (removing a whole line would break the file for whoever reads it). Text that is not JSON
|
||||
/// falls back to the line rule.
|
||||
pub fn redact_json(text: &str) -> String {
|
||||
fn scrub(v: &mut serde_json::Value) {
|
||||
use serde_json::Value;
|
||||
match v {
|
||||
Value::Object(map) => {
|
||||
for (key, value) in map.iter_mut() {
|
||||
let k = key.to_lowercase();
|
||||
if SENSITIVE.iter().any(|s| k.contains(s)) && !value.is_object() && !value.is_array() {
|
||||
*value = Value::String("[redacted]".into());
|
||||
} else {
|
||||
scrub(value);
|
||||
}
|
||||
}
|
||||
}
|
||||
Value::Array(items) => items.iter_mut().for_each(scrub),
|
||||
Value::String(s) => {
|
||||
let l = s.to_lowercase();
|
||||
if ["password=", "passwd=", "secret=", "token=", "apikey=", "api_key=", "password:"].iter().any(|k| l.contains(k)) {
|
||||
*s = "[redacted]".into();
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
match serde_json::from_str::<serde_json::Value>(text) {
|
||||
Ok(mut v) => {
|
||||
scrub(&mut v);
|
||||
serde_json::to_string_pretty(&v).unwrap_or_else(|_| redact(text))
|
||||
}
|
||||
Err(_) => redact(text),
|
||||
}
|
||||
}
|
||||
|
||||
/// Keep the events of a `wevtutil ... /f:text` listing that mention one of `needles` (compared without case), in the
|
||||
/// order listed, at most `max` of them.
|
||||
pub fn filter_event_blocks(listing: &str, needles: &[&str], max: usize) -> String {
|
||||
let mut blocks: Vec<Vec<&str>> = Vec::new();
|
||||
for line in listing.lines() {
|
||||
if line.starts_with("Event[") || blocks.is_empty() {
|
||||
blocks.push(Vec::new());
|
||||
}
|
||||
if let Some(b) = blocks.last_mut() { b.push(line); }
|
||||
}
|
||||
blocks
|
||||
.into_iter()
|
||||
.map(|b| b.join("\n"))
|
||||
.filter(|b| { let l = b.to_lowercase(); needles.iter().any(|n| l.contains(n)) })
|
||||
.take(max)
|
||||
.collect::<Vec<_>>()
|
||||
.join("\n\n")
|
||||
}
|
||||
|
||||
/// Drop the lines of an event listing that name the person or the computer.
|
||||
pub fn drop_identity_lines(listing: &str) -> String {
|
||||
listing
|
||||
.lines()
|
||||
.filter(|l| { let t = l.trim_start(); !(t.starts_with("User:") || t.starts_with("User Name:") || t.starts_with("Computer:")) })
|
||||
.collect::<Vec<_>>()
|
||||
.join("\n")
|
||||
}
|
||||
|
||||
/// `wevtutil /uni:true` writes UTF-16 with a byte order mark; anything else is read as UTF-8 (lossy).
|
||||
fn decode_console_output(bytes: &[u8]) -> String {
|
||||
if bytes.starts_with(&[0xFF, 0xFE]) {
|
||||
let units: Vec<u16> = bytes[2..].chunks_exact(2).map(|c| u16::from_le_bytes([c[0], c[1]])).collect();
|
||||
String::from_utf16_lossy(&units)
|
||||
} else {
|
||||
String::from_utf8_lossy(bytes).into_owned()
|
||||
}
|
||||
}
|
||||
|
||||
/// Crashes and hangs Windows recorded for the server programs in the last two weeks. This is the only trace of a crash
|
||||
/// that ends the process without the server's own crash report (a stack buffer overrun, for example). The lines that
|
||||
/// name the user and the computer are left out.
|
||||
#[cfg(windows)]
|
||||
fn windows_events() -> String {
|
||||
use std::os::windows::process::CommandExt;
|
||||
let query = "*[System[(Provider[@Name='Application Error' or @Name='Windows Error Reporting' or @Name='Application Hang']) and TimeCreated[timediff(@SystemTime) <= 1209600000]]]";
|
||||
let out = std::process::Command::new("wevtutil")
|
||||
.args(["qe", "Application", &format!("/q:{query}"), "/c:300", "/rd:true", "/f:text", "/uni:true"])
|
||||
.creation_flags(0x0800_0000)
|
||||
.output();
|
||||
match out {
|
||||
Ok(o) if o.status.success() => {
|
||||
let text = filter_event_blocks(&decode_console_output(&o.stdout), &["worldserver", "authserver", "mysqld", "coa server manager", "coa-server-manager"], 40);
|
||||
if text.is_empty() { "No crash or hang of the server programs was recorded by Windows in the last 14 days.".into() } else { drop_identity_lines(&text) }
|
||||
}
|
||||
Ok(o) => format!("Windows event log could not be read: {}", decode_console_output(&o.stderr).trim()),
|
||||
Err(e) => format!("Windows event log could not be read: {e}"),
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(not(windows))]
|
||||
fn windows_events() -> String {
|
||||
String::new()
|
||||
}
|
||||
|
||||
/// Newest files of a folder with the given extension (compared without case): path, size, modified time.
|
||||
fn newest_files(dir: &Path, ext: &str, limit: usize) -> Vec<(PathBuf, u64, std::time::SystemTime)> {
|
||||
let Ok(rd) = fs::read_dir(dir) else { return Vec::new() };
|
||||
let mut v: Vec<_> = rd
|
||||
.flatten()
|
||||
.filter(|e| e.path().extension().is_some_and(|x| x.eq_ignore_ascii_case(ext)))
|
||||
.filter_map(|e| { let m = e.metadata().ok()?; m.is_file().then(|| (e.path(), m.len(), m.modified().unwrap_or(std::time::UNIX_EPOCH))) })
|
||||
.collect();
|
||||
v.sort_by(|a, b| b.2.cmp(&a.2));
|
||||
v.truncate(limit);
|
||||
v
|
||||
}
|
||||
|
||||
/// Which server programs run right now and from where, next to what the Manager made of it. A program started from a
|
||||
/// folder or a copy the Manager does not know shows up here even when the Manager reports "port in use".
|
||||
fn processes_report(root: &Path, ports: &layout::Ports) -> String {
|
||||
let here = root.to_string_lossy().to_lowercase().replace('/', "\\");
|
||||
let listen = process::listeners_detailed();
|
||||
let mut out = String::from("Server programs running now (any folder):\n");
|
||||
let found = process::find_by_file_names(&["worldserver.exe", "authserver.exe", "mysqld.exe"]);
|
||||
if found.is_empty() { out.push_str(" none\n"); }
|
||||
for p in found {
|
||||
let ports_of: Vec<String> = listen.iter().filter(|l| l.pid == p.pid).map(|l| l.port.to_string()).collect();
|
||||
let inside = p.exe.to_lowercase().replace('/', "\\").starts_with(&here);
|
||||
out.push_str(&format!(" pid {} {} | listening on: {} | {}\n", p.pid, p.exe, if ports_of.is_empty() { "-".into() } else { ports_of.join(", ") }, if inside { "inside this server folder" } else { "OUTSIDE this server folder" }));
|
||||
}
|
||||
let o = process::observe(root, ports);
|
||||
out.push_str("\nThe Manager's view:\n");
|
||||
for s in [Some(&o.mysql), Some(&o.auth), Some(&o.world), o.secondary_world.as_ref()].into_iter().flatten() {
|
||||
out.push_str(&format!(" {:<16} {:?} port {} {}{}\n", s.name, s.state, s.port, s.pid.map(|p| format!("pid {p}")).unwrap_or_default(), s.conflict.as_ref().map(|c| format!(" | port held by pid {} {}", c.pid, c.exe.clone().unwrap_or_default())).unwrap_or_default()));
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Zip with what a maintainer needs to debug a problem, with secrets removed. Returns the number of files inside.
|
||||
/// One call collects everything: the Manager's and the server's logs, crash reports and small crash dumps, Windows'
|
||||
/// own record of crashes, the update journals, the running server programs and the settings the client depends on.
|
||||
pub fn export_package(root: &Path, meta_dir: &Path, manager_log: &Path, meta: &InstallMeta, report: &Report, out_zip: &Path) -> Result<usize> {
|
||||
const DUMP_FILE_MAX: u64 = 30 * 1024 * 1024;
|
||||
let file = fs::File::create(out_zip)?;
|
||||
let mut zip = zip::ZipWriter::new(file);
|
||||
let opts = zip::write::SimpleFileOptions::default().compression_method(zip::CompressionMethod::Deflated);
|
||||
@@ -195,8 +334,10 @@ pub fn export_package(root: &Path, meta_dir: &Path, manager_log: &Path, meta: &I
|
||||
n += 1;
|
||||
Ok(())
|
||||
};
|
||||
let ports = layout::read_ports(root);
|
||||
let summary = serde_json::json!({
|
||||
"manager": crate::MANAGER_VERSION,
|
||||
"exported_utc": chrono::Utc::now().to_rfc3339(),
|
||||
"core": meta.core,
|
||||
"bots": meta.bots,
|
||||
"squid_bots": crate::squid::release(root),
|
||||
@@ -206,7 +347,25 @@ pub fn export_package(root: &Path, meta_dir: &Path, manager_log: &Path, meta: &I
|
||||
"wow_client_set": meta.client_path.is_some(),
|
||||
});
|
||||
add("summary.json", serde_json::to_string_pretty(&summary)?.as_bytes())?;
|
||||
for (name, path) in [("manager.log", manager_log.to_path_buf()), ("manager-install.log", meta_dir.join("logs/manager.log")), ("Server.log.tail", root.join("Core/Logs/Server.log")), ("Errors.log.tail", root.join("Core/Logs/Errors.log")), ("Auth.log.tail", root.join("Core/Logs/Auth.log")), ("world-console.log.tail", root.join("Core/Logs/world-console.log")), ("mysql-error.log.tail", root.join("mysql/logs/mysql-error.log"))] {
|
||||
|
||||
// Logs. The newest update logs of the repack's own updater are added under their own names.
|
||||
let mut logs: Vec<(String, PathBuf)> = vec![
|
||||
("manager.log".into(), manager_log.to_path_buf()),
|
||||
("manager-install.log".into(), meta_dir.join("logs/manager.log")),
|
||||
("Server.log.tail".into(), root.join("Core/Logs/Server.log")),
|
||||
("Errors.log.tail".into(), root.join("Core/Logs/Errors.log")),
|
||||
("Auth.log.tail".into(), root.join("Core/Logs/Auth.log")),
|
||||
("world-console.log.tail".into(), root.join("Core/Logs/world-console.log")),
|
||||
("CoaBots.log.tail".into(), root.join("Core/Logs/CoaBots.log")),
|
||||
("Playerbots.log.tail".into(), root.join("Core/Logs/Playerbots.log")),
|
||||
("supervisor.log.tail".into(), root.join("Core/Logs/supervisor.log")),
|
||||
("mysql-error.log.tail".into(), root.join("mysql/logs/mysql-error.log")),
|
||||
];
|
||||
let updater_logs = newest_files(&root.join("Core/Logs"), "log", usize::MAX).into_iter().filter(|(p, _, _)| p.file_name().is_some_and(|f| f.to_string_lossy().to_lowercase().starts_with("update-")));
|
||||
for (p, _, _) in updater_logs.take(2) {
|
||||
logs.push((format!("{}.tail", p.file_name().unwrap_or_default().to_string_lossy()), p));
|
||||
}
|
||||
for (name, path) in logs {
|
||||
// A module that reads a missing setting on every tick fills a log with one warning, thousands of times; read far
|
||||
// enough back to see past that, fold the repeats, then keep the last part.
|
||||
let bytes = tail(&path, 8 * 1024 * 1024);
|
||||
@@ -214,9 +373,44 @@ pub fn export_package(root: &Path, meta_dir: &Path, manager_log: &Path, meta: &I
|
||||
let text = squash_repeated_config_warnings(&String::from_utf8_lossy(&bytes));
|
||||
let keep = text.len().saturating_sub(512 * 1024);
|
||||
let start = (keep..text.len()).find(|i| text.is_char_boundary(*i)).unwrap_or(text.len());
|
||||
add(name, redact(&text[start..]).as_bytes())?;
|
||||
add(&name, redact(&text[start..]).as_bytes())?;
|
||||
}
|
||||
}
|
||||
|
||||
// Crash reports of the server (text, and the small dumps next to them), and what Windows recorded for the programs.
|
||||
let crashes = root.join("Core/Crashes");
|
||||
let mut listing = String::new();
|
||||
for (p, len, _) in newest_files(&crashes, "txt", 10) {
|
||||
let name = p.file_name().unwrap_or_default().to_string_lossy().into_owned();
|
||||
listing.push_str(&format!("{name} ({len} bytes)\n"));
|
||||
let text = String::from_utf8_lossy(&tail(&p, 1024 * 1024)).into_owned();
|
||||
add(&format!("crashes/{name}"), redact(&text).as_bytes())?;
|
||||
}
|
||||
for (p, len, _) in newest_files(&crashes, "dmp", 3) {
|
||||
let name = p.file_name().unwrap_or_default().to_string_lossy().into_owned();
|
||||
if len > DUMP_FILE_MAX {
|
||||
listing.push_str(&format!("{name} ({len} bytes) not included: larger than {} MB\n", DUMP_FILE_MAX >> 20));
|
||||
} else if let Ok(bytes) = fs::read(&p) {
|
||||
listing.push_str(&format!("{name} ({len} bytes) included\n"));
|
||||
add(&format!("crashes/{name}"), &bytes)?;
|
||||
}
|
||||
}
|
||||
add("crashes.txt", if listing.is_empty() { "No crash reports in Core/Crashes.".to_string() } else { listing }.as_bytes())?;
|
||||
let events = windows_events();
|
||||
if !events.is_empty() { add("windows-events.txt", events.as_bytes())?; }
|
||||
add("processes.txt", processes_report(root, &ports).as_bytes())?;
|
||||
|
||||
// The newest update journals: the state of each update and the reason it failed.
|
||||
let mut journals: Vec<_> = fs::read_dir(meta_dir.join("updates")).into_iter().flatten().flatten()
|
||||
.filter(|e| e.file_type().is_ok_and(|t| t.is_dir()) && e.file_name().to_string_lossy().chars().all(|c| c.is_ascii_alphanumeric() || matches!(c, '-' | '_')))
|
||||
.collect();
|
||||
journals.sort_by_key(|e| std::cmp::Reverse(e.file_name()));
|
||||
for e in journals.into_iter().take(5) {
|
||||
if let Ok(text) = fs::read_to_string(e.path().join("txn.json")) {
|
||||
add(&format!("updates/{}-txn.json", e.file_name().to_string_lossy()), redact_json(&text).as_bytes())?;
|
||||
}
|
||||
}
|
||||
|
||||
// Which files the server's own configuration folders hold, and the two CoA switches that decide whether the game
|
||||
// client can talk to the world server at all.
|
||||
let mut present = String::new();
|
||||
@@ -244,18 +438,10 @@ pub fn export_package(root: &Path, meta_dir: &Path, manager_log: &Path, meta: &I
|
||||
}
|
||||
}
|
||||
if let Ok(b) = fs::read(root.join("RELEASE.json")) {
|
||||
add("RELEASE.json", redact(&String::from_utf8_lossy(&b)).as_bytes())?;
|
||||
add("RELEASE.json", redact_json(&String::from_utf8_lossy(&b)).as_bytes())?;
|
||||
}
|
||||
if let Ok(b) = fs::read(meta_dir.join("logs/database-checks.json")) {
|
||||
add("database-checks.json", redact(&String::from_utf8_lossy(&b)).as_bytes())?;
|
||||
}
|
||||
if let Ok(b) = fs::read(meta_dir.join("logs/update-result.json")) {
|
||||
add("update-result.json", redact(&String::from_utf8_lossy(&b)).as_bytes())?;
|
||||
}
|
||||
if let Ok(Some(txn)) = crate::update::latest(meta_dir) {
|
||||
if let Ok(b) = fs::read(meta_dir.join("updates").join(&txn.id).join("diagnostic.json")) {
|
||||
add("update-diagnostic.json", redact(&String::from_utf8_lossy(&b)).as_bytes())?;
|
||||
}
|
||||
add("database-checks.json", redact_json(&String::from_utf8_lossy(&b)).as_bytes())?;
|
||||
}
|
||||
zip.finish().map_err(|e| Error::Invalid(e.to_string()))?;
|
||||
Ok(n)
|
||||
@@ -297,6 +483,68 @@ real error
|
||||
assert!(!t.contains("PASS") && !t.contains("abc"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn json_redaction_keeps_the_file_valid_and_hides_the_secrets() {
|
||||
let t = redact_json(r#"{"id":"rev_20261006_token_cache","password":"hunter2","nested":{"apiKey":"k","note":"login with password=abc"},"list":[{"secret":1},"ok"]}"#);
|
||||
let v: serde_json::Value = serde_json::from_str(&t).expect("still JSON");
|
||||
assert_eq!(v["id"], "rev_20261006_token_cache", "an id that merely contains a word is kept");
|
||||
assert_eq!(v["password"], "[redacted]");
|
||||
assert_eq!(v["nested"]["apiKey"], "[redacted]");
|
||||
assert_eq!(v["nested"]["note"], "[redacted]");
|
||||
assert_eq!(v["list"][0]["secret"], "[redacted]");
|
||||
assert_eq!(v["list"][1], "ok");
|
||||
assert!(!t.contains("hunter2") && !t.contains("abc"));
|
||||
assert!(redact_json("not json\nPassword=1").contains("[line removed"), "text falls back to the line rule");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn windows_events_are_filtered_to_the_server_programs() {
|
||||
let listing = "Event[0]:\n Provider Name: Application Error\n Description: Faulting application name: worldserver.exe, version: 0.0.0.0\n\nEvent[1]:\n Provider Name: Application Error\n Description: Faulting application name: notepad.exe\n\nEvent[2]:\n Description: Faulting application name: MYSQLD.EXE\n";
|
||||
let out = filter_event_blocks(listing, &["worldserver", "mysqld"], 10);
|
||||
assert!(out.contains("worldserver.exe") && out.contains("MYSQLD.EXE") && !out.contains("notepad"));
|
||||
assert_eq!(filter_event_blocks(listing, &["worldserver", "mysqld"], 1).matches("Event[").count(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn event_text_loses_the_user_and_computer_lines_and_reads_utf16() {
|
||||
let out = drop_identity_lines("Event[0]\n Source: Application Error\n User: S-1-5-21-1\n User Name: PC\\Dion\n Computer: PC\n Description: worldserver.exe");
|
||||
assert!(out.contains("Source") && out.contains("worldserver.exe"));
|
||||
assert!(!out.contains("S-1-5") && !out.contains("Dion") && !out.contains("Computer"));
|
||||
let mut bytes = vec![0xFF, 0xFE];
|
||||
for u in "Сбой worldserver".encode_utf16() { bytes.extend_from_slice(&u.to_le_bytes()); }
|
||||
assert_eq!(decode_console_output(&bytes), "Сбой worldserver");
|
||||
assert_eq!(decode_console_output(b"plain"), "plain");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_package_carries_crash_reports_update_journals_and_the_process_view() {
|
||||
let d = tempfile::tempdir().unwrap();
|
||||
let root = d.path().join("srv");
|
||||
layout::testkit::fake_repack(&root);
|
||||
fs::create_dir_all(root.join("Core/Crashes")).unwrap();
|
||||
fs::write(root.join("Core/Crashes/567e_worldserver.exe_[4-10_21-25-31].txt"), "Exception code: C0000005\nRCX:0\n").unwrap();
|
||||
fs::write(root.join("Core/Crashes/567e_worldserver.exe_[4-10_21-25-31].dmp"), b"MDMP-small").unwrap();
|
||||
fs::write(root.join("Core/Logs/CoaBots.log"), "bot line\n").unwrap();
|
||||
fs::write(root.join("Core/Logs/update-1.8-20261005.log"), "updater line\n").unwrap();
|
||||
let meta_dir = d.path().join("srv.manager");
|
||||
fs::create_dir_all(meta_dir.join("updates/20261006-082021-0_261006_1-abc")).unwrap();
|
||||
fs::write(meta_dir.join("updates/20261006-082021-0_261006_1-abc/txn.json"), r#"{"state":"rolled-back","message":"Database update 2026_02_24_00 failed: duplicate column"}"#).unwrap();
|
||||
fs::create_dir_all(meta_dir.join("updates/not a journal!")).unwrap();
|
||||
let meta = InstallMeta::new(InstallKind::Imported, &root);
|
||||
let report = run(&root, &meta);
|
||||
let zip_path = d.path().join("diag.zip");
|
||||
export_package(&root, &meta_dir, &d.path().join("none.log"), &meta, &report, &zip_path).unwrap();
|
||||
let mut z = zip::ZipArchive::new(fs::File::open(&zip_path).unwrap()).unwrap();
|
||||
let names: Vec<String> = (0..z.len()).map(|i| z.by_index(i).unwrap().name().to_string()).collect();
|
||||
for want in ["crashes.txt", "processes.txt", "CoaBots.log.tail", "update-1.8-20261005.log.tail", "updates/20261006-082021-0_261006_1-abc-txn.json", "crashes/567e_worldserver.exe_[4-10_21-25-31].txt", "crashes/567e_worldserver.exe_[4-10_21-25-31].dmp"] {
|
||||
assert!(names.iter().any(|n| n == want), "{want} is in the package: {names:?}");
|
||||
}
|
||||
assert!(!names.iter().any(|n| n.contains("not a journal")));
|
||||
let mut listing = String::new();
|
||||
z.by_name("crashes.txt").unwrap().read_to_string(&mut listing).unwrap();
|
||||
assert!(listing.contains("included"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn verify_reports_missing_and_changed_managed_files_only() {
|
||||
let d = tempfile::tempdir().unwrap();
|
||||
|
||||
@@ -0,0 +1,574 @@
|
||||
//! Installing a new server as a Docker installation, from a Linux package.
|
||||
//!
|
||||
//! The order of events is the one of `install::install_base`: nothing appears at the destination until the package is
|
||||
//! signed-off, downloaded, verified, extracted and its database built, all of it in a sibling `<dest>.installing`
|
||||
//! folder. But this is code of its own: the Windows installer is not touched and nothing here is specific to the
|
||||
//! Windows layout. What both installers use is platform-neutral: the signed manifest, the download, the extraction,
|
||||
//! the migration ledger and the registry.
|
||||
//!
|
||||
//! The databases start from the package's own dumps (`Database/baseline/<kind>.sql.zst`, the format of the Manager's
|
||||
//! backups), as a Windows package starts from its prepared database: they hold the state in which every migration of the
|
||||
//! package is already applied, and the installer records them as such. They cannot be rebuilt from the repository's
|
||||
//! SQL files: some migrations are guards that only apply to the maintainers' own database. The game data is not part
|
||||
//! of the package: the person points at a folder they already have.
|
||||
|
||||
use std::fs;
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
use super::cli::{Docker, SystemDocker};
|
||||
use super::{Config, MARKER};
|
||||
use crate::db::{self, Account, Db};
|
||||
use crate::download::Cancel;
|
||||
use crate::driver::Verb;
|
||||
use crate::error::{Error, Result};
|
||||
use crate::fsx;
|
||||
use crate::install::{free_port, problem, random_hex, Installed, Preflight, Step};
|
||||
use crate::manifest::{self, Migration};
|
||||
use crate::migrations;
|
||||
use crate::package::BASELINE_DIR;
|
||||
use crate::pkgsource::{fetch_manifest, fetch_parts, Source};
|
||||
use crate::registry::{metadata_dir_for, InstallKind, InstallMeta, MetaDir, Registry, LAYOUT_DOCKER_V1};
|
||||
|
||||
/// Created in the staging folder so a leftover of an earlier attempt can be told from somebody else's folder.
|
||||
const STAGING_MARKER: &str = ".coa-installing";
|
||||
/// The three game databases: kind (the name of the dump), schema.
|
||||
const DATABASES: [(&str, &str); 3] = [("auth", "acore_auth"), ("characters", "acore_characters"), ("world", "acore_world")];
|
||||
/// Ports the game uses by default on this computer.
|
||||
const DEFAULT_PORTS: (u16, u16, u16) = (3724, 8085, 3443);
|
||||
|
||||
pub struct Params<'a> {
|
||||
pub source: Source,
|
||||
pub dest: PathBuf,
|
||||
/// A folder with the game data (dbc, maps, vmaps, mmaps) that the person already has. Used in place, read-only.
|
||||
pub data_dir: PathBuf,
|
||||
/// Public key to verify the manifest with (production: `signing::EMBEDDED_PUBLIC_KEY`).
|
||||
pub trusted_key: &'a str,
|
||||
pub registry: &'a Registry,
|
||||
pub cancel: Cancel,
|
||||
}
|
||||
|
||||
/// Checks whether `dest` and the game data folder are sensible for a new server on Linux.
|
||||
pub fn preflight(dest: &Path, data_dir: &Path, needed_bytes: u64, registry: &Registry) -> Preflight {
|
||||
let mut problems = Vec::new();
|
||||
let s = dest.to_string_lossy();
|
||||
|
||||
if !dest.is_absolute() {
|
||||
problems.push(problem("relative", "Choose a full folder path, such as /home/you/CoaServer."));
|
||||
}
|
||||
if s.contains(':') {
|
||||
problems.push(problem("colon", "Choose a folder whose path has no colon in it."));
|
||||
}
|
||||
let trimmed = s.trim_end_matches('/');
|
||||
const SYSTEM: [&str; 13] = ["", "/bin", "/boot", "/dev", "/etc", "/lib", "/lib64", "/proc", "/run", "/sbin", "/sys", "/usr", "/var"];
|
||||
if SYSTEM.iter().any(|p| trimmed == *p || (!p.is_empty() && trimmed.starts_with(&format!("{p}/")))) {
|
||||
problems.push(problem("system_folder", "Please choose a normal folder for your games, not a system location."));
|
||||
}
|
||||
if let Some(home) = std::env::var_os("HOME") {
|
||||
let home = home.to_string_lossy().trim_end_matches('/').to_string();
|
||||
let special = ["", "/Documents", "/Desktop", "/Downloads", "/Pictures", "/Music", "/Videos", "/.config", "/.local", "/.local/share"];
|
||||
if !home.is_empty() && special.iter().any(|sfx| trimmed == format!("{home}{sfx}")) {
|
||||
problems.push(problem("personal_folder", "This folder contains unrelated files. Choose another folder or create a new CoA Server folder."));
|
||||
}
|
||||
}
|
||||
|
||||
if dest.exists() {
|
||||
match fs::read_dir(dest) {
|
||||
Ok(mut rd) => {
|
||||
if rd.next().is_some() {
|
||||
match crate::layout::scan(dest).map(|r| r.classification) {
|
||||
Ok(crate::layout::Classification::Incompatible) | Err(_) => {
|
||||
if dest.join("Wow.exe").is_file() || dest.join("Ascension.exe").is_file() {
|
||||
problems.push(problem("client_folder", "This is a game client folder, not a place for a server."));
|
||||
} else {
|
||||
problems.push(problem("not_empty", "This folder contains unrelated files. Choose another folder or create a new CoA Server folder."));
|
||||
}
|
||||
}
|
||||
Ok(_) => problems.push(problem("already_server", "A server is already in this folder. Use \"I already have a server\" to add it instead.")),
|
||||
}
|
||||
}
|
||||
}
|
||||
Err(_) => problems.push(problem("unreadable", "This folder cannot be read. Choose another one.")),
|
||||
}
|
||||
}
|
||||
|
||||
if let Ok(list) = registry.list() {
|
||||
for (_, existing) in list {
|
||||
if let (Ok(a), Ok(b)) = (fsx::canonicalize_lenient(dest), fsx::canonicalize_lenient(&existing)) {
|
||||
if fsx::starts_with_ci(&a, &b) || fsx::starts_with_ci(&b, &a) {
|
||||
problems.push(problem("registered", "A server is already registered at or around this location."));
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
problems.extend(data_problems(data_dir));
|
||||
|
||||
let free_bytes = fsx::free_space(dest).unwrap_or(0);
|
||||
let need = needed_bytes.saturating_add(needed_bytes / 5).saturating_add(512 * 1024 * 1024);
|
||||
if free_bytes < need {
|
||||
problems.push(problem("space", &format!("Not enough free space: about {} GB needed, {} GB available.", need / (1 << 30) + 1, free_bytes / (1 << 30))));
|
||||
}
|
||||
Preflight { ok: problems.is_empty(), problems, free_bytes }
|
||||
}
|
||||
|
||||
fn data_problems(data_dir: &Path) -> Vec<crate::install::Problem> {
|
||||
let s = data_dir.to_string_lossy();
|
||||
if !data_dir.is_absolute() || s.contains(':') {
|
||||
return vec![problem("data_path", "Choose the game data folder with its full path, without a colon in it.")];
|
||||
}
|
||||
let missing: Vec<&str> = ["dbc", "maps"].into_iter().filter(|d| !data_dir.join(d).is_dir()).collect();
|
||||
if missing.is_empty() {
|
||||
Vec::new()
|
||||
} else {
|
||||
vec![problem("data_missing", &format!("This folder does not look like the game data: {} not found in it. It should hold dbc, maps, vmaps and mmaps.", missing.join(" and ")))]
|
||||
}
|
||||
}
|
||||
|
||||
/// Port the game should use: the usual one when it is free on this computer, else any free one.
|
||||
fn pick_port(preferred: u16) -> Result<u16> {
|
||||
if std::net::TcpListener::bind(("127.0.0.1", preferred)).is_ok() {
|
||||
Ok(preferred)
|
||||
} else {
|
||||
free_port()
|
||||
}
|
||||
}
|
||||
|
||||
/// Settings of a new installation: which containers belong to it, where the game data is, the ports, the passwords.
|
||||
/// Written before anything runs, so the database can be started from the staging folder.
|
||||
struct Settings {
|
||||
app_password: String,
|
||||
world_port: u16,
|
||||
}
|
||||
|
||||
fn write_settings(root: &Path, data_dir: &Path) -> Result<Settings> {
|
||||
let project = random_hex(10);
|
||||
let (auth, world, ra) = (pick_port(DEFAULT_PORTS.0)?, pick_port(DEFAULT_PORTS.1)?, pick_port(DEFAULT_PORTS.2)?);
|
||||
let (root_password, app_password) = (random_hex(48), random_hex(48));
|
||||
fs::create_dir_all(root.join("Settings"))?;
|
||||
let docker = Config { project, bind_address: "127.0.0.1".into(), mysql_image: super::MYSQL_IMAGE.into(), data_dir: Some(data_dir.to_string_lossy().into_owned()) };
|
||||
fsx::atomic_write_json(&root.join(MARKER), &docker)?;
|
||||
// Same file and keys as a repack, so the console, the ports and the settings screens work unchanged. The database is
|
||||
// not published on the host; its port is only there to fill the key.
|
||||
fsx::atomic_write_json(
|
||||
&root.join("Settings/repack.json"),
|
||||
&serde_json::json!({ "mysqlPort": 3307, "authPort": auth, "worldPort": world, "raPort": ra, "raUsername": db::SERVICE_ACCOUNT, "raPassword": "" }),
|
||||
)?;
|
||||
let secrets = root.join("Settings/database.json");
|
||||
fsx::atomic_write_json(&secrets, &serde_json::json!({ "rootPassword": root_password, "appPassword": app_password }))?;
|
||||
#[cfg(unix)]
|
||||
{
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
fs::set_permissions(&secrets, fs::Permissions::from_mode(0o600))?;
|
||||
}
|
||||
Ok(Settings { app_password, world_port: world })
|
||||
}
|
||||
|
||||
/// The package must hold what a Docker installation is made of; say what is missing instead of failing later.
|
||||
fn check_extracted(root: &Path) -> Result<()> {
|
||||
let mut missing = Vec::new();
|
||||
for rel in ["Core/worldserver", "Core/authserver", "Core/configs/worldserver.conf.dist", "Core/configs/authserver.conf.dist"] {
|
||||
if !root.join(rel).is_file() {
|
||||
missing.push(rel.to_string());
|
||||
}
|
||||
}
|
||||
for (kind, _) in DATABASES {
|
||||
if !root.join(BASELINE_DIR).join(format!("{kind}.sql.zst")).is_file() {
|
||||
missing.push(format!("{BASELINE_DIR}/{kind}.sql.zst"));
|
||||
}
|
||||
}
|
||||
if missing.is_empty() {
|
||||
Ok(())
|
||||
} else {
|
||||
Err(Error::Invalid(format!("This package is not a complete Linux server package; missing: {}.", missing.join(", "))))
|
||||
}
|
||||
}
|
||||
|
||||
/// Record every migration of the package as applied without running it, in a few statements (one `docker exec` for each
|
||||
/// of more than a thousand would take minutes). Same ledger rows as `migrations::baseline`.
|
||||
fn baseline_statements(list: &[Migration]) -> Result<Vec<String>> {
|
||||
let ok = |t: &str| !t.is_empty() && t.len() <= 190 && t.chars().all(|c| c.is_ascii_alphanumeric() || matches!(c, '_' | '.' | '-'));
|
||||
let mut rows = Vec::with_capacity(list.len());
|
||||
for m in list {
|
||||
if !matches!(m.db.as_str(), "auth" | "characters" | "world") || !ok(&m.id) || m.sha256.len() != 64 || !m.sha256.chars().all(|c| c.is_ascii_hexdigit()) {
|
||||
return Err(Error::InvalidManifest(format!("migration {:?} is not valid", m.id)));
|
||||
}
|
||||
rows.push(format!("('{}','{}','{}','applied',NOW(),NULL,1)", m.db, m.id, m.sha256));
|
||||
}
|
||||
Ok(rows
|
||||
.chunks(400)
|
||||
.map(|c| format!("REPLACE INTO `acore_world`.`coa_manager_migrations` (`db`,`id`,`sha256`,`status`,`applied_at`,`error`,`baseline`) VALUES {};", c.join(",")))
|
||||
.collect())
|
||||
}
|
||||
|
||||
/// Create the three schemas and the game servers' account, load the starting databases and record the package's migrations
|
||||
/// as applied. The database container is started from `root` and stopped again by the caller.
|
||||
fn build_database(d: &dyn Docker, root: &Path, list: &[Migration], s: &Settings, say: &dyn Fn(u8, String)) -> Result<()> {
|
||||
let started = super::run_with(d, root, Verb::StartMysql)?;
|
||||
if !started.ok {
|
||||
return Err(Error::Invalid(started.human.map(|h| h.message.to_string()).unwrap_or_else(|| "The database could not be started.".into())));
|
||||
}
|
||||
let db = Db::from_repack(root, Account::Admin)?;
|
||||
let mut sql = String::new();
|
||||
for (_, schema) in DATABASES {
|
||||
sql.push_str(&format!("CREATE DATABASE `{schema}` CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;\n"));
|
||||
}
|
||||
// The pattern also covers the schemas of other realms (acore_world_wildcard, ...).
|
||||
sql.push_str(&format!("CREATE USER 'acore'@'%' IDENTIFIED BY '{}';\nGRANT ALL PRIVILEGES ON `acore\\_%`.* TO 'acore'@'%';\nFLUSH PRIVILEGES;\n", s.app_password));
|
||||
db.query(&sql)?;
|
||||
|
||||
for (i, (kind, schema)) in DATABASES.iter().enumerate() {
|
||||
say(83 + (i * 4) as u8, format!("Loading the {kind} database"));
|
||||
db.import_from(schema, &root.join(BASELINE_DIR).join(format!("{kind}.sql.zst")))?;
|
||||
}
|
||||
|
||||
say(95 - 3, format!("Recording {} database updates as applied", list.len()));
|
||||
// The ledger table is created by the first read of it.
|
||||
migrations::Store::load(&db)?;
|
||||
for statement in baseline_statements(list)? {
|
||||
db.query(&statement)?;
|
||||
}
|
||||
|
||||
// The realm advertises the port the game server really uses on this computer.
|
||||
db.query(&format!("UPDATE acore_auth.realmlist SET port={} WHERE id=1;", s.world_port))?;
|
||||
// The server console gets its own account with a random password.
|
||||
let console_pw = db.provision_service_account()?;
|
||||
db::write_console_credentials(root, &console_pw)?;
|
||||
if !Db::from_repack(root, Account::Admin)?.ping() {
|
||||
return Err(Error::Invalid("The database did not answer after it was set up.".into()));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn install(p: &Params, report: &dyn Fn(Step)) -> Result<Installed> {
|
||||
install_with(&SystemDocker, p, report)
|
||||
}
|
||||
|
||||
pub fn install_with(d: &dyn Docker, p: &Params, report: &dyn Fn(Step)) -> Result<Installed> {
|
||||
let say = |step: &'static str, percent: u8, detail: Option<String>| report(Step { step, percent, detail });
|
||||
let dest = p.dest.clone();
|
||||
let staging_root = {
|
||||
let mut n = dest.file_name().ok_or_else(|| Error::Invalid("bad destination".into()))?.to_os_string();
|
||||
n.push(".installing");
|
||||
dest.with_file_name(n)
|
||||
};
|
||||
let meta_dir = metadata_dir_for(&dest)?;
|
||||
|
||||
say("Checking your computer", 2, None);
|
||||
super::check_docker(d)?;
|
||||
// The manifest first: it is signed, and tells us how much space we need.
|
||||
let (m, manifest_bytes) = fetch_manifest(&p.source, p.trusted_key)?;
|
||||
if !matches!(m.kind, manifest::Kind::Base | manifest::Kind::Update) || !m.compatible_with_manager(crate::MANAGER_VERSION) {
|
||||
return Err(Error::Invalid("This package needs a newer version of CoA Server Manager.".into()));
|
||||
}
|
||||
let archive = m.archive.clone().ok_or_else(|| Error::InvalidManifest("no archive".into()))?;
|
||||
let download_size: u64 = archive.parts.iter().map(|x| x.size).sum();
|
||||
|
||||
let pre = preflight(&dest, &p.data_dir, archive.unpacked_size + download_size, p.registry);
|
||||
if !pre.ok {
|
||||
return Err(Error::Invalid(pre.problems.iter().map(|x| x.message.clone()).collect::<Vec<_>>().join(" ")));
|
||||
}
|
||||
|
||||
let parts_dir = fetch_parts(&p.source, &m, &meta_dir.join("staging").join("download"), &p.cancel, &|frac, detail| say("Downloading server", 5 + (frac * 45.0) as u8, detail))?;
|
||||
|
||||
if staging_root.exists() {
|
||||
if staging_root.join(STAGING_MARKER).is_file() {
|
||||
fs::remove_dir_all(&staging_root)?; // leftover of an earlier failed attempt that we created
|
||||
} else {
|
||||
return Err(Error::Invalid(format!("{} already exists and was not created by the Manager.", staging_root.display())));
|
||||
}
|
||||
}
|
||||
fs::create_dir_all(&staging_root)?;
|
||||
fs::write(staging_root.join(STAGING_MARKER), b"")?;
|
||||
|
||||
let mut project: Option<Config> = None;
|
||||
let result = (|| -> Result<Installed> {
|
||||
say("Unpacking", 50, None);
|
||||
crate::package::extract(&parts_dir, &m, &staging_root, &|done, total| say("Unpacking", 50 + (done * 30 / total.max(1)) as u8, None))?;
|
||||
check_extracted(&staging_root)?;
|
||||
|
||||
say("Preparing database", 82, None);
|
||||
let settings = write_settings(&staging_root, &p.data_dir)?;
|
||||
project = Some(Config::load(&staging_root)?);
|
||||
let progress = |percent: u8, detail: String| say("Preparing database", percent, Some(detail));
|
||||
let built = build_database(d, &staging_root, &m.migrations, &settings, &progress);
|
||||
let _ = super::run_with(d, &staging_root, Verb::StopAll);
|
||||
built?;
|
||||
fs::remove_file(staging_root.join(STAGING_MARKER))?;
|
||||
|
||||
// Commit: the only moment the destination changes. The database lives in a docker volume, so it does not care
|
||||
// that the folder moves.
|
||||
say("Finishing", 95, None);
|
||||
if dest.exists() {
|
||||
fs::remove_dir(&dest)?; // only succeeds for an empty folder (preflight verified)
|
||||
}
|
||||
fs::rename(&staging_root, &dest)?;
|
||||
super::ensure_main_configs(&dest)?;
|
||||
crate::config::materialize_module_configs(&dest)?;
|
||||
|
||||
let mut meta = InstallMeta::new(InstallKind::New, &dest);
|
||||
meta.layout = LAYOUT_DOCKER_V1.into();
|
||||
meta.core.commit = m.core.commit.clone();
|
||||
meta.core.version = Some(m.version.clone());
|
||||
meta.database.schemas = DATABASES.iter().map(|(_, s)| s.to_string()).collect();
|
||||
meta.managed_files = m.files.iter().map(|f| f.path.clone()).collect();
|
||||
for f in &m.files {
|
||||
meta.original_hashes.insert(f.path.clone(), f.sha256.clone());
|
||||
}
|
||||
let md = MetaDir::create(&dest, &meta)?;
|
||||
fsx::atomic_write(&md.root.join("manifests").join("base.json"), &manifest_bytes)?;
|
||||
p.registry.register(&meta.id, &dest)?;
|
||||
say("Ready", 100, None);
|
||||
Ok(Installed { id: meta.id, path: dest.to_string_lossy().into_owned(), version: m.version.clone() })
|
||||
})();
|
||||
|
||||
if result.is_err() && staging_root.join(STAGING_MARKER).exists() {
|
||||
// Unfinished work of ours; the destination was never touched. Give back what docker holds for it.
|
||||
if let Some(cfg) = &project {
|
||||
super::destroy(d, cfg);
|
||||
}
|
||||
let _ = fs::remove_dir_all(&staging_root);
|
||||
}
|
||||
result
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::docker::cli::{Call, Output};
|
||||
use crate::package::{self, BuildOptions};
|
||||
use base64::Engine;
|
||||
use ed25519_dalek::{Signer, SigningKey};
|
||||
use std::cell::RefCell;
|
||||
|
||||
struct Fake {
|
||||
calls: RefCell<Vec<Vec<String>>>,
|
||||
unavailable: bool,
|
||||
}
|
||||
|
||||
impl Fake {
|
||||
fn new(unavailable: bool) -> Fake {
|
||||
Fake { calls: Default::default(), unavailable }
|
||||
}
|
||||
}
|
||||
|
||||
impl Docker for Fake {
|
||||
fn run(&self, call: &Call) -> Result<Output> {
|
||||
self.calls.borrow_mut().push(call.args.clone());
|
||||
if self.unavailable {
|
||||
return Err(Error::Invalid("docker could not be started: not found".into()));
|
||||
}
|
||||
Ok(Output { code: Some(0), stdout: "27.3.1".into(), stderr: String::new() })
|
||||
}
|
||||
|
||||
fn pause(&self, _d: std::time::Duration) {}
|
||||
}
|
||||
|
||||
fn reg(d: &Path) -> Registry {
|
||||
Registry::at(d.join("reg/installs.json"))
|
||||
}
|
||||
|
||||
fn codes(p: &Preflight) -> Vec<&'static str> {
|
||||
p.problems.iter().map(|x| x.code).collect()
|
||||
}
|
||||
|
||||
fn data_folder(d: &Path) -> PathBuf {
|
||||
let data = d.join("data");
|
||||
fs::create_dir_all(data.join("dbc")).unwrap();
|
||||
fs::create_dir_all(data.join("maps")).unwrap();
|
||||
data
|
||||
}
|
||||
|
||||
/// A signed package folder holding `files`, and the key that verifies it.
|
||||
fn signed_package(d: &Path, files: &[(&str, &str)]) -> (PathBuf, String) {
|
||||
let src = d.join("src");
|
||||
for (rel, content) in files {
|
||||
let p = src.join(rel);
|
||||
fs::create_dir_all(p.parent().unwrap()).unwrap();
|
||||
fs::write(p, content).unwrap();
|
||||
}
|
||||
let pkg = d.join("pkg");
|
||||
let opts = BuildOptions { kind: manifest::Kind::Update, version: "0.1.0".into(), core_commit: None, built_at: "x".into(), part_size: 1 << 20, bots_commit: None, migrations: vec![] };
|
||||
package::build(&src, &pkg, &opts, &|_| {}).unwrap();
|
||||
let key = SigningKey::generate(&mut rand_core::OsRng);
|
||||
let engine = base64::engine::general_purpose::STANDARD;
|
||||
let sig = engine.encode(key.sign(&fs::read(pkg.join("manifest.json")).unwrap()).to_bytes());
|
||||
fs::write(pkg.join("manifest.json.sig"), sig).unwrap();
|
||||
(pkg, engine.encode(key.verifying_key().to_bytes()))
|
||||
}
|
||||
|
||||
const FULL: [(&str, &str); 7] = [
|
||||
("Core/worldserver", "w"),
|
||||
("Core/authserver", "a"),
|
||||
("Core/configs/worldserver.conf.dist", "x"),
|
||||
("Core/configs/authserver.conf.dist", "x"),
|
||||
("Database/baseline/auth.sql.zst", "dump"),
|
||||
("Database/baseline/characters.sql.zst", "dump"),
|
||||
("Database/baseline/world.sql.zst", "dump"),
|
||||
];
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn the_destination_rules_fit_a_linux_computer() {
|
||||
let d = tempfile::tempdir().unwrap();
|
||||
let data = data_folder(d.path());
|
||||
let ok = |dest: &Path| codes(&preflight(dest, &data, 1000, ®(d.path())));
|
||||
assert!(!ok(&d.path().join("CoaServer")).iter().any(|c| *c != "space"), "a new folder is fine");
|
||||
for bad in ["/usr/local/coa", "/etc", "/", "/proc/x"] {
|
||||
assert!(ok(Path::new(bad)).contains(&"system_folder"), "{bad}");
|
||||
}
|
||||
assert!(ok(Path::new("relative/dir")).contains(&"relative"));
|
||||
assert!(ok(Path::new("/srv/with:colon")).contains(&"colon"));
|
||||
let existing = d.path().join("existing");
|
||||
fs::create_dir_all(&existing).unwrap();
|
||||
fs::write(existing.join("notes.txt"), b"x").unwrap();
|
||||
assert!(ok(&existing).contains(&"not_empty"));
|
||||
let r = reg(d.path());
|
||||
r.register("1", &existing).unwrap();
|
||||
assert!(codes(&preflight(&existing.join("inner"), &data, 1000, &r)).contains(&"registered"));
|
||||
// The same name in another case is another folder on Linux.
|
||||
assert!(!codes(&preflight(&d.path().join("EXISTING"), &data, 1000, &r)).contains(&"registered"));
|
||||
}
|
||||
|
||||
// The tests marked for unix use absolute folders of the temporary directory, which on Windows start with a drive letter and a
|
||||
// colon; the Docker backend refuses a colon in a folder it mounts (it would be read as a separator of `--volume`) and only runs
|
||||
// on Linux, so Windows has nothing to check here.
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn the_game_data_folder_must_look_like_game_data() {
|
||||
let d = tempfile::tempdir().unwrap();
|
||||
let reg = reg(d.path());
|
||||
let dest = d.path().join("srv");
|
||||
let empty = d.path().join("empty");
|
||||
fs::create_dir_all(&empty).unwrap();
|
||||
assert!(codes(&preflight(&dest, &empty, 1, ®)).contains(&"data_missing"));
|
||||
assert!(codes(&preflight(&dest, Path::new("relative/data"), 1, ®)).contains(&"data_path"));
|
||||
assert!(!codes(&preflight(&dest, &data_folder(d.path()), 1, ®)).iter().any(|c| c.starts_with("data")));
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn new_settings_name_the_containers_and_keep_the_secrets_private() {
|
||||
let d = tempfile::tempdir().unwrap();
|
||||
let root = d.path().join("srv");
|
||||
let data = data_folder(d.path());
|
||||
let s = write_settings(&root, &data).unwrap();
|
||||
|
||||
let cfg = Config::load(&root).unwrap();
|
||||
assert_eq!(cfg.bind_address, "127.0.0.1", "this computer only until the person opens it");
|
||||
assert_eq!(cfg.project.len(), 10);
|
||||
assert_eq!(cfg.data_path(&root), data);
|
||||
|
||||
let ports = crate::layout::read_ports(&root);
|
||||
assert_eq!(ports.world, s.world_port);
|
||||
assert!(ports.auth > 0 && ports.ra > 0);
|
||||
let repack: serde_json::Value = fsx::read_json(&root.join("Settings/repack.json")).unwrap();
|
||||
assert_eq!(repack["raUsername"], db::SERVICE_ACCOUNT);
|
||||
|
||||
let (root_pw, app_pw) = db::credentials(&root).unwrap();
|
||||
assert!(root_pw.len() == 48 && app_pw.len() == 48 && root_pw != app_pw);
|
||||
assert_eq!(app_pw, s.app_password);
|
||||
#[cfg(unix)]
|
||||
{
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
let mode = fs::metadata(root.join("Settings/database.json")).unwrap().permissions().mode() & 0o777;
|
||||
assert_eq!(mode, 0o600, "the passwords are for their owner only");
|
||||
}
|
||||
// Two installations never share a project name.
|
||||
let other = write_settings(&d.path().join("srv2"), &data).unwrap();
|
||||
assert_ne!(Config::load(&d.path().join("srv2")).unwrap().project, cfg.project);
|
||||
let _ = other;
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_busy_default_port_is_replaced_by_a_free_one() {
|
||||
let held = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
|
||||
let busy = held.local_addr().unwrap().port();
|
||||
let got = pick_port(busy).unwrap();
|
||||
assert_ne!(got, busy);
|
||||
drop(held);
|
||||
assert_eq!(pick_port(busy).unwrap(), busy, "free again: the usual port is used");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_package_is_checked_for_everything_an_installation_needs() {
|
||||
let d = tempfile::tempdir().unwrap();
|
||||
let root = d.path();
|
||||
assert!(check_extracted(root).unwrap_err().to_string().contains("Core/worldserver"));
|
||||
for (rel, c) in FULL {
|
||||
let p = root.join(rel);
|
||||
fs::create_dir_all(p.parent().unwrap()).unwrap();
|
||||
fs::write(p, c).unwrap();
|
||||
}
|
||||
check_extracted(root).unwrap();
|
||||
fs::remove_file(root.join("Database/baseline/world.sql.zst")).unwrap();
|
||||
assert!(check_extracted(root).unwrap_err().to_string().contains("Database/baseline/world.sql.zst"));
|
||||
}
|
||||
|
||||
fn migration(db: &str, id: &str) -> Migration {
|
||||
Migration { db: db.into(), id: id.into(), sha256: "ab".repeat(32), destructive: false, compatible_sha256: vec![] }
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_package_migrations_are_recorded_as_applied_in_a_few_statements() {
|
||||
let list: Vec<Migration> = (0..1000).map(|i| migration(["auth", "characters", "world"][i % 3], &format!("rev_{i}"))).collect();
|
||||
let statements = baseline_statements(&list).unwrap();
|
||||
assert_eq!(statements.len(), 3, "400 rows at most in a statement");
|
||||
assert!(statements[0].starts_with("REPLACE INTO `acore_world`.`coa_manager_migrations`"));
|
||||
assert_eq!(statements.iter().map(|s| s.matches("'applied'").count()).sum::<usize>(), 1000);
|
||||
assert!(statements[0].contains("('auth','rev_0',") && statements[0].contains(",NOW(),NULL,1)"), "marked as a baseline");
|
||||
assert!(baseline_statements(&[]).unwrap().is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_migration_that_could_carry_sql_is_refused_before_anything_is_written() {
|
||||
for bad in [migration("world", "x'); DROP TABLE y;--"), migration("mysql", "ok"), migration("world", ""), Migration { sha256: "zz".into(), ..migration("world", "ok") }] {
|
||||
assert!(baseline_statements(&[migration("auth", "fine"), bad]).is_err());
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn without_docker_nothing_is_downloaded_or_created() {
|
||||
let d = tempfile::tempdir().unwrap();
|
||||
let (pkg, key) = signed_package(d.path(), &FULL);
|
||||
let dest = d.path().join("dest");
|
||||
let r = reg(d.path());
|
||||
let fake = Fake::new(true);
|
||||
let err = install_with(&fake, &Params { source: Source::Dir(pkg), dest: dest.clone(), data_dir: data_folder(d.path()), trusted_key: &key, registry: &r, cancel: Cancel::default() }, &|_| {}).unwrap_err();
|
||||
assert!(err.to_string().to_lowercase().contains("docker"), "{err}");
|
||||
assert!(!dest.exists() && !dest.with_file_name("dest.installing").exists());
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn a_package_without_the_server_is_refused_and_leaves_nothing() {
|
||||
let d = tempfile::tempdir().unwrap();
|
||||
let (pkg, key) = signed_package(d.path(), &[("Core/configs/worldserver.conf.dist", "x"), ("README.txt", "hello")]);
|
||||
let dest = d.path().join("dest");
|
||||
let r = reg(d.path());
|
||||
let fake = Fake::new(false);
|
||||
let err = install_with(&fake, &Params { source: Source::Dir(pkg), dest: dest.clone(), data_dir: data_folder(d.path()), trusted_key: &key, registry: &r, cancel: Cancel::default() }, &|_| {}).unwrap_err();
|
||||
assert!(err.to_string().contains("not a complete Linux server package"), "{err}");
|
||||
assert!(!dest.exists() && !dest.with_file_name("dest.installing").exists());
|
||||
assert!(r.list().unwrap().is_empty());
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn a_failed_database_setup_gives_back_what_docker_holds_and_leaves_no_server() {
|
||||
let d = tempfile::tempdir().unwrap();
|
||||
let (pkg, key) = signed_package(d.path(), &FULL);
|
||||
let dest = d.path().join("dest");
|
||||
let r = reg(d.path());
|
||||
// This fake docker answers every command with success and no container, so the database never becomes ready.
|
||||
let fake = Fake::new(false);
|
||||
let err = install_with(&fake, &Params { source: Source::Dir(pkg), dest: dest.clone(), data_dir: data_folder(d.path()), trusted_key: &key, registry: &r, cancel: Cancel::default() }, &|_| {}).unwrap_err();
|
||||
assert!(err.to_string().to_lowercase().contains("database"), "{err}");
|
||||
assert!(!dest.exists() && !dest.with_file_name("dest.installing").exists(), "no half-installed server");
|
||||
assert!(r.list().unwrap().is_empty());
|
||||
let calls = fake.calls.borrow();
|
||||
let removed = |suffix: &str| calls.iter().any(|c| c[0] == "rm" && c.last().is_some_and(|n| n.starts_with("coa-") && n.ends_with(suffix)));
|
||||
assert!(removed("-db") && removed("-world") && removed("-auth"), "containers removed: {calls:?}");
|
||||
assert!(calls.iter().any(|c| c[..2] == ["volume", "rm"]) && calls.iter().any(|c| c[..2] == ["network", "rm"]));
|
||||
}
|
||||
}
|
||||
@@ -80,6 +80,26 @@ fn docker(d: &dyn Docker, args: &[&str], timeout: Duration) -> Step<super::cli::
|
||||
d.run(&Call::new(args, timeout)).or_else(|e| fail(ErrorCode::DockerUnavailable, e.to_string()))
|
||||
}
|
||||
|
||||
/// Is docker usable by this user? Returns its version, or the reason in docker's own words.
|
||||
pub fn check_docker(d: &dyn Docker) -> Result<String> {
|
||||
let mut log = Log::default();
|
||||
match preflight(d, &mut log) {
|
||||
Ok(()) => Ok(log.0.join(" ")),
|
||||
Err(f) => Err(crate::error::Error::Invalid(format!("{} {}", f.code.human().message, f.output.trim()).trim().to_string())),
|
||||
}
|
||||
}
|
||||
|
||||
/// Remove everything docker holds for an installation: containers, network and the database volume. Used when an
|
||||
/// installation fails before it is finished, and later to uninstall. Missing pieces are not an error.
|
||||
pub(crate) fn destroy(d: &dyn Docker, cfg: &Config) {
|
||||
let n = cfg.names();
|
||||
for name in [&n.auth, &n.world, &n.db] {
|
||||
let _ = d.run(&Call::new(&["rm", "--force", name], QUICK));
|
||||
}
|
||||
let _ = d.run(&Call::new(&["network", "rm", &n.network], QUICK));
|
||||
let _ = d.run(&Call::new(&["volume", "rm", &n.volume], QUICK));
|
||||
}
|
||||
|
||||
fn preflight(d: &dyn Docker, log: &mut Log) -> Step<()> {
|
||||
let o = docker(d, &["version", "--format", "{{.Server.Version}}"], QUICK)?;
|
||||
if !o.ok() {
|
||||
@@ -204,6 +224,7 @@ fn start(d: &dyn Docker, root: &Path, cfg: &Config, with_game: bool, log: &mut L
|
||||
}
|
||||
|
||||
ensure_image(d, log)?;
|
||||
super::ensure_main_configs(root).map_err(|e| Failure { code: ErrorCode::ServerFilesIncomplete, output: e.to_string() })?;
|
||||
std::fs::create_dir_all(root.join("Core/Logs")).map_err(|e| Failure { code: ErrorCode::ServerFilesIncomplete, output: e.to_string() })?;
|
||||
let owner = owner_of(root);
|
||||
let host = std::fs::canonicalize(root).unwrap_or_else(|_| root.to_path_buf());
|
||||
@@ -212,7 +233,7 @@ fn start(d: &dyn Docker, root: &Path, cfg: &Config, with_game: bool, log: &mut L
|
||||
if !state.get(&n.world).is_some_and(Container::running) {
|
||||
remove(d, &n.world);
|
||||
let mut call = Call::new(&[], Duration::from_secs(60));
|
||||
call.args = game_args(cfg, &n, GameKind::World, &host, ports.world, ports.ra, owner.as_deref());
|
||||
call.args = game_args(cfg, &n, GameKind::World, &host, &cfg.data_path(&host), ports.world, ports.ra, owner.as_deref());
|
||||
call.env = database_env(&secrets, true);
|
||||
run_container(d, &call, &n.world, log)?;
|
||||
}
|
||||
@@ -221,7 +242,7 @@ fn start(d: &dyn Docker, root: &Path, cfg: &Config, with_game: bool, log: &mut L
|
||||
if !state.get(&n.auth).is_some_and(Container::running) {
|
||||
remove(d, &n.auth);
|
||||
let mut call = Call::new(&[], Duration::from_secs(60));
|
||||
call.args = game_args(cfg, &n, GameKind::Auth, &host, ports.auth, 0, owner.as_deref());
|
||||
call.args = game_args(cfg, &n, GameKind::Auth, &host, &cfg.data_path(&host), ports.auth, 0, owner.as_deref());
|
||||
call.env = database_env(&secrets, false);
|
||||
run_container(d, &call, &n.auth, log)?;
|
||||
}
|
||||
@@ -320,8 +341,11 @@ fn db_args(cfg: &Config, n: &Names) -> Vec<String> {
|
||||
a.extend(["--volume".into(), format!("{}:/var/lib/mysql", n.volume)]);
|
||||
// The password comes from the environment of the docker client, not from this command line.
|
||||
a.extend(["--env".into(), "MYSQL_ROOT_PASSWORD".into()]);
|
||||
// "mysqladmin ping" succeeds as soon as the server answers, with or without a login.
|
||||
a.extend(["--health-cmd".into(), "mysqladmin ping --silent".into()]);
|
||||
// "mysqladmin ping" succeeds as soon as the server answers, with or without a login. It must go over TCP, like
|
||||
// everything the Manager sends: while a new database initialises, the image first runs a temporary server that
|
||||
// answers on its socket but takes no network connection, and a socket ping would call the container healthy for a few
|
||||
// seconds in which every TCP connection is still refused.
|
||||
a.extend(["--health-cmd".into(), "mysqladmin ping --protocol=tcp --host=127.0.0.1 --silent".into()]);
|
||||
a.extend(["--health-interval".into(), "5s".into(), "--health-timeout".into(), "5s".into(), "--health-retries".into(), "40".into()]);
|
||||
a.extend(["--stop-timeout".into(), "60".into()]);
|
||||
a.push(cfg.mysql_image.clone());
|
||||
@@ -345,7 +369,7 @@ fn database_env(s: &Secrets, world: bool) -> Vec<(String, String)> {
|
||||
env
|
||||
}
|
||||
|
||||
fn game_args(cfg: &Config, n: &Names, kind: GameKind, host: &Path, port: u16, ra_port: u16, owner: Option<&str>) -> Vec<String> {
|
||||
fn game_args(cfg: &Config, n: &Names, kind: GameKind, host: &Path, data: &Path, port: u16, ra_port: u16, owner: Option<&str>) -> Vec<String> {
|
||||
let (name, alias, binary, conf, inner_port) = match kind {
|
||||
GameKind::World => (&n.world, "world", "./worldserver", "configs/worldserver.conf", WORLD_PORT),
|
||||
GameKind::Auth => (&n.auth, "auth", "./authserver", "configs/authserver.conf", AUTH_PORT),
|
||||
@@ -370,7 +394,7 @@ fn game_args(cfg: &Config, n: &Names, kind: GameKind, host: &Path, port: u16, ra
|
||||
// the container and stops the server when it cannot find one.
|
||||
a.extend(env("AC_UPDATES_ENABLE_DATABASES", "0"));
|
||||
if kind == GameKind::World {
|
||||
a.extend(["--volume".into(), format!("{}:{DATA}:ro", host.join("Data").display())]);
|
||||
a.extend(["--volume".into(), format!("{}:{DATA}:ro", data.display())]);
|
||||
a.extend(env("AC_DATA_DIR", DATA));
|
||||
// The remote console is only ever reachable from this computer.
|
||||
a.extend(["--publish".into(), format!("127.0.0.1:{ra_port}:{RA_PORT}")]);
|
||||
@@ -674,6 +698,17 @@ mod tests {
|
||||
assert!(runs[1].args.windows(2).any(|w| w == ["--env", "AC_WORLD_DATABASE_INFO"]), "name only, the value is in the environment");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_database_is_only_healthy_once_it_takes_tcp_connections() {
|
||||
let (_d, root) = server("t1");
|
||||
let sim = Sim::new();
|
||||
assert!(start_all(&sim, &root).ok);
|
||||
let db = &sim.calls_of("run")[0].args;
|
||||
let i = db.iter().position(|a| a == "--health-cmd").expect("the database has a health check");
|
||||
// Found on a new volume: a socket-only ping reported healthy about four seconds before TCP worked.
|
||||
assert!(db[i + 1].contains("--protocol=tcp") && db[i + 1].contains("--host=127.0.0.1"), "{}", db[i + 1]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_world_container_is_wired_like_the_repack_layout() {
|
||||
let (_d, root) = server("t1");
|
||||
@@ -714,8 +749,8 @@ mod tests {
|
||||
let (_d, root) = server("ports");
|
||||
let cfg = Config::load(&root).unwrap();
|
||||
let n = cfg.names();
|
||||
let world = game_args(&cfg, &n, GameKind::World, &root, 18085, 13443, None);
|
||||
let auth = game_args(&cfg, &n, GameKind::Auth, &root, 13724, 0, None);
|
||||
let world = game_args(&cfg, &n, GameKind::World, &root, &root.join("Data"), 18085, 13443, None);
|
||||
let auth = game_args(&cfg, &n, GameKind::Auth, &root, &root.join("Data"), 13724, 0, None);
|
||||
assert!(world.iter().any(|a| a == "127.0.0.1:18085:8085"));
|
||||
assert!(world.iter().any(|a| a == "127.0.0.1:13443:3443"));
|
||||
assert!(world.iter().any(|a| a == "AC_WORLD_SERVER_PORT=8085"));
|
||||
|
||||
@@ -15,10 +15,12 @@
|
||||
//! ```
|
||||
|
||||
mod cli;
|
||||
pub mod install;
|
||||
mod lifecycle;
|
||||
|
||||
pub use cli::{Call, Docker, Output, SystemDocker};
|
||||
pub use lifecycle::{observe, observe_with, run, run_with};
|
||||
pub use lifecycle::{check_docker, observe, observe_with, run, run_with};
|
||||
pub(crate) use lifecycle::destroy;
|
||||
|
||||
use std::net::IpAddr;
|
||||
use std::path::Path;
|
||||
@@ -31,7 +33,7 @@ use crate::layout::{self, Classification, ScanReport};
|
||||
|
||||
/// Present in a Docker installation, absent from a repack.
|
||||
pub const MARKER: &str = "Settings/docker.json";
|
||||
const MYSQL_IMAGE: &str = "mysql:8.4";
|
||||
pub(crate) const MYSQL_IMAGE: &str = "mysql:8.4";
|
||||
const RUNTIME_DOCKERFILE: &str = include_str!("Dockerfile.runtime");
|
||||
|
||||
pub fn is_docker(root: &Path) -> bool {
|
||||
@@ -57,6 +59,10 @@ pub struct Config {
|
||||
pub bind_address: String,
|
||||
#[serde(default = "mysql_image")]
|
||||
pub mysql_image: String,
|
||||
/// Where the game data (dbc, maps, vmaps, mmaps) is, when it is not the `Data` folder of the server. Used in place and
|
||||
/// mounted read-only, so one copy can serve several servers.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub data_dir: Option<String>,
|
||||
}
|
||||
|
||||
pub(crate) struct Names {
|
||||
@@ -74,6 +80,11 @@ impl Config {
|
||||
Ok(cfg)
|
||||
}
|
||||
|
||||
/// The folder mounted as the game data.
|
||||
pub fn data_path(&self, root: &Path) -> std::path::PathBuf {
|
||||
self.data_dir.as_deref().map(std::path::PathBuf::from).unwrap_or_else(|| root.join("Data"))
|
||||
}
|
||||
|
||||
fn validate(&self) -> Result<()> {
|
||||
let name_ok = !self.project.is_empty()
|
||||
&& self.project.len() <= 32
|
||||
@@ -85,6 +96,12 @@ impl Config {
|
||||
if self.bind_address.parse::<IpAddr>().is_err() {
|
||||
return Err(Error::Invalid(format!("{} is not an IP address.", self.bind_address)));
|
||||
}
|
||||
if let Some(d) = &self.data_dir {
|
||||
// The folder goes into a `--volume host:container:ro` option, where a colon would be read as a separator.
|
||||
if !Path::new(d).is_absolute() || d.contains(':') {
|
||||
return Err(Error::Invalid("The game data folder must be a full path without a colon.".into()));
|
||||
}
|
||||
}
|
||||
let image_ok = !self.mysql_image.is_empty() && self.mysql_image.chars().all(|c| c.is_ascii_alphanumeric() || "._/:@-".contains(c));
|
||||
if !image_ok {
|
||||
return Err(Error::Invalid("The database image name is not valid.".into()));
|
||||
@@ -103,6 +120,21 @@ impl Config {
|
||||
}
|
||||
}
|
||||
|
||||
/// Create the world and auth configuration files from their `.dist` templates when they do not exist. A package only
|
||||
/// carries the templates, and on Windows the launcher writes the active files at every start; here nothing else would.
|
||||
/// An existing file is never touched, so the person's settings survive updates. Returns the files created.
|
||||
pub fn ensure_main_configs(root: &Path) -> Result<Vec<String>> {
|
||||
let mut created = Vec::new();
|
||||
for name in ["worldserver", "authserver"] {
|
||||
let (conf, dist) = (root.join(format!("Core/configs/{name}.conf")), root.join(format!("Core/configs/{name}.conf.dist")));
|
||||
if !conf.exists() && dist.is_file() {
|
||||
std::fs::copy(&dist, &conf)?;
|
||||
created.push(format!("{name}.conf"));
|
||||
}
|
||||
}
|
||||
Ok(created)
|
||||
}
|
||||
|
||||
/// Name of the runtime image: it follows the content of its Dockerfile, so changing the libraries builds a new image.
|
||||
pub(crate) fn runtime_image() -> String {
|
||||
format!("coa-runtime:{}", &fsx::sha256_bytes(RUNTIME_DOCKERFILE.as_bytes())[..12])
|
||||
@@ -123,7 +155,8 @@ pub(crate) fn scan(root: &Path) -> Result<ScanReport> {
|
||||
let bot_active = modules_dir.join("mod_coa_playerbots.conf");
|
||||
let bot_conf = if bot_active.is_file() { bot_active } else { modules_dir.join("mod_coa_playerbots.conf.dist") };
|
||||
let bot_config_keys = layout::count_bot_keys(&bot_conf);
|
||||
let has_data = layout::exists(root, "Data/dbc") && layout::exists(root, "Data/maps");
|
||||
let data = cfg.as_ref().map(|c| c.data_path(root)).unwrap_or_else(|_| root.join("Data"));
|
||||
let has_data = data.join("dbc").is_dir() && data.join("maps").is_dir();
|
||||
let has_confs = layout::exists(root, "Core/configs/worldserver.conf") && layout::exists(root, "Core/configs/authserver.conf");
|
||||
|
||||
let items = vec![
|
||||
@@ -162,3 +195,30 @@ pub(crate) fn scan(root: &Path) -> Result<ScanReport> {
|
||||
})
|
||||
}
|
||||
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use std::fs;
|
||||
|
||||
#[test]
|
||||
fn the_main_configs_are_created_from_their_templates_and_never_overwritten() {
|
||||
let d = tempfile::tempdir().unwrap();
|
||||
let cfg = d.path().join("Core/configs");
|
||||
fs::create_dir_all(&cfg).unwrap();
|
||||
fs::write(cfg.join("worldserver.conf.dist"), "Setting = default\n").unwrap();
|
||||
fs::write(cfg.join("authserver.conf.dist"), "Auth = default\n").unwrap();
|
||||
|
||||
assert_eq!(ensure_main_configs(d.path()).unwrap(), ["worldserver.conf", "authserver.conf"]);
|
||||
assert_eq!(fs::read_to_string(cfg.join("worldserver.conf")).unwrap(), "Setting = default\n");
|
||||
|
||||
// The person's own settings survive the next start.
|
||||
fs::write(cfg.join("worldserver.conf"), "Setting = mine\n").unwrap();
|
||||
assert!(ensure_main_configs(d.path()).unwrap().is_empty());
|
||||
assert_eq!(fs::read_to_string(cfg.join("worldserver.conf")).unwrap(), "Setting = mine\n");
|
||||
// Without a template there is nothing to create and nothing fails.
|
||||
fs::remove_file(cfg.join("authserver.conf")).unwrap();
|
||||
fs::remove_file(cfg.join("authserver.conf.dist")).unwrap();
|
||||
assert!(ensure_main_configs(d.path()).unwrap().is_empty());
|
||||
}
|
||||
}
|
||||
@@ -31,8 +31,9 @@ impl Verb {
|
||||
}
|
||||
}
|
||||
|
||||
fn timeout(self) -> Duration {
|
||||
fn timeout(self, root: &Path) -> Duration {
|
||||
match self {
|
||||
Verb::StartAll | Verb::StartWorld if squid_enabled(root) => Duration::from_secs(2700),
|
||||
Verb::StartAll | Verb::StartWorld => Duration::from_secs(420),
|
||||
Verb::StartMysql => Duration::from_secs(120),
|
||||
Verb::StopAll => Duration::from_secs(240),
|
||||
@@ -40,6 +41,14 @@ impl Verb {
|
||||
}
|
||||
}
|
||||
|
||||
fn squid_enabled(root: &Path) -> bool {
|
||||
let active = root.join("Core/configs/modules/playerbots.conf");
|
||||
let path = if active.exists() { active } else { root.join("Core/configs/modules/playerbots.conf.dist") };
|
||||
std::fs::read(path).ok().and_then(|bytes| crate::config::parser::ConfFile::parse_bytes(&bytes).ok())
|
||||
.is_some_and(|config| config.get("AiPlayerbot.Enabled").is_none_or(|value|
|
||||
!matches!(value.trim().trim_matches('"').to_ascii_lowercase().as_str(), "0" | "false" | "no" | "off")))
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize)]
|
||||
pub struct DriverOutcome {
|
||||
pub ok: bool,
|
||||
@@ -81,41 +90,20 @@ fn launcher(root: &Path) -> Result<(PathBuf, PathBuf)> {
|
||||
|
||||
/// Run a launcher verb to completion (blocking; call from a worker thread).
|
||||
pub fn run(root: &Path, verb: Verb) -> Result<DriverOutcome> {
|
||||
run_inner(root, verb, false, false)
|
||||
run_inner(root, verb, false)
|
||||
}
|
||||
|
||||
pub(crate) fn validate_update(root: &Path) -> Result<DriverOutcome> {
|
||||
run_inner(root, Verb::StartAll, true, true)
|
||||
run_inner(root, Verb::StartAll, true)
|
||||
}
|
||||
|
||||
pub(crate) fn start_after_update(root: &Path) -> Result<DriverOutcome> {
|
||||
run_inner(root, Verb::StartAll, true, false)
|
||||
}
|
||||
|
||||
pub(crate) fn validate_secondary(root: &Path) -> Result<DriverOutcome> {
|
||||
run_inner(root, Verb::StartWorld, true, true)
|
||||
}
|
||||
|
||||
/// Validate without accepting game connections or submitting reports. Child supervisors inherit the flag.
|
||||
pub(crate) fn offline_launcher(text: &str) -> Result<String> {
|
||||
let normalized = text.replace("\r\n", "\n");
|
||||
let text = normalized.as_str();
|
||||
if text.contains("# coa-offline-validation") { return Ok(text.into()); }
|
||||
if !text.contains("def spawn(name, command, cwd, log):") || !text.contains("def relay_worker():") {
|
||||
return Err(Error::Invalid("This launcher cannot isolate an update validation. Update was not applied.".into()));
|
||||
}
|
||||
let spawn = "def spawn(name, command, cwd, log):\n # coa-offline-validation\n if os.environ.get('COA_UPDATE_VALIDATION') == '1':\n for filename in ('worldserver.conf', 'authserver.conf'):\n path = ROOT / 'Core/configs' / filename\n if path.exists():\n text = path.read_text(encoding='utf-8-sig')\n for key, value in (('BindIP', '\"127.0.0.1\"'), ('Ra.IP', '\"127.0.0.1\"'), ('SOAP.Enabled', '0')):\n text = re.sub(r'(?m)^\\s*' + re.escape(key) + r'\\s*=.*$', '', text)\n text += '\\n' + key + ' = ' + value + '\\n'\n path.write_text(text, encoding='utf-8')\n";
|
||||
let relay = "def relay_worker():\n if os.environ.get('COA_UPDATE_VALIDATION') == '1':\n save_process('relay-ready', os.getpid())\n while not (STATE / 'stop-relay').exists():\n time.sleep(0.5)\n return\n";
|
||||
Ok(text.replacen("def spawn(name, command, cwd, log):\n", spawn, 1).replacen("def relay_worker():\n", relay, 1))
|
||||
}
|
||||
|
||||
fn run_inner(root: &Path, verb: Verb, validating_update: bool, offline: bool) -> Result<DriverOutcome> {
|
||||
fn run_inner(root: &Path, verb: Verb, validating_update: bool) -> Result<DriverOutcome> {
|
||||
let root = fsx::canonicalize_lenient(root)?;
|
||||
let _update_lock = if !validating_update && matches!(verb, Verb::StartAll | Verb::StartWorld) {
|
||||
Some(crate::update::operation_lock(&crate::registry::metadata_dir_for(&root)?)?)
|
||||
} else { None };
|
||||
if !validating_update && matches!(verb, Verb::StartAll | Verb::StartWorld) {
|
||||
crate::update::recover_before_start(&root, &crate::registry::metadata_dir_for(&root)?)?;
|
||||
crate::update::ensure_recovered(&crate::registry::metadata_dir_for(&root)?)?;
|
||||
}
|
||||
if matches!(verb, Verb::StartAll | Verb::StartWorld) { crate::modules::ensure_bot_exclusivity(&root)?; }
|
||||
if crate::docker::is_docker(&root) {
|
||||
@@ -136,8 +124,7 @@ fn run_inner(root: &Path, verb: Verb, validating_update: bool, offline: bool) ->
|
||||
if matches!(verb, Verb::StartAll | Verb::StartWorld) { crate::modules::ensure_bot_exclusivity(&root)?; }
|
||||
let (python, script) = launcher(&root)?;
|
||||
let original = std::fs::read_to_string(&script)?;
|
||||
let imported = patch_launcher_imports(&original)?;
|
||||
let patched = if offline { offline_launcher(&imported)? } else { imported };
|
||||
let patched = patch_launcher_imports(&original)?;
|
||||
if original != patched {
|
||||
fsx::atomic_write(&script, patched.as_bytes())?;
|
||||
if let Ok(dir) = crate::registry::metadata_dir_for(&root) {
|
||||
@@ -150,10 +137,8 @@ fn run_inner(root: &Path, verb: Verb, validating_update: bool, offline: bool) ->
|
||||
}
|
||||
}
|
||||
let mut cmd = Command::new(&python);
|
||||
let launch = if offline && crate::update_fault::python_failure(&root) { "raise RuntimeError('Injected disposable-fixture Python failure')" } else { LAUNCH_SCRIPT };
|
||||
cmd.arg("-B").arg("-c").arg(launch).arg(&script).arg(verb.arg())
|
||||
cmd.arg("-B").arg("-c").arg(LAUNCH_SCRIPT).arg(&script).arg(verb.arg())
|
||||
.current_dir(&root).stdin(Stdio::null()).stdout(Stdio::piped()).stderr(Stdio::piped());
|
||||
if offline { cmd.env("COA_UPDATE_VALIDATION", "1"); }
|
||||
#[cfg(windows)]
|
||||
{
|
||||
use std::os::windows::process::CommandExt;
|
||||
@@ -173,7 +158,7 @@ fn run_inner(root: &Path, verb: Verb, validating_update: bool, offline: bool) ->
|
||||
let _ = stderr.read_to_string(&mut s);
|
||||
s
|
||||
});
|
||||
let deadline = Instant::now() + verb.timeout();
|
||||
let deadline = Instant::now() + verb.timeout(&root);
|
||||
let status = loop {
|
||||
if let Some(st) = child.try_wait()? {
|
||||
break Some(st);
|
||||
@@ -203,10 +188,7 @@ fn run_inner(root: &Path, verb: Verb, validating_update: bool, offline: bool) ->
|
||||
}
|
||||
};
|
||||
tracing::info!(?verb, ok, ?code, "driver: launcher verb finished");
|
||||
if ok && verb == Verb::StartAll {
|
||||
if offline { crate::multiworld::start_validation(&root)?; }
|
||||
else { crate::multiworld::start(&root)?; }
|
||||
}
|
||||
if ok && verb == Verb::StartAll { crate::multiworld::start(&root)?; }
|
||||
Ok(DriverOutcome { ok, exit_code, code, human: code.map(ErrorCode::human), output })
|
||||
}
|
||||
|
||||
@@ -225,11 +207,24 @@ pub(crate) fn patch_launcher_imports(text: &str) -> Result<String> {
|
||||
pub(crate) fn launcher_matches(signed: &str, actual: &[u8]) -> bool {
|
||||
if signed.as_bytes() == actual { return true; }
|
||||
if patch_launcher_imports(signed).is_ok_and(|s| s.as_bytes() == actual) { return true; }
|
||||
if patch_launcher_imports(signed).and_then(|s| offline_launcher(&s)).is_ok_and(|s| s.as_bytes() == actual) { return true; }
|
||||
crate::realms::patch_launcher(signed).is_ok_and(|s| s.as_bytes() == actual
|
||||
|| patch_launcher_imports(&s).is_ok_and(|p| p.as_bytes() == actual))
|
||||
}
|
||||
|
||||
/// Recover legacy metadata only when undoing supported Manager edits reproduces the recorded hash.
|
||||
pub(crate) fn launcher_matches_recorded(recorded: &str, actual: &[u8]) -> bool {
|
||||
let Ok(text) = std::str::from_utf8(actual) else { return false; };
|
||||
let without_import = text.replacen(
|
||||
"ROOT = Path(__file__).resolve().parents[1]\nsys.path.insert(0, str(Path(__file__).resolve().parent))",
|
||||
"ROOT = Path(__file__).resolve().parents[1]", 1,
|
||||
);
|
||||
for candidate in [Some(without_import.clone()), crate::realms::unpatch_launcher(&without_import)].into_iter().flatten() {
|
||||
if crate::fsx::sha256_bytes(candidate.as_bytes()).eq_ignore_ascii_case(recorded)
|
||||
&& launcher_matches(&candidate, actual) { return true; }
|
||||
}
|
||||
false
|
||||
}
|
||||
|
||||
pub(crate) fn startup_failure(root: &Path, started: &DriverOutcome) -> String {
|
||||
let code = started.code.filter(|c| *c != ErrorCode::Unknown)
|
||||
.or_else(|| crate::health::diagnose_installation(root));
|
||||
@@ -244,6 +239,18 @@ pub(crate) fn startup_failure(root: &Path, started: &DriverOutcome) -> String {
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn large_squid_provisioning_has_time_to_finish_without_extending_shutdown() {
|
||||
let folder = tempfile::tempdir().unwrap();
|
||||
let modules = folder.path().join("Core/configs/modules");
|
||||
std::fs::create_dir_all(&modules).unwrap();
|
||||
std::fs::write(modules.join("playerbots.conf.dist"), "AiPlayerbot.Enabled = 1\n").unwrap();
|
||||
assert_eq!(Verb::StartAll.timeout(folder.path()), Duration::from_secs(2700));
|
||||
assert_eq!(Verb::StopAll.timeout(folder.path()), Duration::from_secs(240));
|
||||
std::fs::write(modules.join("playerbots.conf"), "AiPlayerbot.Enabled = 0\n").unwrap();
|
||||
assert_eq!(Verb::StartWorld.timeout(folder.path()), Duration::from_secs(420));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn translates_known_launcher_messages() {
|
||||
assert_eq!(translate("RuntimeError: Port 8085 is already used. Stop the other server"), ErrorCode::PortInUse);
|
||||
|
||||
@@ -31,11 +31,25 @@ pub struct Settings {
|
||||
pub mode: Mode,
|
||||
/// The address friends type into their client for this mode.
|
||||
pub host: Option<String>,
|
||||
/// Independent of the effective host of the current mode. None means automatic LAN detection.
|
||||
#[serde(default)]
|
||||
pub lan_address_override: Option<String>,
|
||||
}
|
||||
|
||||
impl Default for Settings {
|
||||
fn default() -> Self {
|
||||
Settings { mode: Mode::Local, host: None }
|
||||
Settings { mode: Mode::Local, host: None, lan_address_override: None }
|
||||
}
|
||||
}
|
||||
|
||||
impl Settings {
|
||||
/// Only LAN application changes the LAN preference. Other modes keep it for the next LAN session.
|
||||
pub fn select_mode(&mut self, mode: Mode, host: String, lan_override: Option<String>) {
|
||||
if mode == Mode::Lan {
|
||||
self.lan_address_override = lan_override;
|
||||
}
|
||||
self.mode = mode;
|
||||
self.host = Some(host);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -233,7 +247,7 @@ CoA.AllowRemoteClients = 0
|
||||
fn a_shared_server_gets_its_bind_address_back_before_start_and_a_local_one_is_left_alone() {
|
||||
let (_d, root, meta) = setup();
|
||||
assert!(!ensure_bind(&root, &meta).unwrap(), "local mode: nothing to do");
|
||||
save(&meta, &Settings { mode: Mode::Private, host: Some("100.64.1.2".into()) }).unwrap();
|
||||
save(&meta, &Settings { mode: Mode::Private, host: Some("100.64.1.2".into()), ..Settings::default() }).unwrap();
|
||||
assert!(ensure_bind(&root, &meta).unwrap(), "templates were reset to 127.0.0.1 -> reopened");
|
||||
assert!(bind_is_open(&root));
|
||||
assert!(!ensure_bind(&root, &meta).unwrap(), "already open: idempotent");
|
||||
@@ -243,11 +257,39 @@ CoA.AllowRemoteClients = 0
|
||||
fn settings_round_trip_and_default_to_local() {
|
||||
let d = tempfile::tempdir().unwrap();
|
||||
assert_eq!(load(d.path()).mode, Mode::Local);
|
||||
save(d.path(), &Settings { mode: Mode::Private, host: Some("100.64.1.2".into()) }).unwrap();
|
||||
save(d.path(), &Settings { mode: Mode::Private, host: Some("100.64.1.2".into()), ..Settings::default() }).unwrap();
|
||||
let s = load(d.path());
|
||||
assert_eq!((s.mode, s.host.as_deref()), (Mode::Private, Some("100.64.1.2")));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn old_settings_load_without_migrating_effective_host_to_override() {
|
||||
let s: Settings = serde_json::from_str(r#"{"mode":"lan","host":"192.168.1.50"}"#).unwrap();
|
||||
assert_eq!(s.mode, Mode::Lan);
|
||||
assert_eq!(s.host.as_deref(), Some("192.168.1.50"));
|
||||
assert_eq!(s.lan_address_override, None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn lan_preference_survives_save_load_and_every_other_mode_and_can_be_cleared() {
|
||||
let d = tempfile::tempdir().unwrap();
|
||||
let mut s = Settings::default();
|
||||
s.select_mode(Mode::Lan, "192.168.1.50".into(), Some("192.168.1.50".into()));
|
||||
for (mode, host) in [(Mode::Private, "100.101.20.5"), (Mode::Direct, "203.0.113.9"), (Mode::Local, "127.0.0.1")] {
|
||||
s.select_mode(mode, host.into(), None);
|
||||
save(d.path(), &s).unwrap();
|
||||
s = load(d.path());
|
||||
assert_eq!(s.lan_address_override.as_deref(), Some("192.168.1.50"));
|
||||
assert_eq!(s.host.as_deref(), Some(host));
|
||||
let lan = crate::net::resolve_lan_host(s.lan_address_override.as_deref(), Some("192.168.0.169".parse().unwrap())).unwrap();
|
||||
s.select_mode(Mode::Lan, lan, s.lan_address_override.clone());
|
||||
assert_eq!(s.host.as_deref(), Some("192.168.1.50"));
|
||||
}
|
||||
s.select_mode(Mode::Lan, "192.168.0.169".into(), None);
|
||||
save(d.path(), &s).unwrap();
|
||||
assert_eq!(load(d.path()).lan_address_override, None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn friend_package_contains_only_whitelisted_files() {
|
||||
let (d, root, _m) = setup();
|
||||
@@ -274,4 +316,23 @@ CoA.AllowRemoteClients = 0
|
||||
}
|
||||
assert!(make_friend_package(&root, "bad host; x", false, &d.path().join("x.zip")).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn manual_lan_host_survives_startup_bind_restoration_and_drives_friend_package() {
|
||||
let (d, root, meta) = setup();
|
||||
let mut s = Settings::default();
|
||||
s.select_mode(Mode::Lan, "192.168.1.50".into(), Some("192.168.1.50".into()));
|
||||
save(&meta, &s).unwrap();
|
||||
assert!(ensure_bind(&root, &meta).unwrap());
|
||||
assert!(bind_is_open(&root));
|
||||
let restored = load(&meta);
|
||||
assert_eq!(restored.host.as_deref(), Some("192.168.1.50"));
|
||||
assert_eq!(restored.lan_address_override.as_deref(), Some("192.168.1.50"));
|
||||
let package = d.path().join("manual-lan.zip");
|
||||
make_friend_package(&root, restored.host.as_deref().unwrap(), false, &package).unwrap();
|
||||
let mut zip = zip::ZipArchive::new(fs::File::open(package).unwrap()).unwrap();
|
||||
let mut realm = String::new();
|
||||
std::io::Read::read_to_string(&mut zip.by_name("realmlist.wtf").unwrap(), &mut realm).unwrap();
|
||||
assert_eq!(realm, "set realmlist 192.168.1.50\r\n");
|
||||
}
|
||||
}
|
||||
@@ -35,7 +35,7 @@ pub struct Preflight {
|
||||
pub free_bytes: u64,
|
||||
}
|
||||
|
||||
fn problem(code: &'static str, message: &str) -> Problem {
|
||||
pub(crate) fn problem(code: &'static str, message: &str) -> Problem {
|
||||
Problem { code, message: message.into() }
|
||||
}
|
||||
|
||||
@@ -133,7 +133,7 @@ pub struct Installed {
|
||||
pub version: String,
|
||||
}
|
||||
|
||||
fn random_hex(n: usize) -> String {
|
||||
pub(crate) fn random_hex(n: usize) -> String {
|
||||
let mut s = String::new();
|
||||
while s.len() < n {
|
||||
s.push_str(&uuid::Uuid::new_v4().simple().to_string());
|
||||
@@ -148,6 +148,10 @@ pub(crate) fn bootstrap_database(root: &Path) -> Result<()> {
|
||||
with_scratch_ports(root, || bootstrap_database_inner(root))
|
||||
}
|
||||
|
||||
pub(crate) fn free_port() -> Result<u16> {
|
||||
Ok(std::net::TcpListener::bind("127.0.0.1:0")?.local_addr()?.port())
|
||||
}
|
||||
|
||||
/// Run `f` with the staging copy listening on unused ports, so an installation never collides with a server (or any
|
||||
/// other program) already using the shipped ports. The shipped ports are put back afterwards.
|
||||
pub(crate) fn with_scratch_ports<T>(root: &Path, f: impl FnOnce() -> Result<T>) -> Result<T> {
|
||||
@@ -155,14 +159,10 @@ pub(crate) fn with_scratch_ports<T>(root: &Path, f: impl FnOnce() -> Result<T>)
|
||||
let path = root.join("Settings/repack.json");
|
||||
let original: serde_json::Value = fsx::read_json(&path)?;
|
||||
let mut scratch = original.clone();
|
||||
let mut listeners = Vec::new();
|
||||
for k in KEYS {
|
||||
let listener = std::net::TcpListener::bind("127.0.0.1:0")?;
|
||||
scratch[k] = listener.local_addr()?.port().into();
|
||||
listeners.push(listener);
|
||||
scratch[k] = free_port()?.into();
|
||||
}
|
||||
fsx::atomic_write_json(&path, &scratch)?;
|
||||
drop(listeners);
|
||||
let result = f();
|
||||
// keep whatever else changed meanwhile (console credentials), restore only the ports
|
||||
let mut now: serde_json::Value = fsx::read_json(&path).unwrap_or(scratch);
|
||||
|
||||
@@ -25,7 +25,6 @@ pub mod population;
|
||||
pub mod process;
|
||||
pub mod manifest;
|
||||
pub mod migrations;
|
||||
pub mod migration_registry;
|
||||
pub mod multiworld;
|
||||
pub mod repair;
|
||||
pub mod schema_check;
|
||||
@@ -38,10 +37,9 @@ pub mod realmlist;
|
||||
pub mod realms;
|
||||
pub mod registry;
|
||||
pub mod release;
|
||||
pub mod report;
|
||||
pub mod release_schema;
|
||||
pub mod update;
|
||||
mod update_trial;
|
||||
mod update_fault;
|
||||
pub mod upnp;
|
||||
pub mod signing;
|
||||
pub mod srp6;
|
||||
|
||||
@@ -35,9 +35,9 @@ pub struct LedgerRow {
|
||||
/// Storage for the ledger and the ability to run a SQL file; implemented by the real database and by tests.
|
||||
pub trait Store {
|
||||
fn load(&self) -> Result<Vec<LedgerRow>>;
|
||||
fn load_readonly(&self) -> Result<Vec<LedgerRow>> { self.load() }
|
||||
fn put(&self, row: &LedgerRow) -> Result<()>;
|
||||
fn run_file(&self, schema: &str, file: &Path) -> Result<()>;
|
||||
fn checkpoint(&self, _point: &str) {}
|
||||
}
|
||||
|
||||
fn hex_of(s: &str) -> String {
|
||||
@@ -49,14 +49,17 @@ fn ident_ok(s: &str) -> bool {
|
||||
}
|
||||
|
||||
impl Store for Db {
|
||||
fn checkpoint(&self, point: &str) {
|
||||
if let Some(root) = self.native_root() { crate::update_fault::checkpoint(&root, point); }
|
||||
}
|
||||
fn load(&self) -> Result<Vec<LedgerRow>> {
|
||||
self.query(&format!(
|
||||
"CREATE TABLE IF NOT EXISTS `{LEDGER_SCHEMA}`.`{LEDGER_TABLE}` (`db` VARCHAR(32) NOT NULL, `id` VARCHAR(190) NOT NULL, `sha256` CHAR(64) NOT NULL, `status` VARCHAR(16) NOT NULL, `applied_at` DATETIME NOT NULL, `error` TEXT NULL, `baseline` TINYINT NOT NULL DEFAULT 0, PRIMARY KEY (`db`,`id`)) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;"
|
||||
))?;
|
||||
let out = self.query(&format!("SELECT `db`,`id`,`sha256`,`status`,`baseline`,COALESCE(HEX(`error`),'') FROM `{LEDGER_SCHEMA}`.`{LEDGER_TABLE}` ORDER BY `db`,`id`;"))?;
|
||||
self.load_readonly()
|
||||
}
|
||||
|
||||
fn load_readonly(&self) -> Result<Vec<LedgerRow>> {
|
||||
let out = if self.tables(LEDGER_SCHEMA)?.iter().any(|name| name == LEDGER_TABLE) {
|
||||
self.query(&format!("SELECT `db`,`id`,`sha256`,`status`,`baseline`,COALESCE(HEX(`error`),'') FROM `{LEDGER_SCHEMA}`.`{LEDGER_TABLE}` ORDER BY `db`,`id`;"))?
|
||||
} else { String::new() };
|
||||
let mut rows = Vec::new();
|
||||
// Files the core's own updater (or whoever prepared this database) already recorded count as applied.
|
||||
for (kind, schema) in db::SCHEMAS {
|
||||
@@ -152,7 +155,51 @@ fn recorded<'a>(rows: &'a [LedgerRow], m: &Migration) -> Option<&'a LedgerRow> {
|
||||
}
|
||||
|
||||
fn hash_changed(row: &LedgerRow, m: &Migration) -> bool {
|
||||
row.status == Status::Applied && row.sha256 != "0".repeat(64) && !row.sha256.eq_ignore_ascii_case(&m.sha256) && !m.compatible_sha256.iter().any(|h| h.eq_ignore_ascii_case(&row.sha256))
|
||||
row.status == Status::Applied && row.sha256 != "0".repeat(64) && !row.sha256.eq_ignore_ascii_case(&m.sha256)
|
||||
&& !m.compatible_sha256.iter().any(|hash| hash.eq_ignore_ascii_case(&row.sha256))
|
||||
}
|
||||
|
||||
/// Inspect recorded history without creating a ledger or executing migrations.
|
||||
pub fn preflight(store: &dyn Store, list: &[Migration]) -> Result<()> {
|
||||
check_history(&store.load_readonly()?, list)
|
||||
}
|
||||
|
||||
pub fn pending_count(store: &dyn Store, list: &[Migration]) -> Result<usize> {
|
||||
let rows = store.load_readonly()?;
|
||||
check_history(&rows, list)?;
|
||||
Ok(list.iter().filter(|m| recorded(&rows, m).is_none_or(|r| r.status != Status::Applied)).count())
|
||||
}
|
||||
|
||||
fn verified_file(m: &Migration, dir: &Path) -> Result<(&'static str, std::path::PathBuf, bool)> {
|
||||
if !ident_ok(&m.id) { return Err(Error::InvalidManifest(format!("migration id {:?} is not allowed", m.id))); }
|
||||
let schema = db::schema_of(&m.db)?;
|
||||
let path = fsx::safe_join(dir, &format!("{}/{}.sql", m.db, m.id))?;
|
||||
let bytes = std::fs::read(&path).map_err(|_| Error::Invalid(format!("migration file {} is missing", m.id)))?;
|
||||
let actual = fsx::sha256_bytes(&bytes);
|
||||
if !actual.eq_ignore_ascii_case(&m.sha256) { return Err(Error::HashMismatch { path: path.display().to_string(), expected: m.sha256.clone(), actual }); }
|
||||
Ok((schema, path, m.destructive || looks_destructive(&String::from_utf8_lossy(&bytes))))
|
||||
}
|
||||
|
||||
/// Check every migration artifact, including applied history, before replacing server files.
|
||||
pub fn verify_files(list: &[Migration], dir: &Path) -> Result<()> {
|
||||
let mut seen = std::collections::BTreeSet::new();
|
||||
for m in list {
|
||||
if !seen.insert((&m.db, &m.id)) { return Err(Error::InvalidManifest(format!("duplicate migration {} ({})", m.id, m.db))); }
|
||||
verified_file(m, dir)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn check_history(rows: &[LedgerRow], list: &[Migration]) -> Result<()> {
|
||||
for m in list {
|
||||
if recorded(rows, m).is_some_and(|r| matches!(r.status, Status::Running | Status::Failed)) {
|
||||
return Err(Error::Invalid(format!("Database update {} ({}) failed or was interrupted and may be partially applied. Restore its recovery point before retrying.", m.id, m.db)));
|
||||
}
|
||||
if recorded(rows, m).is_some_and(|r| hash_changed(r, m)) {
|
||||
return Err(Error::Invalid(format!("Applied database update {} ({}) has a different checksum. A new migration is required; it was not replayed.", m.id, m.db)));
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Record migrations as already present without running them (adopting an existing server whose database
|
||||
@@ -182,14 +229,7 @@ pub struct ApplyReport {
|
||||
pub fn apply_pending(store: &dyn Store, list: &[Migration], dir: &Path, snapshot: &dyn Fn() -> Result<String>) -> Result<ApplyReport> {
|
||||
let rows = store.load()?;
|
||||
// The list order is the release's order of application (released updates, then pending, then modules).
|
||||
for m in list {
|
||||
if recorded(&rows, m).is_some_and(|r| matches!(r.status, Status::Running | Status::Failed)) {
|
||||
return Err(Error::Invalid(format!("Database update {} ({}) failed or was interrupted and may be partially applied. Restore its recovery point before retrying.", m.id, m.db)));
|
||||
}
|
||||
if recorded(&rows, m).is_some_and(|r| hash_changed(r, m)) {
|
||||
return Err(Error::Invalid(format!("Applied database update {} ({}) has a different checksum. A new migration is required; it was not replayed.", m.id, m.db)));
|
||||
}
|
||||
}
|
||||
check_history(&rows, list)?;
|
||||
let todo: Vec<&Migration> = list.iter().filter(|m| recorded(&rows, m).is_none_or(|r| r.status != Status::Applied)).collect();
|
||||
tracing::info!(total = list.len(), pending = todo.len(), skipped = list.len() - todo.len(), "database migration plan");
|
||||
|
||||
@@ -197,17 +237,8 @@ pub fn apply_pending(store: &dyn Store, list: &[Migration], dir: &Path, snapshot
|
||||
let mut files = Vec::new();
|
||||
let mut any_destructive = false;
|
||||
for m in &todo {
|
||||
if !ident_ok(&m.id) {
|
||||
return Err(Error::InvalidManifest(format!("migration id {:?} is not allowed", m.id)));
|
||||
}
|
||||
let schema = db::schema_of(&m.db)?;
|
||||
let path = fsx::safe_join(dir, &format!("{}/{}.sql", m.db, m.id))?;
|
||||
let bytes = std::fs::read(&path).map_err(|_| Error::Invalid(format!("migration file {} is missing", m.id)))?;
|
||||
let actual = fsx::sha256_bytes(&bytes);
|
||||
if !actual.eq_ignore_ascii_case(&m.sha256) {
|
||||
return Err(Error::HashMismatch { path: path.display().to_string(), expected: m.sha256.clone(), actual });
|
||||
}
|
||||
any_destructive |= m.destructive || looks_destructive(&String::from_utf8_lossy(&bytes));
|
||||
let (schema, path, destructive) = verified_file(m, dir)?;
|
||||
any_destructive |= destructive;
|
||||
files.push((*m, schema, path));
|
||||
}
|
||||
|
||||
@@ -221,13 +252,10 @@ pub fn apply_pending(store: &dyn Store, list: &[Migration], dir: &Path, snapshot
|
||||
for (m, schema, path) in files {
|
||||
tracing::info!(migration = %m.id, database = %m.db, "database migration starting");
|
||||
store.put(&LedgerRow { db: m.db.clone(), id: m.id.clone(), sha256: m.sha256.clone(), status: Status::Running, error: Some("Interrupted SQL must be recovered before replay.".into()), baseline: false })?;
|
||||
store.checkpoint(&format!("before-sql:{}", m.id));
|
||||
match store.run_file(schema, &path) {
|
||||
Ok(()) => {
|
||||
store.checkpoint(&format!("after-sql:{}", m.id));
|
||||
store.put(&LedgerRow { db: m.db.clone(), id: m.id.clone(), sha256: m.sha256.clone(), status: Status::Applied, error: None, baseline: false })?;
|
||||
report.applied.push(m.id.clone());
|
||||
store.checkpoint(&format!("recorded-sql:{}", m.id));
|
||||
tracing::info!(migration = %m.id, database = %m.db, "database migration applied");
|
||||
}
|
||||
Err(e) => {
|
||||
@@ -312,16 +340,57 @@ mod tests {
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn only_explicit_published_compatibility_skips_changed_hash_without_rewriting_history() {
|
||||
fn staged_files_reject_missing_corrupt_duplicate_and_invalid_migrations() {
|
||||
let (dir, list) = setup(&[("characters", "repair", "SELECT 1;\n")]);
|
||||
verify_files(&list, dir.path()).unwrap();
|
||||
let mut bad = list.clone();
|
||||
bad[0].id = "../outside".into();
|
||||
assert!(verify_files(&bad, dir.path()).is_err());
|
||||
bad = list.clone();
|
||||
bad.push(list[0].clone());
|
||||
assert!(verify_files(&bad, dir.path()).is_err());
|
||||
std::fs::write(dir.path().join("characters/repair.sql"), b"SELECT 2;\n").unwrap();
|
||||
assert!(verify_files(&list, dir.path()).is_err());
|
||||
std::fs::remove_file(dir.path().join("characters/repair.sql")).unwrap();
|
||||
assert!(verify_files(&list, dir.path()).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn preflight_uses_readonly_history_and_rejects_conflicts_without_writes() {
|
||||
struct ReadOnly<'a>(&'a Mem);
|
||||
impl Store for ReadOnly<'_> {
|
||||
fn load(&self) -> Result<Vec<LedgerRow>> { panic!("preflight must use readonly access") }
|
||||
fn load_readonly(&self) -> Result<Vec<LedgerRow>> { self.0.load() }
|
||||
fn put(&self, _: &LedgerRow) -> Result<()> { panic!("preflight must not rewrite history") }
|
||||
fn run_file(&self, _: &str, _: &Path) -> Result<()> { panic!("preflight must not run SQL") }
|
||||
}
|
||||
let (_d, list) = setup(&[("characters", "repair", "SELECT 1;\n")]);
|
||||
for state in [Status::Applied, Status::Running, Status::Failed] {
|
||||
let store = Mem::default();
|
||||
store.rows.borrow_mut().push(LedgerRow { db: "characters".into(), id: "repair".into(), sha256: "a".repeat(64), status: state, error: None, baseline: false });
|
||||
assert!(preflight(&ReadOnly(&store), &list).is_err());
|
||||
assert_eq!(store.rows.borrow()[0].sha256, "a".repeat(64));
|
||||
assert_eq!(store.rows.borrow()[0].status, state);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn published_compatibility_preserves_history_and_never_replays_sql() {
|
||||
let (d, mut list) = setup(&[("characters", "repair", "SELECT 1;\n")]);
|
||||
let store = Mem::default();
|
||||
let previous = fsx::sha256_bytes(b"SELECT 1;\r\n");
|
||||
store.rows.borrow_mut().push(LedgerRow { db: "characters".into(), id: "repair".into(), sha256: previous.clone(), status: Status::Applied, error: None, baseline: false });
|
||||
let old = fsx::sha256_bytes(b"SELECT 1;\r\n");
|
||||
store.rows.borrow_mut().push(LedgerRow { db: "characters".into(), id: "repair".into(), sha256: old.clone(), status: Status::Applied, error: None, baseline: false });
|
||||
assert!(apply_pending(&store, &list, d.path(), &no_snapshot).is_err());
|
||||
list[0].compatible_sha256.push(previous.clone());
|
||||
list[0].compatible_sha256.push(old.clone());
|
||||
assert_eq!(status(&store, &list).unwrap()[0].status, Status::Applied);
|
||||
assert!(apply_pending(&store, &list, d.path(), &no_snapshot).unwrap().applied.is_empty());
|
||||
assert!(store.ran.borrow().is_empty());
|
||||
assert_eq!(store.rows.borrow()[0].sha256, previous);
|
||||
assert_eq!(store.rows.borrow()[0].sha256, old);
|
||||
store.rows.borrow_mut()[0].status = Status::Running;
|
||||
assert!(apply_pending(&store, &list, d.path(), &no_snapshot).is_err());
|
||||
store.rows.borrow_mut()[0].status = Status::Failed;
|
||||
assert!(apply_pending(&store, &list, d.path(), &no_snapshot).is_err());
|
||||
assert!(store.ran.borrow().is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -125,14 +125,6 @@ fn secondary_launcher(source: &str) -> Result<String> {
|
||||
}
|
||||
|
||||
pub fn start(main: &Path) -> Result<()> {
|
||||
start_inner(main, false)
|
||||
}
|
||||
|
||||
pub(crate) fn start_validation(main: &Path) -> Result<()> {
|
||||
start_inner(main, true)
|
||||
}
|
||||
|
||||
fn start_inner(main: &Path, offline: bool) -> Result<()> {
|
||||
if !realms::state(main)?.simultaneous { return Ok(()); }
|
||||
if is_running(main) {
|
||||
let second = root(main);
|
||||
@@ -140,7 +132,7 @@ fn start_inner(main: &Path, offline: bool) -> Result<()> {
|
||||
return Err(Error::Invalid("The second realm is still starting or stopping.".into()));
|
||||
}
|
||||
let second = prepare(main)?;
|
||||
let out = if offline { driver::validate_secondary(&second)? } else { driver::run(&second, Verb::StartWorld)? };
|
||||
let out = driver::run(&second, Verb::StartWorld)?;
|
||||
if !out.ok { return Err(Error::Invalid(format!("The second realm did not start: {}", out.output))); }
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -19,6 +19,51 @@ pub fn lan_ip() -> Option<Ipv4Addr> {
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
|
||||
pub struct LanAddress {
|
||||
pub interface: String,
|
||||
pub address: String,
|
||||
pub is_default: bool,
|
||||
}
|
||||
|
||||
/// Suitable unicast IPv4 addresses; shared carrier/Tailscale space belongs to Private mode.
|
||||
pub fn is_lan_address(ip: Ipv4Addr) -> bool {
|
||||
!ip.is_unspecified() && !ip.is_loopback() && !ip.is_link_local()
|
||||
&& !ip.is_multicast() && !ip.is_broadcast() && ip.octets()[0] != 0
|
||||
&& ip.octets()[0] < 240 && !is_cgnat_range(ip)
|
||||
}
|
||||
|
||||
pub fn validate_lan_address(address: &str) -> Result<Ipv4Addr> {
|
||||
address.parse::<Ipv4Addr>().ok().filter(|ip| is_lan_address(*ip))
|
||||
.ok_or_else(|| Error::Invalid("Invalid IPv4 address for local network.".into()))
|
||||
}
|
||||
|
||||
/// An absent/disconnected manual address is intentional: never fall back to another adapter.
|
||||
pub fn resolve_lan_host(manual: Option<&str>, automatic: Option<Ipv4Addr>) -> Result<String> {
|
||||
match manual {
|
||||
Some(address) => validate_lan_address(address).map(|ip| ip.to_string()),
|
||||
None => automatic.filter(|ip| is_lan_address(*ip)).map(|ip| ip.to_string())
|
||||
.ok_or_else(|| Error::Invalid("This computer has no usable local network address.".into())),
|
||||
}
|
||||
}
|
||||
|
||||
fn lan_candidates(rows: impl IntoIterator<Item = (String, Ipv4Addr)>, automatic: Option<Ipv4Addr>) -> Vec<LanAddress> {
|
||||
let mut rows: Vec<_> = rows.into_iter().filter(|(_, ip)| is_lan_address(*ip)).collect();
|
||||
rows.sort_by(|a, b| a.0.cmp(&b.0).then(a.1.cmp(&b.1)));
|
||||
let mut seen = std::collections::HashSet::new();
|
||||
rows.into_iter().filter(|(_, ip)| seen.insert(*ip)).map(|(interface, ip)| LanAddress {
|
||||
interface, address: ip.to_string(), is_default: Some(ip) == automatic,
|
||||
}).collect()
|
||||
}
|
||||
|
||||
/// Native OS enumeration (GetAdaptersAddresses on Windows, getifaddrs on Unix).
|
||||
pub fn lan_addresses(automatic: Option<Ipv4Addr>) -> Result<Vec<LanAddress>> {
|
||||
let interfaces = if_addrs::get_if_addrs()?;
|
||||
Ok(lan_candidates(interfaces.into_iter().filter(|i| i.is_oper_up()).filter_map(|i| {
|
||||
match i.ip() { IpAddr::V4(ip) => Some((i.name, ip)), _ => None }
|
||||
}), automatic))
|
||||
}
|
||||
|
||||
pub fn is_private(ip: Ipv4Addr) -> bool {
|
||||
ip.is_private() || ip.is_loopback() || ip.is_link_local()
|
||||
}
|
||||
@@ -132,6 +177,42 @@ mod tests {
|
||||
s.parse().unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn lan_validation_and_resolution_never_replace_manual_addresses() {
|
||||
for good in ["192.168.1.20", "10.0.0.5", "172.16.2.4"] {
|
||||
assert!(validate_lan_address(good).is_ok());
|
||||
}
|
||||
for bad in ["abc", "999.1.1.1", "0.0.0.0", "0.1.2.3", "127.0.0.1", "127.9.1.2", "169.254.10.20", "100.101.20.5", "224.0.0.1", "255.255.255.255", "240.0.0.1", "192.168.1.1'; DROP TABLE realmlist"] {
|
||||
assert!(validate_lan_address(bad).is_err(), "{bad}");
|
||||
}
|
||||
let automatic = Some(ip("192.168.0.169"));
|
||||
assert_eq!(resolve_lan_host(None, automatic).unwrap(), "192.168.0.169");
|
||||
assert_eq!(resolve_lan_host(Some("192.168.1.50"), automatic).unwrap(), "192.168.1.50");
|
||||
assert_eq!(resolve_lan_host(Some("192.168.1.50"), None).unwrap(), "192.168.1.50");
|
||||
assert!(resolve_lan_host(Some("invalid"), automatic).is_err());
|
||||
assert!(resolve_lan_host(None, None).is_err());
|
||||
assert!(resolve_lan_host(None, Some(ip("169.254.1.2"))).is_err());
|
||||
assert!(resolve_lan_host(None, Some(ip("100.100.1.2"))).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn candidates_are_filtered_deduplicated_deterministic_and_default_marked() {
|
||||
let rows = vec![
|
||||
("Wi-Fi", "192.168.0.25"), ("Ethernet 2", "192.168.1.50"),
|
||||
("Ethernet", "192.168.0.169"), ("Duplicate", "192.168.1.50"),
|
||||
("Loopback", "127.0.0.2"), ("APIPA", "169.254.1.2"),
|
||||
("Tailscale", "100.101.20.5"), ("Empty", "0.0.0.0"),
|
||||
("Hyper-V Virtual", "10.0.0.5"),
|
||||
];
|
||||
let make = |rows: Vec<(&str, &str)>| lan_candidates(rows.into_iter().map(|(name, address)| (name.into(), ip(address))), Some(ip("192.168.0.169")));
|
||||
let result = make(rows.clone());
|
||||
assert_eq!(result.len(), 4);
|
||||
assert_eq!(result.iter().filter(|a| a.is_default).count(), 1);
|
||||
assert!(result.iter().any(|a| a.interface == "Hyper-V Virtual"));
|
||||
assert!(result.iter().any(|a| a.is_default && a.address == "192.168.0.169"));
|
||||
assert_eq!(result, make(rows.into_iter().rev().collect()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn address_classes() {
|
||||
assert!(is_private(ip("192.168.1.5")) && is_private(ip("10.0.0.2")) && is_private(ip("172.16.4.4")) && is_private(ip("127.0.0.1")));
|
||||
|
||||
@@ -21,6 +21,12 @@ pub const DEFAULT_PART_SIZE: u64 = 1_900_000_000;
|
||||
/// Archive path of the one-time database credentials shipped with a base package.
|
||||
pub const BOOTSTRAP_CREDENTIALS: &str = "Settings/database.bootstrap.json";
|
||||
|
||||
/// Folder of a Linux (Docker) package that holds the starting databases: `<kind>.sql.zst` for `auth`, `characters`
|
||||
/// and `world`, in the format of the Manager's own backups. They hold the state in which every migration of the package is
|
||||
/// already applied (a world database cannot be rebuilt from the repository's SQL files: some migrations are guarded and
|
||||
/// only apply to the maintainers' own database).
|
||||
pub const BASELINE_DIR: &str = "Database/baseline";
|
||||
|
||||
/// Files that never belong in a shipped package: per-install state, logs, secrets, old binaries.
|
||||
pub fn excluded(rel: &str) -> bool {
|
||||
if rel.replace('\\', "/").to_lowercase().starts_with(".realms/") { return true; }
|
||||
|
||||
@@ -4,8 +4,6 @@
|
||||
use std::fs;
|
||||
use std::io::Read;
|
||||
use std::path::{Path, PathBuf};
|
||||
use base64::{engine::general_purpose::STANDARD, Engine};
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
use crate::download::{self, Cancel, Job, Progress};
|
||||
use crate::error::{Error, Result};
|
||||
@@ -22,77 +20,6 @@ pub enum Source {
|
||||
Dir(PathBuf),
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize, Deserialize)]
|
||||
pub struct Channel {
|
||||
pub schema: u32,
|
||||
pub version: String,
|
||||
pub release: String,
|
||||
pub manifest_sha256: String,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub acceptance_sha256: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
pub struct SignedChannel {
|
||||
pub payload: String,
|
||||
pub signature: String,
|
||||
}
|
||||
|
||||
pub fn verify_channel(bytes: &[u8], trusted_key: &str) -> Result<Channel> {
|
||||
let signed: SignedChannel = serde_json::from_slice(bytes).map_err(|e| Error::InvalidManifest(e.to_string()))?;
|
||||
let payload = STANDARD.decode(&signed.payload).map_err(|e| Error::InvalidManifest(e.to_string()))?;
|
||||
signing::verify(&payload, &signed.signature, trusted_key)?;
|
||||
let pointer: Channel = serde_json::from_slice(&payload).map_err(|e| Error::InvalidManifest(e.to_string()))?;
|
||||
let required = format!("https://github.com/Corfirean/coa-server-build/releases/download/server-{}/", pointer.version);
|
||||
if pointer.schema != 1 || crate::manifest::parse_version(&pointer.version).is_none() || pointer.release != required {
|
||||
return Err(Error::InvalidManifest("Channel does not point to an immutable server release.".into()));
|
||||
}
|
||||
Ok(pointer)
|
||||
}
|
||||
|
||||
/// A channel is one atomically replaced signed envelope. Its target is immutable.
|
||||
pub struct PinnedPackage {
|
||||
pub source: Source,
|
||||
pub manifest: Manifest,
|
||||
pub bytes: Vec<u8>,
|
||||
pub signature: Vec<u8>,
|
||||
}
|
||||
|
||||
pub fn fetch_package(source: &Source, trusted_key: &str) -> Result<PinnedPackage> {
|
||||
let channel = match source {
|
||||
Source::Dir(d) if !d.join("channel.json").exists() => None,
|
||||
_ => match fetch_small(source, "channel.json") {
|
||||
Ok(bytes) => Some(bytes),
|
||||
Err(Error::PackageNotPublished(_)) => None,
|
||||
Err(e) => return Err(e),
|
||||
},
|
||||
};
|
||||
let (mut resolved, expected) = if let Some(bytes) = channel {
|
||||
let pointer = verify_channel(&bytes, trusted_key)?;
|
||||
(Source::Url(pointer.release.clone()), Some(pointer))
|
||||
} else { (source.clone(), None) };
|
||||
let mut bytes = fetch_small(&resolved, "manifest.json")?;
|
||||
let mut signature = fetch_small(&resolved, "manifest.json.sig")?;
|
||||
signing::verify(&bytes, &String::from_utf8_lossy(&signature), trusted_key)?;
|
||||
let manifest = Manifest::parse(&bytes)?;
|
||||
// Legacy moving channels are pinned by matching their signed manifest to the immutable tag.
|
||||
if matches!(&resolved, Source::Url(url) if matches!(url.trim_end_matches('/'), "https://github.com/Corfirean/coa-server-build/releases/download/stable" | "https://github.com/Corfirean/coa-server-build/releases/download/edge")) {
|
||||
resolved = Source::Url(format!("https://github.com/Corfirean/coa-server-build/releases/download/server-{}/", manifest.version));
|
||||
let immutable = fetch_small(&resolved, "manifest.json")?;
|
||||
let sig = fetch_small(&resolved, "manifest.json.sig")?;
|
||||
signing::verify(&immutable, &String::from_utf8_lossy(&sig), trusted_key)?;
|
||||
if immutable != bytes { return Err(Error::InvalidManifest("Moving channel differs from its immutable release.".into())); }
|
||||
bytes = immutable;
|
||||
signature = sig;
|
||||
}
|
||||
if let Some(pointer) = expected {
|
||||
if pointer.version != manifest.version || pointer.manifest_sha256 != fsx::sha256_bytes(&bytes) {
|
||||
return Err(Error::InvalidManifest("Immutable release does not match the signed channel.".into()));
|
||||
}
|
||||
}
|
||||
Ok(PinnedPackage { source: resolved, manifest, bytes, signature })
|
||||
}
|
||||
|
||||
/// Read a small file (manifest, signature) from the source.
|
||||
pub fn fetch_small(source: &Source, name: &str) -> Result<Vec<u8>> {
|
||||
match source {
|
||||
@@ -117,8 +44,11 @@ pub fn fetch_small(source: &Source, name: &str) -> Result<Vec<u8>> {
|
||||
|
||||
/// Download and verify the manifest. Returns the parsed manifest and its exact bytes.
|
||||
pub fn fetch_manifest(source: &Source, trusted_key: &str) -> Result<(Manifest, Vec<u8>)> {
|
||||
let pinned = fetch_package(source, trusted_key)?;
|
||||
Ok((pinned.manifest, pinned.bytes))
|
||||
let bytes = fetch_small(source, "manifest.json")?;
|
||||
let sig = String::from_utf8_lossy(&fetch_small(source, "manifest.json.sig")?).into_owned();
|
||||
signing::verify(&bytes, &sig, trusted_key)?;
|
||||
let manifest = Manifest::parse(&bytes)?;
|
||||
Ok((manifest, bytes))
|
||||
}
|
||||
|
||||
/// Make every archive part available in a verified folder: a local source is used in place, a remote one is
|
||||
|
||||
@@ -250,6 +250,19 @@ pub fn is_alive(record: &ProcessIdentity) -> bool {
|
||||
identity(record.pid).map(|cur| cur.same_as(record)).unwrap_or(false)
|
||||
}
|
||||
|
||||
/// Every running process whose image file is named one of `names` (compared without case), wherever it lives. Only for
|
||||
/// diagnostics: a process found this way is not trusted to belong to any installation.
|
||||
pub fn find_by_file_names(names: &[&str]) -> Vec<ProcessIdentity> {
|
||||
sys::all_pids()
|
||||
.into_iter()
|
||||
.filter_map(identity)
|
||||
.filter(|p| {
|
||||
let file = p.exe.rsplit(['\\', '/']).next().unwrap_or("");
|
||||
names.iter().any(|n| file.eq_ignore_ascii_case(n))
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Every running process whose image is exactly `exe`.
|
||||
pub fn find_by_exe(exe: &Path) -> Vec<ProcessIdentity> {
|
||||
let want = exe.to_string_lossy().to_lowercase().replace('/', "\\");
|
||||
|
||||
@@ -287,25 +287,35 @@ pub fn prepare_launcher(root: &Path) -> Result<()> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
const LAUNCHER_REALM_REPLACEMENTS: &[(&str, &str)] = &[
|
||||
("(\"WorldDatabaseInfo\", \"acore_world\")", "(\"WorldDatabaseInfo\", \"acore_world_wildcard\" if coa_realm() == 'wildcard' else \"acore_world\")"),
|
||||
("(\"CharacterDatabaseInfo\", \"acore_characters\")", "(\"CharacterDatabaseInfo\", \"acore_characters_wildcard\" if coa_realm() == 'wildcard' else \"acore_characters\")"),
|
||||
("SET name='AzerothCore',address=", "SET name='{coa_realm_name()}',address="),
|
||||
("WHERE id=1;", "WHERE id={coa_realm_id()};"),
|
||||
("mysql(\"UPDATE acore_auth.realmlist SET flag=0", "mysql(f\"UPDATE acore_auth.realmlist SET flag=0"),
|
||||
];
|
||||
|
||||
const LAUNCHER_REALM_INSERT: &str = "# coa-manager-realm-profiles-v1\ndef coa_realm():\n path = ROOT / 'Settings/realm-profile.json'\n return json.loads(path.read_text(encoding='utf-8')).get('active', 'coa') if path.exists() else 'coa'\n\ndef coa_realm_id():\n return 2 if coa_realm() == 'wildcard' else 1\n\ndef coa_realm_name():\n return 'Wildcard' if coa_realm() == 'wildcard' else 'Conquest of Azeroth'\n\n";
|
||||
|
||||
pub(crate) fn patch_launcher(source: &str) -> Result<String> {
|
||||
if source.contains("# coa-manager-realm-profiles-v1") { return Ok(source.into()); }
|
||||
let replacements = [
|
||||
("(\"WorldDatabaseInfo\", \"acore_world\")", "(\"WorldDatabaseInfo\", \"acore_world_wildcard\" if coa_realm() == 'wildcard' else \"acore_world\")"),
|
||||
("(\"CharacterDatabaseInfo\", \"acore_characters\")", "(\"CharacterDatabaseInfo\", \"acore_characters_wildcard\" if coa_realm() == 'wildcard' else \"acore_characters\")"),
|
||||
("SET name='AzerothCore',address=", "SET name='{coa_realm_name()}',address="),
|
||||
("WHERE id=1;", "WHERE id={coa_realm_id()};"),
|
||||
("mysql(\"UPDATE acore_auth.realmlist SET flag=0", "mysql(f\"UPDATE acore_auth.realmlist SET flag=0"),
|
||||
];
|
||||
let mut out = source.to_string();
|
||||
for (from, to) in replacements {
|
||||
for &(from, to) in LAUNCHER_REALM_REPLACEMENTS {
|
||||
if !out.contains(from) { return Err(Error::Invalid("This launcher does not support realm profiles. Update the server package first.".into())); }
|
||||
out = out.replace(from, to);
|
||||
}
|
||||
let insert = "# coa-manager-realm-profiles-v1\ndef coa_realm():\n path = ROOT / 'Settings/realm-profile.json'\n return json.loads(path.read_text(encoding='utf-8')).get('active', 'coa') if path.exists() else 'coa'\n\ndef coa_realm_id():\n return 2 if coa_realm() == 'wildcard' else 1\n\ndef coa_realm_name():\n return 'Wildcard' if coa_realm() == 'wildcard' else 'Conquest of Azeroth'\n\n";
|
||||
// Insert before the entry point so ROOT, json and functions are all defined when called.
|
||||
let marker = "if __name__ == \"__main__\":";
|
||||
if !out.contains(marker) { return Err(Error::Invalid("Unrecognised server launcher entry point.".into())); }
|
||||
Ok(out.replace(marker, &format!("{insert}{marker}")))
|
||||
Ok(out.replace(marker, &format!("{LAUNCHER_REALM_INSERT}{marker}")))
|
||||
}
|
||||
|
||||
/// Reverse only our exact realm transformation; callers must verify the recovered original hash.
|
||||
pub(crate) fn unpatch_launcher(source: &str) -> Option<String> {
|
||||
if !source.contains(LAUNCHER_REALM_INSERT) { return None; }
|
||||
let mut original = source.replacen(LAUNCHER_REALM_INSERT, "", 1);
|
||||
for &(from, to) in LAUNCHER_REALM_REPLACEMENTS { original = original.replace(to, from); }
|
||||
patch_launcher(&original).ok().filter(|patched| patched == source).map(|_| original)
|
||||
}
|
||||
|
||||
pub fn before_start(root: &Path) -> Result<()> {
|
||||
|
||||
@@ -14,6 +14,7 @@ use crate::fsx;
|
||||
|
||||
pub const META_SCHEMA: u32 = 1;
|
||||
pub const LAYOUT_REPACK_V1: &str = "repack-v1";
|
||||
pub const LAYOUT_DOCKER_V1: &str = "docker-v1";
|
||||
const META_SUBDIRS: [&str; 6] = ["manifests", "backups", "migrations", "logs", "cache", "staging"];
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
|
||||
|
||||
@@ -13,7 +13,6 @@ use crate::package::{self, BuildOptions};
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct SqlFile {
|
||||
pub compatible_sha256: Vec<String>,
|
||||
pub db: String,
|
||||
pub id: String,
|
||||
/// Path relative to the checkout it came from (used only for ordering and display).
|
||||
@@ -50,7 +49,7 @@ pub fn collect_core_sql(core: &Path) -> Result<Vec<SqlFile>> {
|
||||
let mut out = Vec::new();
|
||||
let mut push = |db: &str, id: String, abs: PathBuf, origin: String| -> Result<()> {
|
||||
let sha256 = fsx::sha256_file(&abs)?;
|
||||
out.push(SqlFile { compatible_sha256: vec![], db: db.into(), id, origin, abs, sha256 });
|
||||
out.push(SqlFile { db: db.into(), id, origin, abs, sha256 });
|
||||
Ok(())
|
||||
};
|
||||
for (kind, dirs) in [("auth", ["db_auth", "pending_db_auth"]), ("characters", ["db_characters", "pending_db_characters"]), ("world", ["db_world", "pending_db_world"])] {
|
||||
@@ -88,18 +87,33 @@ pub fn collect_core_sql(core: &Path) -> Result<Vec<SqlFile>> {
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// Dump the three game databases of `server` (a repack or a Docker server, started if needed) into `out` as the starting
|
||||
/// databases of a Linux package: `<kind>.sql.zst`. The databases must be in the state in which every migration of the
|
||||
/// package is applied. Returns (kind, compressed bytes) per database.
|
||||
pub fn export_baseline(server: &Path, out: &Path) -> Result<Vec<(String, u64)>> {
|
||||
fs::create_dir_all(out)?;
|
||||
crate::backup::with_database(server, |db| {
|
||||
let mut done = Vec::new();
|
||||
for (kind, schema) in crate::db::SCHEMAS {
|
||||
let (bytes, _) = db.dump_to(schema, &out.join(format!("{kind}.sql.zst")))?;
|
||||
done.push((kind.to_string(), bytes));
|
||||
}
|
||||
Ok(done)
|
||||
})
|
||||
}
|
||||
|
||||
/// SQL a bots module checkout ships for the characters database (its `dist/sql`).
|
||||
pub fn collect_bots_sql(bots: &Path) -> Result<Vec<SqlFile>> {
|
||||
let mut out = Vec::new();
|
||||
for f in sql_in(&bots.join("dist/sql")) {
|
||||
let stem = f.file_stem().unwrap().to_string_lossy().into_owned();
|
||||
out.push(SqlFile { compatible_sha256: vec![], db: "characters".into(), id: format!("mod_coa_playerbots__{stem}"), origin: format!("dist/sql/{stem}.sql"), sha256: fsx::sha256_file(&f)?, abs: f });
|
||||
out.push(SqlFile { db: "characters".into(), id: format!("mod_coa_playerbots__{stem}"), origin: format!("dist/sql/{stem}.sql"), sha256: fsx::sha256_file(&f)?, abs: f });
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
fn to_migrations(files: &[SqlFile]) -> Vec<Migration> {
|
||||
files.iter().map(|f| Migration { compatible_sha256: f.compatible_sha256.clone(), id: f.id.clone(), db: f.db.clone(), sha256: f.sha256.clone(), destructive: false }).collect()
|
||||
files.iter().map(|f| Migration { compatible_sha256: vec![], id: f.id.clone(), db: f.db.clone(), sha256: f.sha256.clone(), destructive: false }).collect()
|
||||
}
|
||||
|
||||
pub struct UpdateParams<'a> {
|
||||
@@ -227,7 +241,7 @@ mod tests {
|
||||
write(&tree, "Core/newlib.dll", "n");
|
||||
write(&tree, crate::schema_check::CONTRACT, "same contract");
|
||||
write(&sqldir, "world.sql", "SELECT 1;");
|
||||
let sql = vec![SqlFile { compatible_sha256: vec![], db: "world".into(), id: "m1".into(), origin: "x".into(), abs: sqldir.join("world.sql"), sha256: fsx::sha256_file(&sqldir.join("world.sql")).unwrap() }];
|
||||
let sql = vec![SqlFile { db: "world".into(), id: "m1".into(), origin: "x".into(), abs: sqldir.join("world.sql"), sha256: fsx::sha256_file(&sqldir.join("world.sql")).unwrap() }];
|
||||
let m = pack_update(&UpdateParams { tree: &tree, base_manifest: &base, sql: &sql, out: &upd_out, version: "1.1.0".into(), core_commit: Some("a".repeat(40)), bots_commit: Some("b".repeat(40)), part_size: 1 << 20 }, &|_| {}).unwrap();
|
||||
let paths: Vec<&str> = m.files.iter().map(|f| f.path.as_str()).collect();
|
||||
assert!(paths.contains(&"Core/worldserver.exe") && paths.contains(&"Core/newlib.dll"));
|
||||
|
||||
@@ -16,7 +16,7 @@ pub fn collect(core: &Path, bots: Option<&Path>, repairs: Option<&Path>) -> Resu
|
||||
paths.sort();
|
||||
for path in paths.into_iter().filter(|p| p.extension().is_some_and(|e| e == "sql")) {
|
||||
let stem = path.file_stem().unwrap().to_string_lossy();
|
||||
files.push(SqlFile { compatible_sha256: vec![], db: kind.into(), id: format!("manager_repair__{stem}"), origin: format!("{kind}/{stem}.sql"), sha256: fsx::sha256_file(&path)?, abs: path });
|
||||
files.push(SqlFile { db: kind.into(), id: format!("manager_repair__{stem}"), origin: format!("{kind}/{stem}.sql"), sha256: fsx::sha256_file(&path)?, abs: path });
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -47,7 +47,7 @@ pub fn capture_release(fixture: &Path, tree: &Path, sql: &[SqlFile]) -> Result<(
|
||||
return Err(Error::Invalid("Refusing to apply release SQL to a non-fixture server.".into()));
|
||||
}
|
||||
let staging = tempfile::tempdir()?;
|
||||
let migrations: Vec<_> = sql.iter().map(|f| Migration { compatible_sha256: f.compatible_sha256.clone(), db: f.db.clone(), id: f.id.clone(), sha256: f.sha256.clone(), destructive: false }).collect();
|
||||
let migrations: Vec<_> = sql.iter().map(|f| Migration { compatible_sha256: vec![], db: f.db.clone(), id: f.id.clone(), sha256: f.sha256.clone(), destructive: false }).collect();
|
||||
for file in sql {
|
||||
let path = fsx::safe_join(staging.path(), &format!("{}/{}.sql", file.db, file.id))?;
|
||||
fsx::atomic_write(&path, &std::fs::read(&file.abs)?)?;
|
||||
|
||||
@@ -0,0 +1,116 @@
|
||||
//! Where a problem report goes. A report about the bots goes to the repository of the bot system in question, anything
|
||||
//! else to the Manager's own. The repositories come from the module catalog, so there is one list to keep right.
|
||||
|
||||
use std::path::Path;
|
||||
|
||||
use serde::Serialize;
|
||||
|
||||
pub const MANAGER_REPO: &str = "Corfirean/coa-server-manager";
|
||||
|
||||
/// One place a report can be filed. `id` is what the page sends back; `repo` is `owner/name` on GitHub.
|
||||
#[derive(Debug, Clone, Serialize, PartialEq, Eq)]
|
||||
pub struct Target {
|
||||
pub id: &'static str,
|
||||
pub repo: String,
|
||||
/// The report form asks for the Manager's labels only where we own the repository.
|
||||
pub ours: bool,
|
||||
}
|
||||
|
||||
/// `https://github.com/owner/name/tree/main/x` -> `owner/name`.
|
||||
fn repo_of(url: &str) -> Option<String> {
|
||||
let rest = url.strip_prefix("https://github.com/")?;
|
||||
let mut parts = rest.split('/');
|
||||
let (owner, name) = (parts.next()?, parts.next()?);
|
||||
let ok = |s: &str| !s.is_empty() && s.chars().all(|c| c.is_ascii_alphanumeric() || "._-".contains(c));
|
||||
(ok(owner) && ok(name)).then(|| format!("{owner}/{name}"))
|
||||
}
|
||||
|
||||
fn catalog_repo(id: &str) -> Option<String> {
|
||||
crate::modules::catalog().into_iter().find(|e| e.id == id).and_then(|e| repo_of(&e.repo))
|
||||
}
|
||||
|
||||
/// The three places, in the order the page lists them. A bot system whose repository is unknown falls back to the Manager's.
|
||||
pub fn targets() -> Vec<Target> {
|
||||
let mut v = vec![Target { id: "manager", repo: MANAGER_REPO.into(), ours: true }];
|
||||
for (id, module) in [("companions", "companions"), ("squid", "playerbots")] {
|
||||
if let Some(repo) = catalog_repo(module) {
|
||||
v.push(Target { id, repo: repo.clone(), ours: repo.starts_with("Corfirean/") });
|
||||
}
|
||||
}
|
||||
v
|
||||
}
|
||||
|
||||
pub fn target(id: &str) -> Option<Target> {
|
||||
targets().into_iter().find(|t| t.id == id)
|
||||
}
|
||||
|
||||
/// True for the "new issue" page of one of the targets: exactly that page, optionally with a query.
|
||||
pub fn is_new_issue_url(url: &str) -> bool {
|
||||
targets().iter().any(|t| {
|
||||
let base = format!("https://github.com/{}/issues/new", t.repo);
|
||||
url == base || url.starts_with(&format!("{base}?"))
|
||||
})
|
||||
}
|
||||
|
||||
/// What the report form fills in about the bot systems of this server.
|
||||
#[derive(Debug, Clone, Serialize, PartialEq, Eq)]
|
||||
pub struct Bots {
|
||||
/// The target the form should start with: the bot system that is switched on, else the Manager.
|
||||
pub suggested: &'static str,
|
||||
/// The release of SQUID Playerbots, when it is the one switched on.
|
||||
pub squid_version: Option<String>,
|
||||
}
|
||||
|
||||
pub fn bots(root: &Path) -> Bots {
|
||||
let list = crate::modules::list(root);
|
||||
let on = |id: &str| list.iter().find(|m| m.id == id).filter(|m| m.installed && m.enabled);
|
||||
let squid = on("playerbots");
|
||||
Bots {
|
||||
suggested: if squid.is_some() { "squid" } else if on("companions").is_some() { "companions" } else { "manager" },
|
||||
squid_version: squid.and_then(|m| m.version.clone()).filter(|v| !v.is_empty()),
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn the_three_targets_come_from_the_catalog() {
|
||||
let t = targets();
|
||||
let repo = |id: &str| t.iter().find(|x| x.id == id).map(|x| x.repo.clone());
|
||||
assert_eq!(repo("manager").as_deref(), Some("Corfirean/coa-server-manager"));
|
||||
assert_eq!(repo("companions").as_deref(), Some("Corfirean/mod-coa-playerbots"));
|
||||
assert_eq!(repo("squid").as_deref(), Some("Zyth45/mod-playerbots"));
|
||||
assert!(t.iter().find(|x| x.id == "squid").is_some_and(|x| !x.ours));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn repository_names_are_read_from_module_links() {
|
||||
assert_eq!(repo_of("https://github.com/Corfirean/azerothcore-wotlk-coa/tree/coa-bots/modules/x").as_deref(), Some("Corfirean/azerothcore-wotlk-coa"));
|
||||
assert_eq!(repo_of("https://github.com/Zyth45/mod-playerbots").as_deref(), Some("Zyth45/mod-playerbots"));
|
||||
assert_eq!(repo_of("https://example.com/a/b"), None);
|
||||
assert_eq!(repo_of("https://github.com/a"), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn only_the_new_issue_pages_of_the_targets_are_allowed() {
|
||||
assert!(is_new_issue_url("https://github.com/Zyth45/mod-playerbots/issues/new"));
|
||||
assert!(is_new_issue_url("https://github.com/Corfirean/mod-coa-playerbots/issues/new?title=a&body=b"));
|
||||
assert!(!is_new_issue_url("https://github.com/Zyth45/mod-playerbots/issues/newer"));
|
||||
assert!(!is_new_issue_url("https://github.com/Zyth45/other/issues/new"));
|
||||
assert!(!is_new_issue_url("https://evil.example/Corfirean/coa-server-manager/issues/new"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_suggested_target_follows_the_bot_system_that_is_on() {
|
||||
let d = tempfile::tempdir().unwrap();
|
||||
let root = d.path().join("srv");
|
||||
crate::layout::testkit::fake_repack(&root);
|
||||
let conf = root.join("Core/configs/modules");
|
||||
std::fs::write(conf.join("mod_coa_playerbots.conf"), "CoaBots.Enable = 1\n").unwrap();
|
||||
assert_eq!(bots(&root).suggested, "companions");
|
||||
std::fs::write(conf.join("mod_coa_playerbots.conf"), "CoaBots.Enable = 0\n").unwrap();
|
||||
assert_eq!(bots(&root).suggested, "manager");
|
||||
}
|
||||
}
|
||||
+409
-771
File diff suppressed because it is too large.
Load diff
@@ -7,7 +7,4 @@ license.workspace = true
|
||||
[dependencies]
|
||||
coa-core = { path = "../coa-core" }
|
||||
serde_json = "1"
|
||||
base64 = "0.22"
|
||||
ed25519-dalek = "2"
|
||||
tempfile = "3"
|
||||
chrono = { version = "0.4", default-features = false, features = ["clock", "std"] }
|
||||
@@ -6,6 +6,7 @@
|
||||
//! coa-release extract-schema-base --package DIR --fixture NEW-coa-schema-fixture-DIR
|
||||
//! coa-release schema-contract --repack FIXTURE --tree DIR --core DIR [--bots DIR] [--repairs DIR]
|
||||
//! coa-release clean-base --repack DIR --core DIR --tree DIR --out DIR [--bots DIR] [--data DIR]
|
||||
//! coa-release export-baseline --server DIR --out DIR (the three databases of a prepared server, for a Linux package)
|
||||
//! coa-release sign --dir DIR (key: env COA_SIGNING_KEY, or ~/.coa-manager/signing/manifest-signing.key)
|
||||
//! coa-release verify --dir DIR (against the public key built into this tool)
|
||||
|
||||
@@ -46,65 +47,6 @@ fn run() -> Result<(), String> {
|
||||
let e = |x: coa_core::Error| x.to_string();
|
||||
let part = a.get("part-size").and_then(|v| v.parse().ok()).unwrap_or(DEFAULT_PART_SIZE);
|
||||
match cmd.as_str() {
|
||||
"verify-registry" => {
|
||||
let sql = coa_core::migration_registry::reconcile(&PathBuf::from(need(&a, "registry")?), Vec::new()).map_err(e)?;
|
||||
println!("Verified {} historical migrations, order and signed byte variants", sql.len());
|
||||
}
|
||||
"resolve" => {
|
||||
let package = coa_core::pkgsource::fetch_package(&coa_core::pkgsource::Source::Url(need(&a, "source")?.clone()), coa_core::signing::EMBEDDED_PUBLIC_KEY).map_err(e)?;
|
||||
coa_core::fsx::atomic_write(&PathBuf::from(need(&a, "out")?), &package.bytes).map_err(e)?;
|
||||
}
|
||||
"extract-game-data" => {
|
||||
let source = PathBuf::from(need(&a, "package")?);
|
||||
let package = coa_core::pkgsource::fetch_package(&coa_core::pkgsource::Source::Dir(source.clone()), coa_core::signing::EMBEDDED_PUBLIC_KEY).map_err(e)?;
|
||||
if !package.manifest.files.iter().any(|f| f.path.starts_with("Data/")) { return Err("Signed base has no game data.".into()); }
|
||||
coa_core::package::extract_selected(&source, &package.manifest, &PathBuf::from(need(&a, "fixture")?), &|p| p.starts_with("Data/"), &|_, _| {}).map_err(e)?;
|
||||
}
|
||||
"repackage" => {
|
||||
let source = PathBuf::from(need(&a, "package")?);
|
||||
let pinned = coa_core::pkgsource::fetch_package(&coa_core::pkgsource::Source::Dir(source.clone()), coa_core::signing::EMBEDDED_PUBLIC_KEY).map_err(e)?;
|
||||
let work = tempfile::tempdir().map_err(|e| e.to_string())?;
|
||||
coa_core::package::extract(&source, &pinned.manifest, work.path(), &|_, _| {}).map_err(e)?;
|
||||
let mut sql: Vec<_> = pinned.manifest.migrations.iter().map(|m| coa_core::release::SqlFile {
|
||||
compatible_sha256: m.compatible_sha256.clone(), db: m.db.clone(), id: m.id.clone(), sha256: m.sha256.clone(), origin: "signed package".into(), abs: work.path().join("_migrations").join(&m.db).join(format!("{}.sql", m.id)),
|
||||
}).collect();
|
||||
let repairs = PathBuf::from(need(&a, "repairs")?);
|
||||
for repair in coa_core::release_schema::collect(&work.path().join("no-core"), None, Some(&repairs)).map_err(e)? {
|
||||
if !sql.iter().any(|m| m.db == repair.db && m.id == repair.id) { sql.push(repair); }
|
||||
}
|
||||
let sql = coa_core::migration_registry::reconcile(&PathBuf::from(need(&a, "registry")?), sql).map_err(e)?;
|
||||
let migrations = sql.iter().map(|m| coa_core::manifest::Migration { compatible_sha256: m.compatible_sha256.clone(), db: m.db.clone(), id: m.id.clone(), sha256: m.sha256.clone(), destructive: false }).collect();
|
||||
for file in &sql { coa_core::fsx::atomic_write(&work.path().join("_migrations").join(&file.db).join(format!("{}.sql", file.id)), &std::fs::read(&file.abs).map_err(|e| e.to_string())?).map_err(e)?; }
|
||||
let out = PathBuf::from(need(&a, "out")?);
|
||||
let opts = BuildOptions { kind: Kind::Update, version: need(&a, "version")?.clone(), core_commit: pinned.manifest.core.commit, bots_commit: pinned.manifest.bots.and_then(|b| b.commit), built_at: chrono_now(), part_size: part, migrations };
|
||||
let mut manifest = build(work.path(), &out, &opts, &|s| eprintln!("{s}")).map_err(e)?;
|
||||
manifest.min_manager_version = coa_core::MANAGER_VERSION.into();
|
||||
coa_core::fsx::atomic_write_json(&out.join("manifest.json"), &manifest).map_err(e)?;
|
||||
}
|
||||
"archive-migrations" => {
|
||||
coa_core::migration_registry::import(&PathBuf::from(need(&a, "package")?), &PathBuf::from(need(&a, "registry")?), coa_core::signing::EMBEDDED_PUBLIC_KEY).map_err(e)?;
|
||||
println!("Published migration bytes and compatibility archived");
|
||||
}
|
||||
"verify-channel" => {
|
||||
let pointer = coa_core::pkgsource::verify_channel(&std::fs::read(need(&a, "file")?).map_err(|e| e.to_string())?, coa_core::signing::EMBEDDED_PUBLIC_KEY).map_err(e)?;
|
||||
let dir = PathBuf::from(need(&a, "dir")?);
|
||||
let manifest: Manifest = coa_core::fsx::read_json(&dir.join("manifest.json")).map_err(e)?;
|
||||
if manifest.version != pointer.version || coa_core::fsx::sha256_file(&dir.join("manifest.json")).map_err(e)? != pointer.manifest_sha256 || pointer.acceptance_sha256.as_deref() != Some(&coa_core::fsx::sha256_file(&dir.join("acceptance.json")).map_err(e)?) {
|
||||
return Err("Signed channel differs from the tested package/report".into());
|
||||
}
|
||||
}
|
||||
"channel" => {
|
||||
use base64::{engine::general_purpose::STANDARD, Engine};
|
||||
use ed25519_dalek::{Signer, SigningKey};
|
||||
let dir = PathBuf::from(need(&a, "dir")?);
|
||||
let pinned = coa_core::pkgsource::fetch_package(&coa_core::pkgsource::Source::Dir(dir.clone()), coa_core::signing::EMBEDDED_PUBLIC_KEY).map_err(e)?;
|
||||
let pointer = coa_core::pkgsource::Channel { schema: 1, version: pinned.manifest.version.clone(), release: format!("https://github.com/Corfirean/coa-server-build/releases/download/server-{}/", pinned.manifest.version), manifest_sha256: coa_core::fsx::sha256_bytes(&pinned.bytes), acceptance_sha256: Some(coa_core::fsx::sha256_file(&dir.join("acceptance.json")).map_err(e)?) };
|
||||
let payload = serde_json::to_vec(&pointer).map_err(|e| e.to_string())?;
|
||||
let seed: [u8; 32] = STANDARD.decode(signing_key()?.trim()).map_err(|e| e.to_string())?.try_into().map_err(|_| "Wrong signing key length")?;
|
||||
let signed = coa_core::pkgsource::SignedChannel { payload: STANDARD.encode(&payload), signature: STANDARD.encode(SigningKey::from_bytes(&seed).sign(&payload).to_bytes()) };
|
||||
coa_core::signing::verify_embedded(&payload, &signed.signature).map_err(e)?;
|
||||
coa_core::fsx::atomic_write_json(&PathBuf::from(need(&a, "out")?), &signed).map_err(e)?;
|
||||
}
|
||||
"extract-schema-base" => {
|
||||
coa_core::release_schema::extract_base(
|
||||
&PathBuf::from(need(&a, "package")?), &PathBuf::from(need(&a, "fixture")?),
|
||||
@@ -118,8 +60,7 @@ fn run() -> Result<(), String> {
|
||||
if let Some(core) = a.get("core") {
|
||||
let bots = a.get("bots").map(PathBuf::from);
|
||||
let repairs = a.get("repairs").map(PathBuf::from);
|
||||
let mut sql = coa_core::release_schema::collect(&PathBuf::from(core), bots.as_deref(), repairs.as_deref()).map_err(e)?;
|
||||
if let Some(registry) = a.get("registry") { sql = coa_core::migration_registry::reconcile(&PathBuf::from(registry), sql).map_err(e)?; }
|
||||
let sql = coa_core::release_schema::collect(&PathBuf::from(core), bots.as_deref(), repairs.as_deref()).map_err(e)?;
|
||||
coa_core::release_schema::capture_release(&repack, &tree, &sql).map_err(e)?;
|
||||
} else {
|
||||
coa_core::backup::with_database(&repack, |db| coa_core::schema_check::capture(db, &tree)).map_err(e)?;
|
||||
@@ -137,8 +78,7 @@ fn run() -> Result<(), String> {
|
||||
coa_core::schema_check::require_release_contract(&PathBuf::from(need(&a, "tree")?)).map_err(e)?;
|
||||
let bots = a.get("bots").map(PathBuf::from);
|
||||
let repairs = a.get("repairs").map(PathBuf::from);
|
||||
let mut sql = coa_core::release_schema::collect(&PathBuf::from(need(&a, "core")?), bots.as_deref(), repairs.as_deref()).map_err(e)?;
|
||||
if let Some(registry) = a.get("registry") { sql = coa_core::migration_registry::reconcile(&PathBuf::from(registry), sql).map_err(e)?; }
|
||||
let sql = coa_core::release_schema::collect(&PathBuf::from(need(&a, "core")?), bots.as_deref(), repairs.as_deref()).map_err(e)?;
|
||||
let out = PathBuf::from(need(&a, "out")?);
|
||||
let m = pack_update(
|
||||
&UpdateParams { tree: &PathBuf::from(need(&a, "tree")?), base_manifest: &base, sql: &sql, out: &out, version: need(&a, "version")?.clone(), core_commit: a.get("core-commit").cloned(), bots_commit: a.get("bots-commit").cloned(), part_size: part },
|
||||
@@ -154,6 +94,12 @@ fn run() -> Result<(), String> {
|
||||
coa_core::cleanbase::build(&coa_core::cleanbase::Params { repack: &repack, core: &core, bots: bots.as_deref(), tree: &tree, data: data.as_deref(), out: &out }, &|s| eprintln!("{s}")).map_err(e)?;
|
||||
println!("clean base tree at {}", out.display());
|
||||
}
|
||||
"export-baseline" => {
|
||||
let done = coa_core::release::export_baseline(&PathBuf::from(need(&a, "server")?), &PathBuf::from(need(&a, "out")?)).map_err(e)?;
|
||||
for (kind, bytes) in done {
|
||||
println!("{kind}.sql.zst: {:.1} MB", bytes as f64 / 1e6);
|
||||
}
|
||||
}
|
||||
"sign" => {
|
||||
let dir = PathBuf::from(need(&a, "dir")?);
|
||||
require_contract_entry(&dir)?;
|
||||
|
||||
+38
-1
@@ -374,9 +374,46 @@ hand over to `coa_core::docker`; nothing else needed to change for start, stop,
|
||||
commands do on the host (password through `MYSQL_PWD`, never on a command line). Nothing else changes: accounts,
|
||||
backups, the population query, migrations and the RA service account all go through `Db`, and the host needs no
|
||||
MySQL client. A repack keeps using its bundled tools.
|
||||
* **Not done yet**: installation and the database setup (schemas, `acore` user), updates, port conflict detection,
|
||||
* **Health of the database container** is a ping over TCP, like every connection the Manager makes. On a new volume the
|
||||
image first runs a temporary server that answers on its socket but takes no network connection; a socket ping reported
|
||||
the container healthy about four seconds before TCP worked (measured: 10 s against 14 s).
|
||||
* **Main configuration files**: a package carries only `worldserver.conf.dist` and `authserver.conf.dist` (the release
|
||||
tool leaves active files out). On Windows the launcher writes them at each start; on Docker `ensure_main_configs` creates
|
||||
them from the templates when they are missing, at installation and at every start, and never overwrites one.
|
||||
* **Installing a new server** (`docker/install.rs`, separate from `install::install_base`, which is not touched). Same
|
||||
order of events: signed manifest, space and folder checks, verified download, extraction into `<dest>.installing`,
|
||||
database, then one rename. The package must hold `Core/worldserver`, `Core/authserver`, the `.dist` templates,
|
||||
`_migrations/` and **`Database/baseline/{auth,characters,world}.sql.zst`**. The baseline is a dump, in the format of the
|
||||
Manager's backups, of databases in which **every migration of the package is already applied**; the installer imports
|
||||
it, records those migrations as applied (`baseline = 1`, a few bulk statements) and creates the `acore` account, the
|
||||
realm port and the console account. It is the same arrangement as a Windows package, which ships its prepared database.
|
||||
The databases are **not rebuilt from the repository's SQL**: some migrations are guards generated from the maintainers'
|
||||
live database (`rev_20260903_01_live_class_baseline` refuses to run unless the table holds exactly the rows it expects),
|
||||
so replaying the SQL files from the base scripts fails, in any order. `coa-release export-baseline --server DIR --out DIR`
|
||||
produces the dumps from a prepared server (repack or Docker). The game data stays where the person has it
|
||||
(`dataDir` in `docker.json`, mounted read-only). A failure removes the containers, the volume and the staging folder.
|
||||
* **Not done yet**: wiring the installer into the screens, downloading the game data, updates, port conflict detection,
|
||||
the firewall and exposure checks, the Wildcard realm profiles, and the client under Wine/Proton.
|
||||
|
||||
### D14. Keeping Windows and Linux apart
|
||||
|
||||
A fix for one platform must not be able to break the other. The rules:
|
||||
|
||||
1. **Platform code lives in its own modules**: `coa_core::docker` for Linux and Docker; the repack code (`driver`, `process`,
|
||||
`install`, `layout` and the bundled-tool half of `db`) for Windows. A new Linux feature is a new file there, not an edit
|
||||
of a repack function.
|
||||
2. **Shared modules hold platform-neutral logic only** (manifest, signing, download, extraction, migrations, backups,
|
||||
configuration editing, the registry).
|
||||
3. **The difference enters in as few places as possible**: the early `is_docker` return at the top of `driver::run`,
|
||||
`process::observe`, `layout::scan` and `Db::from_repack`, and the platform checks of the Tauri layer. Everything past
|
||||
that point belongs to one platform.
|
||||
4. **No `cfg` in the middle of a shared algorithm.** Where one is unavoidable (file modes, a path comparison), it is small,
|
||||
commented, and the other platform's branch is the code that was there before.
|
||||
5. **Reuse by calling, not by editing**: a Linux feature that needs a helper from a Windows-side file makes it
|
||||
`pub(crate)` and calls it (visibility only); it does not change what the helper does.
|
||||
6. **Both platforms are tested on every pull request** (`check.yml`: Windows and Linux). Tests of one platform's behaviour
|
||||
are marked for that platform, so they cannot fail on the other.
|
||||
|
||||
---------------------------------------------------------------------------------------------------------
|
||||
|
||||
## 3. Flows
|
||||
|
||||
@@ -1,94 +0,0 @@
|
||||
# Reliable updates and Windows acceptance
|
||||
|
||||
An operation resolves one signed manifest and immutable release before downloading its
|
||||
archive. The same verified bytes are used for the private trial and the real application.
|
||||
The installation lock covers stop, snapshot, trial, application, validation and recovery.
|
||||
Native Windows installations with the bundled Python and MySQL runtime are supported;
|
||||
Docker and unrecognised launchers are rejected before applying files.
|
||||
|
||||
The manager measures the installation and database directories, checks free space and
|
||||
allocates recovery reserves. The private copy contains independent runtime, configuration,
|
||||
game-data and database files. It imports the verified original recovery point, runs the
|
||||
candidate SQL and uses loopback ports for startup. The known launcher reporting relay is
|
||||
disabled during validation. No junctions or hardlinks are created.
|
||||
|
||||
Transactions keep the exact manifest hash, original running state, protected generated
|
||||
files, database recovery point and individual file operations. SQL has its own migration
|
||||
ledger. Stop, snapshot and trial have separate durable states. The original failure stage
|
||||
is retained when the current state changes to recovery or recovered.
|
||||
Interrupted SQL is restored, never automatically repeated. Windows file replacement
|
||||
uses a synced temporary file and MoveFileExW with WRITE_THROUGH, including long paths.
|
||||
Recovery is repeatable and does not require backing up the damaged state. Corrupt journals
|
||||
or snapshots block startup and preserve available copies.
|
||||
|
||||
Recovery verifies the original dump before importing it into a private recovery schema,
|
||||
then compares the live database with a deterministic dump of that schema. This accounts
|
||||
for MySQL's normalisation of character-set declarations while checking schema and rows.
|
||||
Configuration backups carry individual content hashes. Legacy update snapshots without
|
||||
those hashes require manual inspection rather than an unverified automatic restore.
|
||||
Database dumps and configuration copies are flushed to disk before the snapshot is usable.
|
||||
A committed operation interrupted before admission
|
||||
resumes startup without undoing the committed database. Diagnostic JSON is saved locally;
|
||||
database passwords are removed and reports leave the machine only through explicit export.
|
||||
|
||||
## Migration publication
|
||||
|
||||
`coa-release archive-migrations --package DIR --registry DIR` verifies the released
|
||||
signature and preserves original SQL bytes, fixed order, hashes and signed provenance.
|
||||
Only byte variants differing in UTF-8 BOM or line endings can share an ID. Other changes
|
||||
fail the build and need a new migration ID. Compatibility hashes are included in the signed
|
||||
manifest, leaving existing ledger checksums unchanged.
|
||||
|
||||
Published packages use `server-VERSION` releases. Channels contain one signed envelope;
|
||||
it binds the immutable manifest and acceptance report hashes. Stable is switched only
|
||||
after package verification and acceptance. Never replace assets of an existing immutable
|
||||
release or rewrite historical registry SQL.
|
||||
|
||||
## Disposable acceptance fixture
|
||||
|
||||
Run `tools/update-chaos-gate.ps1 -BasePackage DIR -CandidatePackage DIR -Target NEW_PATH`
|
||||
on Windows. NEW_PATH must start with `coa-schema-fixture-chaos-`; the harness creates
|
||||
both disposable markers itself. Base and candidate signatures are required. The harness
|
||||
extracts game data independently and seeds an account, character and inventory item.
|
||||
Optional `-DataSource DIR` reads an existing game-data folder without modifying it.
|
||||
|
||||
Crash injection is compiled only with `coa-core/testkit` and additionally requires the
|
||||
disposable marker. `COA_UPDATE_CRASH_AT` terminates the test process with exit 91 at a
|
||||
named checkpoint. Production builds do not enable this mechanism. The harness exercises
|
||||
file journaling, SQL phases, commit and repeated recovery interruption. Backups and failed
|
||||
trial copies remain available for diagnosis.
|
||||
|
||||
The release jobs must run on a Windows worker with enough free space for the actual
|
||||
signed base, private copy, full snapshots and recovery reserves. Insufficient space is a
|
||||
test failure, not permission to bypass acceptance.
|
||||
The workflows require a dedicated runner labelled `coa-update-acceptance` (Windows,
|
||||
X64). Provision at least 300 GB of free workspace and 16 GB of RAM for the retained
|
||||
ten-scenario matrix, plus the normal Rust/Tauri build prerequisites. The timeout is
|
||||
24 hours: full snapshot, import and recovery checks take minutes per injected fault.
|
||||
A default hosted runner's disk and four-hour budget are insufficient for this gate.
|
||||
|
||||
`tools/update-chaos-matrix.ps1` runs separate fixtures for CoA, Wildcard, both worlds,
|
||||
SQUID and imported installations. With `-PreviousPackage`, it also runs each mode from
|
||||
that signed previous release. Its acceptance report binds every scenario to the same
|
||||
candidate manifest hash and manager source commit. Publication requires all ten scenarios.
|
||||
It also requires every mandatory fault class in each scenario's coverage record. Missing
|
||||
coverage produces an `incomplete` report and fails publication. The current harness still
|
||||
lacks real disk exhaustion, denied writes, database-child and new-server crash coverage,
|
||||
OS network containment and coverage of every file-operation phase.
|
||||
The gate includes real occupied ports and locked files, a Python startup failure, and SQL
|
||||
that creates and populates a table before failing. These faults must preserve seeded
|
||||
accounts, characters and inventory in every applicable database.
|
||||
|
||||
Validation currently isolates listeners on loopback and disables the recognised reporting
|
||||
relay. It does not enforce an operating-system firewall against arbitrary outbound actions
|
||||
in custom binaries; additional network containment is required for that release criterion.
|
||||
|
||||
## Release acceptance still required
|
||||
|
||||
Unit tests and compilation do not establish the full release criterion. Record results
|
||||
for exact package and installer hashes, previous supported releases and skipped versions,
|
||||
CoA/Wildcard/both/SQUID, imported repacks and modified configurations. Exercise occupied
|
||||
ports/files, partial DDL, disk exhaustion, write errors, corrupt packages/journals/backups,
|
||||
Python failure and server crashes. Verify schema, all player data, migration history,
|
||||
metadata and startup after every injected failure. A passing subset must not be described
|
||||
as completion of this matrix or as a guarantee against all possible failures.
|
||||
@@ -1,61 +0,0 @@
|
||||
# Local update validation, 2026-10-05
|
||||
|
||||
These results are a partial validation record, not a release acceptance report.
|
||||
Tests use the independently copied, doubly marked disposable fixture
|
||||
`C:\games\coa-schema-fixture-chaos-20261005-v1`. User installations are not modified.
|
||||
|
||||
Candidate: `0.261005.24`, signed manifest SHA-256
|
||||
`1284b1273815209c9621b6d173a2211bae316f33462ccbe8b578e53b8d26fb5b`.
|
||||
Published migration provenance was verified for `0.261005.0` and `0.261005.22`.
|
||||
Their disputed repair differs only by line endings; both published hashes are retained.
|
||||
|
||||
Completed real-runtime checks:
|
||||
|
||||
- Base-to-candidate update, isolated trial, SQL, startup and commit.
|
||||
- Repeat candidate application without replaying applied migrations.
|
||||
- CoA and Wildcard together, including both world processes and player databases.
|
||||
- Hard process termination after stop and after corrective SQL.
|
||||
- Repeated recovery interruption after database restoration, followed by successful recovery.
|
||||
- Occupied world port and exclusively locked configuration-default file, rejected before stop.
|
||||
- Partial DDL and inserted data followed by invalid SQL in the live corrective migration.
|
||||
Automatic rollback completed and removed the injected table.
|
||||
- Bundled Python failure during live startup after a successful private two-world trial.
|
||||
Automatic recovery passed exact pre-operation file and installation-metadata hashes,
|
||||
restored all six databases, and preserved seeded accounts, characters and inventory.
|
||||
- Modified user template values survived recovery. The fixture changes the template,
|
||||
not the launcher-generated active file; this corrected an initial harness assertion.
|
||||
- A modified manifest with its original signature was rejected before application.
|
||||
- Hard termination immediately after recording a complete snapshot, followed by separately
|
||||
corrupted transaction JSON and compressed character database archive. Both recovery
|
||||
attempts refused without starting services or changing the world executable/installation
|
||||
metadata. After removing the injected corruption, rollback completed and preserved the
|
||||
seeded accounts, characters and inventory in both worlds.
|
||||
- A live Python failure with both worlds originally running restored their ready state,
|
||||
all six databases, player data, configuration and installation metadata. An initial
|
||||
strict comparison exposed realm-profile regeneration after restart; the final protection
|
||||
pass was corrected and the real-runtime case passed on repetition. Test processes were
|
||||
explicitly stopped after verification.
|
||||
|
||||
Checks compare restored database content and preserve a seeded account, character and
|
||||
inventory item in each applicable realm. Recovery also checks original file hashes and
|
||||
installation metadata. The core unit suite passed 260 tests; frontend build and translation
|
||||
validation passed. Changes after these runs require the relevant checks again.
|
||||
The full 260-test run used `--test-threads=1`. A parallel run during native database
|
||||
recovery encountered connection resets in two existing RA socket tests; those failures
|
||||
are recorded rather than treated as update failures or hidden by the passing rerun.
|
||||
|
||||
Not yet established: the complete five-mode, base/previous-release Windows matrix;
|
||||
published installer execution against fixtures; actual disk exhaustion and denied writes;
|
||||
database-child termination during table swaps; every individual file mutation checkpoint;
|
||||
operating-system containment of arbitrary external actions. Publication must stay blocked
|
||||
until the required matrix and remaining release invariants have been demonstrated.
|
||||
|
||||
The matrix report now explicitly records fault coverage. Missing mandatory fault classes
|
||||
produce an `incomplete` report and fail the gate, even when every scenario that was executed
|
||||
passed. Disk exhaustion, denied writes, database-child and new-server crashes,
|
||||
network containment and all file-operation phases still require actual evidence. Snapshot
|
||||
corruption guards now have real-runtime coverage. The later backup-metadata hash and
|
||||
backup-retention guards require their own runtime injection checks before release.
|
||||
|
||||
Infrastructure inspection found zero registered repository runners for both projects.
|
||||
The dedicated Windows acceptance runner must be provisioned before these workflows can run.
|
||||
Generated
+2
-2
@@ -1,12 +1,12 @@
|
||||
{
|
||||
"name": "coa-server-manager",
|
||||
"version": "0.6.5",
|
||||
"version": "0.6.6",
|
||||
"lockfileVersion": 3,
|
||||
"requires": true,
|
||||
"packages": {
|
||||
"": {
|
||||
"name": "coa-server-manager",
|
||||
"version": "0.6.5",
|
||||
"version": "0.6.6",
|
||||
"dependencies": {
|
||||
"@tauri-apps/api": "^2.12.0",
|
||||
"@tauri-apps/plugin-dialog": "^2.8.0",
|
||||
|
||||
+1
-1
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"name": "coa-server-manager",
|
||||
"private": true,
|
||||
"version": "0.6.5",
|
||||
"version": "0.6.6",
|
||||
"license": "AGPL-3.0-only",
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
|
||||
@@ -1,3 +0,0 @@
|
||||
[toolchain]
|
||||
channel = "1.98.1"
|
||||
profile = "minimal"
|
||||
+41
-35
@@ -697,28 +697,7 @@ async fn check_update(state: State<'_, AppState>, id: String, source: Option<Str
|
||||
#[tauri::command]
|
||||
fn pending_update(state: State<'_, AppState>, id: String) -> std::result::Result<Option<update::Txn>, UiError> {
|
||||
let root = path_of(&state, &id)?;
|
||||
let dir = meta_dir(&root)?;
|
||||
let latest = update::latest(&dir)?;
|
||||
Ok(update::unfinished(&dir).or_else(|| latest.filter(|t| t.state == update::State::Committed && t.server_stopped)))
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
async fn recover_update(state: State<'_, AppState>, id: String) -> std::result::Result<Option<update::Txn>, UiError> {
|
||||
let root = path_of(&state, &id)?;
|
||||
let _guard = BusyGuard::acquire(&state, &id)?;
|
||||
blocking(move || update::recover(&root, &meta_dir(&root)?)).await.map_err(UiError::from)
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
fn last_update(state: State<'_, AppState>, id: String) -> std::result::Result<Option<update::Txn>, UiError> {
|
||||
let root = path_of(&state, &id)?;
|
||||
Ok(update::latest(&meta_dir(&root)?)?)
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
fn last_update_result(state: State<'_, AppState>, id: String) -> std::result::Result<Option<update::ExecutionResult>, UiError> {
|
||||
let root = path_of(&state, &id)?;
|
||||
Ok(update::last_execution_result(&meta_dir(&root)?)?)
|
||||
Ok(update::pending_checked(&meta_dir(&root)?)?)
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
@@ -728,14 +707,22 @@ async fn apply_update(
|
||||
id: String,
|
||||
source: Option<String>,
|
||||
resolutions: BTreeMap<String, Resolution>,
|
||||
) -> std::result::Result<update::ExecutionResult, UiError> {
|
||||
) -> std::result::Result<update::Outcome, UiError> {
|
||||
let root = path_of(&state, &id)?;
|
||||
let src = update_source(source);
|
||||
let _guard = BusyGuard::acquire(&state, &id)?;
|
||||
blocking(move || {
|
||||
let (dir, _) = install_meta(&root)?;
|
||||
// Files cannot be replaced while the server runs: stop it first (gracefully), like the Stop button.
|
||||
let observed = coa_core::process::observe(&root, &layout::read_ports(&root));
|
||||
if observed.world.state != coa_core::process::ServiceState::Stopped || observed.auth.state != coa_core::process::ServiceState::Stopped || coa_core::multiworld::is_running(&root) {
|
||||
let out = driver::run(&root, Verb::StopAll)?;
|
||||
if !out.ok {
|
||||
return Err(Error::Invalid("The server could not be stopped, so the update was not started.".into()));
|
||||
}
|
||||
}
|
||||
let env = update::RepackEnv { root: &root, meta_dir: &dir };
|
||||
update::execute(
|
||||
update::apply(
|
||||
&update::Params { root: &root, meta_dir: &dir, source: src, trusted_key: coa_core::signing::EMBEDDED_PUBLIC_KEY, cancel: Cancel::default(), resolutions, env: &env, fail_after_ops: None },
|
||||
&|step, percent| {
|
||||
let _ = app.emit("update-progress", serde_json::json!({ "step": step, "percent": percent }));
|
||||
@@ -1262,6 +1249,7 @@ async fn play(state: State<'_, AppState>, id: String) -> std::result::Result<Dri
|
||||
struct FriendsStatus {
|
||||
settings: coa_core::friends::Settings,
|
||||
lan_ip: Option<String>,
|
||||
lan_addresses: Vec<coa_core::net::LanAddress>,
|
||||
exposure: Vec<coa_core::net::Exposure>,
|
||||
/// The configuration lets other computers reach the login and world servers.
|
||||
servers_open: bool,
|
||||
@@ -1278,10 +1266,9 @@ struct FriendsStatus {
|
||||
#[tauri::command]
|
||||
fn open_link(url: String) -> std::result::Result<(), UiError> {
|
||||
const ALLOWED: &[&str] = &["https://tailscale.com/", "https://login.tailscale.com/", "https://portforward.com/", "https://github.com/Corfirean/"];
|
||||
// A prefilled "new issue" page of this project: the address must be exactly that page, and its query may carry
|
||||
// `&` between the (percent-encoded) title and text.
|
||||
const NEW_ISSUE: &str = "https://github.com/Corfirean/coa-server-manager/issues/new";
|
||||
let issue = url == NEW_ISSUE || url.starts_with(&format!("{NEW_ISSUE}?"));
|
||||
// A prefilled "new issue" page of one of the places a report can go (the Manager, Companions, SQUID Playerbots): the
|
||||
// address must be exactly that page, and its query may carry `&` between the (percent-encoded) title and text.
|
||||
let issue = coa_core::report::is_new_issue_url(&url);
|
||||
let chars_ok = url.chars().all(|c| c.is_ascii_alphanumeric() || "/:._-?=#%".contains(c) || (issue && c == '&'));
|
||||
// the GitHub page of a module that is in the bundled catalog (some are not ours)
|
||||
let catalog = coa_core::modules::catalog().iter().any(|e| e.repo == url);
|
||||
@@ -1299,6 +1286,16 @@ struct ReportContext {
|
||||
/// "new" for a server the Manager installed, "imported" for one that was added.
|
||||
install_kind: String,
|
||||
server_version: Option<String>,
|
||||
/// Where the form should start: the bot system that is switched on, else the Manager.
|
||||
suggested_target: String,
|
||||
/// The release of whichever bot system is on, for a report that goes to its repository.
|
||||
bots_version: Option<String>,
|
||||
}
|
||||
|
||||
/// The places a report can go, each with its GitHub repository.
|
||||
#[tauri::command]
|
||||
fn report_targets() -> Vec<coa_core::report::Target> {
|
||||
coa_core::report::targets()
|
||||
}
|
||||
|
||||
/// "Windows 11 (build 26200)" from `ver`; empty if it cannot be read.
|
||||
@@ -1325,11 +1322,15 @@ async fn report_context(state: State<'_, AppState>, id: String) -> std::result::
|
||||
let root = path_of(&state, &id)?;
|
||||
blocking(move || {
|
||||
let (_, meta) = install_meta(&root)?;
|
||||
let bots = coa_core::report::bots(&root);
|
||||
let companions = [meta.bots.version.clone(), meta.bots.commit.as_ref().map(|c| c.chars().take(8).collect())].into_iter().flatten().collect::<Vec<String>>().join(" · ");
|
||||
Ok(ReportContext {
|
||||
manager_version: coa_core::MANAGER_VERSION.to_string(),
|
||||
windows: windows_version(),
|
||||
install_kind: if meta.kind == coa_core::registry::InstallKind::New { "new".into() } else { "imported".into() },
|
||||
server_version: meta.core.version.clone(),
|
||||
suggested_target: bots.suggested.to_string(),
|
||||
bots_version: if bots.suggested == "squid" { bots.squid_version } else if bots.suggested == "companions" && !companions.is_empty() { Some(companions) } else { None },
|
||||
})
|
||||
})
|
||||
.await
|
||||
@@ -1341,9 +1342,11 @@ async fn friends_status(state: State<'_, AppState>, id: String) -> std::result::
|
||||
blocking(move || {
|
||||
let meta = meta_dir(&root)?;
|
||||
let ports = layout::read_ports(&root);
|
||||
let automatic = coa_core::net::lan_ip().filter(|ip| coa_core::net::is_lan_address(*ip));
|
||||
Ok(FriendsStatus {
|
||||
settings: coa_core::friends::load(&meta),
|
||||
lan_ip: coa_core::net::lan_ip().map(|a| a.to_string()),
|
||||
lan_ip: automatic.map(|a| a.to_string()),
|
||||
lan_addresses: coa_core::net::lan_addresses(automatic).unwrap_or_default(),
|
||||
exposure: coa_core::net::exposure(&ports),
|
||||
servers_open: coa_core::friends::bind_is_open(&root),
|
||||
firewall: coa_core::firewall::status(),
|
||||
@@ -1396,9 +1399,10 @@ async fn friends_enable(
|
||||
id: String,
|
||||
mode: coa_core::friends::Mode,
|
||||
host: Option<String>,
|
||||
lan_address_override: Option<String>,
|
||||
use_upnp: bool,
|
||||
) -> std::result::Result<FriendsResult, UiError> {
|
||||
use coa_core::friends::{self, Mode, Settings};
|
||||
use coa_core::friends::{self, Mode};
|
||||
let root = path_of(&state, &id)?;
|
||||
let _guard = BusyGuard::acquire(&state, &id)?;
|
||||
blocking(move || {
|
||||
@@ -1409,7 +1413,7 @@ async fn friends_enable(
|
||||
let secondary = realms.secondary_world_port.filter(|_| realms.simultaneous);
|
||||
let host = match mode {
|
||||
Mode::Local => "127.0.0.1".to_string(),
|
||||
Mode::Lan => coa_core::net::lan_ip().ok_or_else(|| Error::Invalid("This computer has no network address.".into()))?.to_string(),
|
||||
Mode::Lan => coa_core::net::resolve_lan_host(lan_address_override.as_deref(), coa_core::net::lan_ip())?,
|
||||
Mode::Direct => host.filter(|h| !h.is_empty()).ok_or_else(|| Error::Invalid("Check your connection first to learn your public address.".into()))?,
|
||||
Mode::Private => coa_core::net::tailscale().ip.ok_or_else(|| Error::Invalid("Tailscale is not connected. Install it, sign in, then try again.".into()))?,
|
||||
};
|
||||
@@ -1430,7 +1434,9 @@ async fn friends_enable(
|
||||
None => note = Some("Your router does not support automatic setup; forward the two game ports by hand or use the private network.".to_string()),
|
||||
}
|
||||
}
|
||||
friends::save(&meta, &Settings { mode, host: Some(host.clone()) })?;
|
||||
let mut settings = friends::load(&meta);
|
||||
settings.select_mode(mode, host.clone(), lan_address_override);
|
||||
friends::save(&meta, &settings)?;
|
||||
let running = coa_core::process::observe(&root, &ports).world.state == coa_core::process::ServiceState::Running;
|
||||
if running {
|
||||
friends::apply_realm_address(&root, &host)?;
|
||||
@@ -1483,6 +1489,8 @@ async fn export_diagnostics(state: State<'_, AppState>, id: String) -> std::resu
|
||||
let report = coa_core::diag::run(&root, &meta);
|
||||
let out = coa_core::diag::desktop_or_temp().join(format!("CoA-Diagnostics-{}.zip", coa_core::diag::stamp()));
|
||||
coa_core::diag::export_package(&root, &dir, &data_dir().join("logs").join("manager.log"), &meta, &report, &out)?;
|
||||
// Show the file in its folder so nobody has to look for it; failing to open the folder is not a failure.
|
||||
let _ = tauri_plugin_opener::reveal_item_in_dir(&out);
|
||||
Ok(out.to_string_lossy().into_owned())
|
||||
})
|
||||
.await
|
||||
@@ -1582,9 +1590,6 @@ pub fn run() {
|
||||
create_account,
|
||||
check_update,
|
||||
pending_update,
|
||||
recover_update,
|
||||
last_update,
|
||||
last_update_result,
|
||||
apply_update,
|
||||
rollback_update,
|
||||
retry_update_validation,
|
||||
@@ -1595,6 +1600,7 @@ pub fn run() {
|
||||
companions_delete_all,
|
||||
companions_despawn_some,
|
||||
open_link,
|
||||
report_targets,
|
||||
companion_sizes,
|
||||
add_companions,
|
||||
remote_connection,
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"$schema": "https://schema.tauri.app/config/2",
|
||||
"productName": "CoA Server Manager",
|
||||
"version": "0.6.5",
|
||||
"version": "0.6.6",
|
||||
"identifier": "com.coa.servermanager",
|
||||
"build": {
|
||||
"beforeDevCommand": "npm run dev",
|
||||
|
||||
+4
-4
@@ -46,9 +46,8 @@ export {};
|
||||
if(cmd==="preview_preset"){const a=args;const sc=a.scope==="server"?serverSchema:botsSchema;const pr=(a.scope==="server"?serverPresets:botsPresets).presets as any[];const p=pr.find(x=>x.id===a.preset)??{id:a.preset??"defaults",title:"Recommended defaults",description:"Every setting returns to its default value."};const st=(sc.settings as any[]).filter(x=>x.type==="int"||x.type==="float"||x.type==="enum").slice(0,3);return {id:p.id,title:p.title,description:p.description,changes:st.map(x=>({key:x.key,title:x.title,from:x.default,to:x.type==="enum"?(x.options?.[1]?.value??x.default):(Number(x.default)||1)*2,dangerous:false}))};}
|
||||
if(cmd==="companion_sizes") return {hardware:{cores:16,ram_gb:31,free_ram_gb:12},sizes:[{id:"small",title:"Small",bots:50,warning:null},{id:"medium",title:"Medium",bots:250,warning:null},{id:"large",title:"Large",bots:500,warning:"500 companions may need more CPU and memory than this computer has (8 cores, 16 GB)."}]};
|
||||
if(cmd==="add_companions"){const base=(window as any).__bots??85;(window as any).__target=base+args.count;return {spawned:"queued",created:null,baseline:base};}
|
||||
if(cmd==="check_update") return {from_version:(window as any).__updated?"0.261001.8":"0.260930.5",to_version:"0.261001.8",items:[],conflicts:[],migrations:5,download_bytes:6000000};
|
||||
if(cmd==="apply_update"){const w=window as any;for(let i=1;i<=8;i++){await new Promise((r: any)=>setTimeout(r,700));(w.__handlers?.["update-progress"]??[]).forEach((h: any)=>h({event:"update-progress",id:1,payload:{step:i<4?"Downloading the update":i<7?"Applying the update":"Finishing",percent:i*12}}));}(window as any).__updated=true;return {disposition:"updated",txn:{state:"committed",to_version:"0.261001.8"},message:null};}
|
||||
if(cmd==="pending_update" || cmd==="last_update" || cmd==="last_update_result" || cmd==="recover_update") return null;
|
||||
if(cmd==="check_update") return {from_version:(window as any).__updated?"0.261001.8":"0.260930.5",to_version:"0.261001.8",items:[],conflicts:[],migrations:5,pending_migrations:(window as any).__updated?0:5,download_bytes:6000000};
|
||||
if(cmd==="apply_update"){const w=window as any;for(let i=1;i<=8;i++){await new Promise((r: any)=>setTimeout(r,700));(w.__handlers?.["update-progress"]??[]).forEach((h: any)=>h({event:"update-progress",id:1,payload:{step:i<4?"Downloading the update":i<7?"Applying the update":"Finishing",percent:i*12}}));}(window as any).__updated=true;return {txn:{state:"committed",to_version:"0.261001.8"},migrations:null};}
|
||||
if(cmd==="get_population"){if(!running) return null;let b=(window as any).__bots??85;const t=(window as any).__target??0;if(t>b){b=Math.min(t,b+25);(window as any).__bots=b;}return {online_total:b,bots_online:Math.max(0,b-7),players_online:0,bots_total:b};}
|
||||
if(cmd==="get_performance") return running?{mean_ms:14,median_ms:15,p95_ms:24,p99_ms:30,max_ms:61,ticks_per_sec:71.4}:null;
|
||||
if(cmd==="run_diagnostics") return {problems:2,checks:[{id:"files",title:"Server files",level:"ok",detail:"All expected server parts were found."},{id:"world",title:"World server",level:"warn",detail:"Not running."},{id:"disk",title:"Free disk space",level:"warn",detail:"Only 3 GB free; backups and updates need room."},{id:"exposure",title:"Private services",level:"ok",detail:"Database and server console are not reachable from the network."}]};
|
||||
@@ -88,7 +87,8 @@ export {};
|
||||
return (S[args.module]??[]).map(s => ({...s, value: moduleEdits[args.module]?.[s.key] ?? s.value}));
|
||||
}
|
||||
if(cmd==="module_save_settings") { moduleEdits[args.module] = {...moduleEdits[args.module], ...args.changes}; return Object.keys(args.changes); }
|
||||
if(cmd==="report_context") return {manager_version:"0.3.1",windows:"Windows 11 (build 26200)",install_kind:"new",server_version:"0.261001.10"};
|
||||
if(cmd==="report_context") return {manager_version:"0.3.1",windows:"Windows 11 (build 26200)",install_kind:"new",server_version:"0.261001.10",suggested_target:"companions",bots_version:"0.2.1 · 1a2b3c4d"};
|
||||
if(cmd==="report_targets") return [{id:"manager",repo:"Corfirean/coa-server-manager",ours:true},{id:"companions",repo:"Corfirean/mod-coa-playerbots",ours:true},{id:"squid",repo:"Zyth45/mod-playerbots",ours:false}];
|
||||
if(cmd==="open_link"){(window as any).__lastLink=args.url;return null;}
|
||||
if(cmd==="export_diagnostics") return "C:\\Users\\you\\Desktop\\CoA-Diagnostics-20261001-140000.zip";
|
||||
if(cmd==="install_preflight") return {ok:true,problems:[],free_bytes:210*2**30};
|
||||
|
||||
+24
-4
@@ -371,7 +371,6 @@ const de: Partial<Record<keyof typeof en, string>> = {
|
||||
"upd.backNote": "Die Rückkehr stellt Dateien und Einstellungen wieder her. Wurden Datenbankupdates begonnen, werden auch alle Datenbanken aus der Sicherung vor dem Update wiederhergestellt. Späterer Fortschritt geht verloren.",
|
||||
"upd.goBackTo": "Zu Version {v} zurückkehren",
|
||||
"upd.goBackBefore": "Zur Version vor dem Update zurückkehren",
|
||||
"upd.autoRestored": "Die Aktualisierung ist fehlgeschlagen. Der vorherige Server wurde automatisch wiederhergestellt.",
|
||||
"upd.title": "Server-Updates",
|
||||
"upd.text": "Updates werden auf Echtheit geprüft, vorher gesichert und können rückgängig gemacht werden.",
|
||||
"upd.check": "Nach Updates suchen",
|
||||
@@ -703,9 +702,9 @@ const de: Partial<Record<keyof typeof en, string>> = {
|
||||
"rep.expectedHint": "Beschreibe das erwartete Verhalten.",
|
||||
"rep.steps": "Schritte zum Nachstellen",
|
||||
"rep.attachTitle": "Logs und Screenshots",
|
||||
"rep.attachText": "Erstelle eine Diagnosedatei (Einstellungen und Logs ohne Passwörter und Adressen) und ziehe sie zusammen mit Screenshots oder Videos auf die GitHub-Seite, sobald sie offen ist.",
|
||||
"rep.attachText": "Ein Klick sammelt die Diagnose: Logs des Managers und des Servers, Absturzberichte, Windows-Absturzeinträge und Update-Protokolle, ohne Passwörter und Adressen. Der Ordner mit der Datei wird geöffnet; ziehe die Datei zusammen mit Screenshots oder Videos auf die GitHub-Seite.",
|
||||
"rep.makeFile": "Diagnosedatei erstellen",
|
||||
"rep.fileSaved": "Gespeichert unter {path}. Ziehe diese Datei in das GitHub-Issue.",
|
||||
"rep.fileSaved": "Gespeichert unter {path}. Der Ordner wurde geöffnet. Ziehe diese Datei in das GitHub-Issue.",
|
||||
"rep.privacy": "Bitte entferne Passwörter, Tokens, private IP-Angaben und andere sensible Daten, bevor du Logs veröffentlichst.",
|
||||
"rep.open": "Bericht auf GitHub öffnen",
|
||||
"rep.copy": "Text kopieren",
|
||||
@@ -715,6 +714,17 @@ const de: Partial<Record<keyof typeof en, string>> = {
|
||||
"rep.opened": "GitHub wurde im Browser geöffnet. Prüfe den Text, hänge Dateien an und klicke auf „Submit new issue“.",
|
||||
"rep.openedLong": "Der Bericht ist für einen Link zu lang und wurde deshalb in die Zwischenablage kopiert. GitHub ist geöffnet: Füge ihn (Strg+V) in die Beschreibung ein, hänge Dateien an und klicke auf „Submit new issue“.",
|
||||
"rep.copied": "In die Zwischenablage kopiert.",
|
||||
"rep.targetTitle": "Worum geht es bei dem Problem?",
|
||||
"rep.target.manager": "CoA Server Manager, der Server oder andere Module",
|
||||
"rep.target.companions": "CoA Companions (Bots und das CoABotUI-Addon)",
|
||||
"rep.target.squid": "SQUID Playerbots",
|
||||
"rep.targetPublic": "Der Bericht wird öffentlich auf GitHub in {repo} veröffentlicht.",
|
||||
"rep.botsVersion": "Bot-Version",
|
||||
"rep.withDiag": "Diagnose für mich sammeln (empfohlen)",
|
||||
"rep.collectOpen": "Diagnose sammeln und Bericht öffnen",
|
||||
"rep.collecting": "Diagnose wird gesammelt…",
|
||||
"overview.reportHint": "Ein Dienst wurde von selbst beendet?",
|
||||
"overview.reportBtn": "Diagnose sammeln und melden",
|
||||
|
||||
// Realmlist switcher and modules page
|
||||
"realm.profileLabel": "Realm",
|
||||
@@ -752,7 +762,9 @@ const de: Partial<Record<keyof typeof en, string>> = {
|
||||
"mod.noSettings": "Keine weiteren Einstellungen. Verwende den Modulschalter oben.",
|
||||
"err.bot_modules_conflict.title": "Zwei Bot-Module sind aktiviert",
|
||||
"err.bot_modules_conflict.message": "Deaktiviere CoA Companions oder SQUID Playerbots unter Module vor dem Serverstart.",
|
||||
"mod.ahbot.setup": "GUID eines separaten Auktionscharakters eintragen, Verkäufer und Modul aktivieren. Der Charakter muss offline sein. Der CoA-Filter nutzt Beute-, Händler- und Berufstabellen; Stufengrenzen gelten zusätzlich. Erfordert einen Serverbuild mit CoA-Auktionsfilter.",
|
||||
"mod.ahbot.setup": "Modul und Verkäufer aktivieren. Der Server legt beim ersten Start selbst einen Auktionscharakter an (Konto AHBOT), eine GUID ist nicht nötig. Ein Charakter bietet in den Auktionshäusern beider Fraktionen an. Der CoA-Filter nutzt Beute-, Händler- und Berufstabellen; Stufengrenzen gelten zusätzlich. Erfordert einen Serverbuild mit CoA-Auktionsfilter und automatischem Auktionscharakter.",
|
||||
"mod.enchanter.add": "Verzauberer platzieren: Stellt euch an die gewünschte Stelle und gebt .npc add 601015 ein",
|
||||
"mod.enchanter.remove": "Verzauberer entfernen: Ziel auf den NPC setzen und .npc delete eingeben",
|
||||
"mod.ahbot.allSettings": "Alle Auktionseinstellungen",
|
||||
"mod.title": "Module",
|
||||
"mod.intro": "Zusatzfunktionen, die im Server eingebaut sind. Schalte die gewünschten ein oder aus, öffne ihre GitHub-Seite oder ändere ihre Einstellungen.",
|
||||
@@ -817,6 +829,14 @@ const de: Partial<Record<keyof typeof en, string>> = {
|
||||
"upd.current": "Du bist auf dem neuesten Stand (Version {v}).",
|
||||
"client.job.checking": "Client wird geprüft…",
|
||||
"client.job.updating": "Client wird aktualisiert",
|
||||
"fr.lan.address": "Netzwerkadresse",
|
||||
"fr.lan.automatic": "Automatisch",
|
||||
"fr.lan.default": "Standard",
|
||||
"fr.lan.custom": "Eigene Adresse…",
|
||||
"fr.lan.customIpv4": "Eigene IPv4-Adresse",
|
||||
"fr.lan.unavailable": "Ausgewählte Adresse nicht verfügbar",
|
||||
"fr.lan.unavailableText": "Die ausgewählte Adresse ist derzeit keinem erkannten lokalen Netzwerkadapter zugewiesen. Wählen Sie eine andere Adresse oder Automatisch, oder behalten Sie diese Adresse bewusst bei.",
|
||||
"fr.lan.invalid": "Ungültige IPv4-Adresse",
|
||||
};
|
||||
|
||||
export default de;
|
||||
+24
-4
@@ -404,7 +404,6 @@ const en = {
|
||||
"upd.backNote": "Going back restores files and settings. If database updates started, it also restores all databases to the backup taken before the update. Later progress will be lost.",
|
||||
"upd.goBackTo": "Go back to version {v}",
|
||||
"upd.goBackBefore": "Go back to the version before the update",
|
||||
"upd.autoRestored": "The update failed validation. Your previous server was restored automatically.",
|
||||
"upd.title": "Server updates",
|
||||
"upd.text": "Updates are checked for authenticity, backed up first, and can be undone.",
|
||||
"upd.check": "Check for updates",
|
||||
@@ -736,9 +735,9 @@ const en = {
|
||||
"rep.expectedHint": "Describe the expected behaviour.",
|
||||
"rep.steps": "Steps to reproduce",
|
||||
"rep.attachTitle": "Logs and screenshots",
|
||||
"rep.attachText": "Create a diagnostics file (settings and logs with passwords and addresses removed) and drag it, together with any screenshot or video, into the GitHub page once it is open.",
|
||||
"rep.attachText": "One click collects the diagnostics: the Manager's and the server's logs, crash reports, Windows crash records and update journals, with passwords and addresses removed. The file's folder opens; drag the file, together with any screenshot or video, into the GitHub page.",
|
||||
"rep.makeFile": "Create the diagnostics file",
|
||||
"rep.fileSaved": "Saved to {path}. Drag this file into the GitHub issue.",
|
||||
"rep.fileSaved": "Saved to {path}. The folder was opened. Drag this file into the GitHub issue.",
|
||||
"rep.privacy": "Please remove passwords, tokens, private IP information or other sensitive data before posting logs.",
|
||||
"rep.open": "Open the report on GitHub",
|
||||
"rep.copy": "Copy the text",
|
||||
@@ -748,6 +747,17 @@ const en = {
|
||||
"rep.opened": "GitHub was opened in your browser. Check the text, attach files and press Submit new issue.",
|
||||
"rep.openedLong": "The report is too long for a link, so it was copied to the clipboard. GitHub is open: paste it (Ctrl+V) into the description, attach files and press Submit new issue.",
|
||||
"rep.copied": "Copied to the clipboard.",
|
||||
"rep.targetTitle": "What is the problem about?",
|
||||
"rep.target.manager": "CoA Server Manager, the server or other modules",
|
||||
"rep.target.companions": "CoA Companions (bots and the CoABotUI addon)",
|
||||
"rep.target.squid": "SQUID Playerbots",
|
||||
"rep.targetPublic": "The report will be public on GitHub in {repo}.",
|
||||
"rep.botsVersion": "Bot release",
|
||||
"rep.withDiag": "Collect the diagnostics for me (recommended)",
|
||||
"rep.collectOpen": "Collect diagnostics and open the report",
|
||||
"rep.collecting": "Collecting diagnostics…",
|
||||
"overview.reportHint": "A service stopped on its own?",
|
||||
"overview.reportBtn": "Collect diagnostics and report",
|
||||
|
||||
// Realmlist switcher and modules page
|
||||
"realm.label": "Realm",
|
||||
@@ -771,7 +781,9 @@ const en = {
|
||||
"mod.ahbot.weightsHint": "Relative weights, not percentages. 0 excludes a quality; larger values make it more frequent. If all defaults are zero, enabling selects common quality. Other item filters still apply.",
|
||||
"mod.ahbot.noTypes": "All types are disabled. The seller has no types to choose for new listings.",
|
||||
"mod.noSettings": "There are no additional settings. Use the module switch above.",
|
||||
"mod.ahbot.setup": "Enter a dedicated auction character GUID, enable the seller and the module. Keep that character offline. The CoA filter selects items from loot tables, vendors and professions; level restrictions also apply. Requires a server build with the CoA auction filter.",
|
||||
"mod.ahbot.setup": "Turn on the module and the seller. The server creates its own auction character (account AHBOT) the first time it starts, so no GUID is needed. One character lists in both factions' auction houses. The CoA filter selects items from loot tables, vendors and professions; level restrictions also apply. Requires a server build with the CoA auction filter and the automatic auction character.",
|
||||
"mod.enchanter.add": "Place the enchanter: stand where you want him and enter .npc add 601015",
|
||||
"mod.enchanter.remove": "Remove the enchanter: target him and enter .npc delete",
|
||||
"mod.ahbot.allSettings": "All settings",
|
||||
"err.bot_modules_conflict.title": "Two bot modules are enabled",
|
||||
"err.bot_modules_conflict.message": "Disable CoA Companions or SQUID Playerbots in Modules before starting the server.",
|
||||
@@ -838,6 +850,14 @@ const en = {
|
||||
"upd.current": "You are up to date (version {v}).",
|
||||
"client.job.checking": "Checking the client…",
|
||||
"client.job.updating": "Updating the client",
|
||||
"fr.lan.address": "Network address",
|
||||
"fr.lan.automatic": "Automatic",
|
||||
"fr.lan.default": "Default",
|
||||
"fr.lan.custom": "Custom address…",
|
||||
"fr.lan.customIpv4": "Custom IPv4 address",
|
||||
"fr.lan.unavailable": "Selected address unavailable",
|
||||
"fr.lan.unavailableText": "The selected address is not currently assigned to a detected local interface. Choose another address or switch to Automatic, or keep this address intentionally.",
|
||||
"fr.lan.invalid": "Invalid IPv4 address",
|
||||
} as const;
|
||||
|
||||
export default en;
|
||||
+24
-4
@@ -371,7 +371,6 @@ const es: Partial<Record<keyof typeof en, string>> = {
|
||||
"upd.backNote": "Volver restaura los archivos y los ajustes. Si comenzaron las actualizaciones de las bases de datos, también se restauran todas las bases desde la copia anterior a la actualización. Se perderá el progreso posterior.",
|
||||
"upd.goBackTo": "Volver a la versión {v}",
|
||||
"upd.goBackBefore": "Volver a la versión anterior a la actualización",
|
||||
"upd.autoRestored": "La actualización falló. El servidor anterior se restauró automáticamente.",
|
||||
"upd.title": "Actualizaciones del servidor",
|
||||
"upd.text": "Las actualizaciones se comprueban, se respaldan antes y se pueden deshacer.",
|
||||
"upd.check": "Buscar actualizaciones",
|
||||
@@ -703,9 +702,9 @@ const es: Partial<Record<keyof typeof en, string>> = {
|
||||
"rep.expectedHint": "Describe el comportamiento esperado.",
|
||||
"rep.steps": "Pasos para reproducirlo",
|
||||
"rep.attachTitle": "Registros y capturas",
|
||||
"rep.attachText": "Crea un archivo de diagnóstico (ajustes y registros sin contraseñas ni direcciones) y arrástralo, junto con capturas o vídeos, a la página de GitHub cuando se abra.",
|
||||
"rep.attachText": "Un clic reúne el diagnóstico: registros del Manager y del servidor, informes de fallos, registros de fallos de Windows y diarios de actualización, sin contraseñas ni direcciones. Se abre la carpeta del archivo; arrástralo, junto con capturas o vídeos, a la página de GitHub.",
|
||||
"rep.makeFile": "Crear el archivo de diagnóstico",
|
||||
"rep.fileSaved": "Guardado en {path}. Arrastra este archivo al issue de GitHub.",
|
||||
"rep.fileSaved": "Guardado en {path}. Se abrió la carpeta. Arrastra este archivo al issue de GitHub.",
|
||||
"rep.privacy": "Elimina contraseñas, tokens, información de IP privada y otros datos sensibles antes de publicar registros.",
|
||||
"rep.open": "Abrir el informe en GitHub",
|
||||
"rep.copy": "Copiar el texto",
|
||||
@@ -715,6 +714,17 @@ const es: Partial<Record<keyof typeof en, string>> = {
|
||||
"rep.opened": "GitHub se abrió en tu navegador. Revisa el texto, adjunta archivos y pulsa «Submit new issue».",
|
||||
"rep.openedLong": "El informe es demasiado largo para un enlace, así que se copió al portapapeles. GitHub está abierto: pégalo (Ctrl+V) en la descripción, adjunta archivos y pulsa «Submit new issue».",
|
||||
"rep.copied": "Copiado al portapapeles.",
|
||||
"rep.targetTitle": "¿Sobre qué es el problema?",
|
||||
"rep.target.manager": "CoA Server Manager, el servidor u otros módulos",
|
||||
"rep.target.companions": "CoA Companions (bots y el addon CoABotUI)",
|
||||
"rep.target.squid": "SQUID Playerbots",
|
||||
"rep.targetPublic": "El informe será público en GitHub, en {repo}.",
|
||||
"rep.botsVersion": "Versión de los bots",
|
||||
"rep.withDiag": "Reunir el diagnóstico por mí (recomendado)",
|
||||
"rep.collectOpen": "Reunir el diagnóstico y abrir el informe",
|
||||
"rep.collecting": "Reuniendo el diagnóstico…",
|
||||
"overview.reportHint": "¿Un servicio se detuvo solo?",
|
||||
"overview.reportBtn": "Reunir el diagnóstico y avisar",
|
||||
|
||||
// Realmlist switcher and modules page
|
||||
"realm.profileLabel": "Reino",
|
||||
@@ -752,7 +762,9 @@ const es: Partial<Record<keyof typeof en, string>> = {
|
||||
"mod.noSettings": "No hay ajustes adicionales. Usa el interruptor del módulo de arriba.",
|
||||
"err.bot_modules_conflict.title": "Hay dos módulos de bots activos",
|
||||
"err.bot_modules_conflict.message": "Desactiva CoA Companions o SQUID Playerbots en Módulos antes de iniciar el servidor.",
|
||||
"mod.ahbot.setup": "Indica el GUID de un personaje dedicado a subastas y activa vendedor y módulo. El personaje debe estar desconectado. El filtro CoA usa botín, vendedores y profesiones; los límites de nivel se aplican además. Requiere un servidor con filtro de subastas CoA.",
|
||||
"mod.ahbot.setup": "Activa el módulo y el vendedor. El servidor crea por sí mismo un personaje de subastas (cuenta AHBOT) en el primer arranque, no hace falta GUID. Un solo personaje publica en las casas de subastas de ambas facciones. El filtro CoA usa botín, vendedores y profesiones; los límites de nivel se aplican además. Requiere un servidor con filtro de subastas CoA y personaje de subastas automático.",
|
||||
"mod.enchanter.add": "Colocar al encantador: ponte donde quieras y escribe .npc add 601015",
|
||||
"mod.enchanter.remove": "Quitar al encantador: selecciona al PNJ y escribe .npc delete",
|
||||
"mod.ahbot.allSettings": "Todos los ajustes de subastas",
|
||||
"mod.title": "Módulos",
|
||||
"mod.intro": "Funciones adicionales integradas en el servidor. Activa o desactiva las que quieras, abre su página de GitHub o cambia sus ajustes.",
|
||||
@@ -817,6 +829,14 @@ const es: Partial<Record<keyof typeof en, string>> = {
|
||||
"upd.current": "Estás al día (versión {v}).",
|
||||
"client.job.checking": "Comprobando el cliente…",
|
||||
"client.job.updating": "Actualizando el cliente",
|
||||
"fr.lan.address": "Dirección de red",
|
||||
"fr.lan.automatic": "Automática",
|
||||
"fr.lan.default": "Predeterminada",
|
||||
"fr.lan.custom": "Dirección personalizada…",
|
||||
"fr.lan.customIpv4": "Dirección IPv4 personalizada",
|
||||
"fr.lan.unavailable": "Dirección seleccionada no disponible",
|
||||
"fr.lan.unavailableText": "La dirección seleccionada no está asignada actualmente a ninguna interfaz local detectada. Elige otra dirección o Automática, o conserva esta dirección si así lo deseas.",
|
||||
"fr.lan.invalid": "Dirección IPv4 no válida",
|
||||
};
|
||||
|
||||
export default es;
|
||||
+24
-4
@@ -371,7 +371,6 @@ const fr: Partial<Record<keyof typeof en, string>> = {
|
||||
"upd.backNote": "Le retour restaure les fichiers et les paramètres. Si la mise à jour des bases a commencé, toutes les bases sont aussi restaurées depuis la sauvegarde précédant la mise à jour. La progression ultérieure sera perdue.",
|
||||
"upd.goBackTo": "Revenir à la version {v}",
|
||||
"upd.goBackBefore": "Revenir à la version d’avant la mise à jour",
|
||||
"upd.autoRestored": "La mise à jour a échoué. Le serveur précédent a été restauré automatiquement.",
|
||||
"upd.title": "Mises à jour du serveur",
|
||||
"upd.text": "Les mises à jour sont vérifiées, sauvegardées au préalable et peuvent être annulées.",
|
||||
"upd.check": "Rechercher des mises à jour",
|
||||
@@ -703,9 +702,9 @@ const fr: Partial<Record<keyof typeof en, string>> = {
|
||||
"rep.expectedHint": "Décrivez le comportement attendu.",
|
||||
"rep.steps": "Étapes pour reproduire",
|
||||
"rep.attachTitle": "Journaux et captures d’écran",
|
||||
"rep.attachText": "Créez un fichier de diagnostic (réglages et journaux sans mots de passe ni adresses) et glissez-le, avec vos captures ou vidéos, sur la page GitHub une fois ouverte.",
|
||||
"rep.attachText": "Un clic rassemble le diagnostic : journaux du Manager et du serveur, rapports de plantage, enregistrements de plantage de Windows et journaux de mise à jour, sans mots de passe ni adresses. Le dossier du fichier s’ouvre ; glissez le fichier, avec vos captures ou vidéos, sur la page GitHub.",
|
||||
"rep.makeFile": "Créer le fichier de diagnostic",
|
||||
"rep.fileSaved": "Enregistré dans {path}. Glissez ce fichier dans l’issue GitHub.",
|
||||
"rep.fileSaved": "Enregistré dans {path}. Le dossier a été ouvert. Glissez ce fichier dans l’issue GitHub.",
|
||||
"rep.privacy": "Veuillez retirer les mots de passe, jetons, adresses IP privées et autres données sensibles avant de publier des journaux.",
|
||||
"rep.open": "Ouvrir le rapport sur GitHub",
|
||||
"rep.copy": "Copier le texte",
|
||||
@@ -715,6 +714,17 @@ const fr: Partial<Record<keyof typeof en, string>> = {
|
||||
"rep.opened": "GitHub s’est ouvert dans votre navigateur. Vérifiez le texte, joignez les fichiers et appuyez sur « Submit new issue ».",
|
||||
"rep.openedLong": "Le rapport est trop long pour un lien : il a été copié dans le presse-papiers. GitHub est ouvert : collez-le (Ctrl+V) dans la description, joignez les fichiers et appuyez sur « Submit new issue ».",
|
||||
"rep.copied": "Copié dans le presse-papiers.",
|
||||
"rep.targetTitle": "De quoi parle le problème ?",
|
||||
"rep.target.manager": "CoA Server Manager, le serveur ou d’autres modules",
|
||||
"rep.target.companions": "CoA Companions (bots et addon CoABotUI)",
|
||||
"rep.target.squid": "SQUID Playerbots",
|
||||
"rep.targetPublic": "Le rapport sera public sur GitHub dans {repo}.",
|
||||
"rep.botsVersion": "Version des bots",
|
||||
"rep.withDiag": "Rassembler le diagnostic pour moi (recommandé)",
|
||||
"rep.collectOpen": "Rassembler le diagnostic et ouvrir le rapport",
|
||||
"rep.collecting": "Collecte du diagnostic…",
|
||||
"overview.reportHint": "Un service s’est arrêté tout seul ?",
|
||||
"overview.reportBtn": "Rassembler le diagnostic et signaler",
|
||||
|
||||
// Realmlist switcher and modules page
|
||||
"realm.profileLabel": "Royaume",
|
||||
@@ -752,7 +762,9 @@ const fr: Partial<Record<keyof typeof en, string>> = {
|
||||
"mod.noSettings": "Aucun réglage supplémentaire. Utilisez l’interrupteur du module ci-dessus.",
|
||||
"err.bot_modules_conflict.title": "Deux modules de bots sont activés",
|
||||
"err.bot_modules_conflict.message": "Désactivez CoA Companions ou SQUID Playerbots dans Modules avant de démarrer le serveur.",
|
||||
"mod.ahbot.setup": "Indiquez le GUID d’un personnage dédié aux enchères, activez le vendeur et le module. Le personnage doit être hors ligne. Le filtre CoA utilise le butin, les vendeurs et les métiers ; les limites de niveau s’ajoutent. Nécessite un serveur avec le filtre d’enchères CoA.",
|
||||
"mod.ahbot.setup": "Activez le module et le vendeur. Le serveur crée lui-même un personnage d’enchères (compte AHBOT) au premier démarrage, aucun GUID n’est nécessaire. Un seul personnage met en vente dans les hôtels des ventes des deux factions. Le filtre CoA utilise le butin, les vendeurs et les métiers ; les limites de niveau s’ajoutent. Nécessite un serveur avec le filtre d’enchères CoA et le personnage d’enchères automatique.",
|
||||
"mod.enchanter.add": "Placer l’enchanteur : placez-vous à l’endroit voulu et saisissez .npc add 601015",
|
||||
"mod.enchanter.remove": "Retirer l’enchanteur : ciblez le PNJ et saisissez .npc delete",
|
||||
"mod.ahbot.allSettings": "Tous les réglages d’enchères",
|
||||
"mod.title": "Modules",
|
||||
"mod.intro": "Fonctions supplémentaires intégrées au serveur. Activez ou désactivez celles que vous voulez, ouvrez leur page GitHub ou modifiez leurs réglages.",
|
||||
@@ -817,6 +829,14 @@ const fr: Partial<Record<keyof typeof en, string>> = {
|
||||
"upd.current": "Vous êtes à jour (version {v}).",
|
||||
"client.job.checking": "Vérification du client…",
|
||||
"client.job.updating": "Mise à jour du client",
|
||||
"fr.lan.address": "Adresse réseau",
|
||||
"fr.lan.automatic": "Automatique",
|
||||
"fr.lan.default": "Par défaut",
|
||||
"fr.lan.custom": "Adresse personnalisée…",
|
||||
"fr.lan.customIpv4": "Adresse IPv4 personnalisée",
|
||||
"fr.lan.unavailable": "Adresse sélectionnée indisponible",
|
||||
"fr.lan.unavailableText": "Cette adresse n’est actuellement attribuée à aucune interface locale détectée. Choisissez une autre adresse ou le mode Automatique, ou conservez volontairement cette adresse.",
|
||||
"fr.lan.invalid": "Adresse IPv4 non valide",
|
||||
};
|
||||
|
||||
export default fr;
|
||||
+24
-4
@@ -402,7 +402,6 @@ const ru: Partial<Record<keyof typeof en, string>> = {
|
||||
"upd.backNote": "Возврат восстанавливает файлы и настройки. Если обновление баз уже началось, все базы также восстанавливаются из копии перед обновлением. Более поздний прогресс будет потерян.",
|
||||
"upd.goBackTo": "Вернуться к версии {v}",
|
||||
"upd.goBackBefore": "Вернуться к версии до обновления",
|
||||
"upd.autoRestored": "Обновление не прошло проверку. Прежний сервер автоматически восстановлен.",
|
||||
"upd.title": "Обновления сервера",
|
||||
"upd.text": "Подлинность обновлений проверяется, перед ними делается резервная копия, и их можно отменить.",
|
||||
"upd.check": "Проверить обновления",
|
||||
@@ -734,9 +733,9 @@ const ru: Partial<Record<keyof typeof en, string>> = {
|
||||
"rep.expectedHint": "Опишите ожидаемое поведение.",
|
||||
"rep.steps": "Как воспроизвести",
|
||||
"rep.attachTitle": "Логи и скриншоты",
|
||||
"rep.attachText": "Создайте файл диагностики (настройки и логи без паролей и адресов) и перетащите его вместе со скриншотами или видео на страницу GitHub, когда она откроется.",
|
||||
"rep.attachText": "Диагностика собирается одним нажатием: логи менеджера и сервера, отчёты о падениях, записи Windows о сбоях и журналы обновлений, без паролей и адресов. Откроется папка с файлом; перетащите его вместе со скриншотами или видео на страницу GitHub.",
|
||||
"rep.makeFile": "Создать файл диагностики",
|
||||
"rep.fileSaved": "Сохранено: {path}. Перетащите этот файл в issue на GitHub.",
|
||||
"rep.fileSaved": "Сохранено: {path}. Папка открыта. Перетащите этот файл в issue на GitHub.",
|
||||
"rep.privacy": "Перед публикацией логов удалите пароли, токены, частные IP-адреса и другие личные данные.",
|
||||
"rep.open": "Открыть отчёт на GitHub",
|
||||
"rep.copy": "Копировать текст",
|
||||
@@ -746,6 +745,17 @@ const ru: Partial<Record<keyof typeof en, string>> = {
|
||||
"rep.opened": "GitHub открыт в браузере. Проверьте текст, прикрепите файлы и нажмите «Submit new issue».",
|
||||
"rep.openedLong": "Отчёт слишком длинный для ссылки, поэтому он скопирован в буфер обмена. GitHub открыт: вставьте текст (Ctrl+V) в описание, прикрепите файлы и нажмите «Submit new issue».",
|
||||
"rep.copied": "Скопировано в буфер обмена.",
|
||||
"rep.targetTitle": "О чём проблема?",
|
||||
"rep.target.manager": "CoA Server Manager, сервер или другие модули",
|
||||
"rep.target.companions": "CoA Companions (боты и аддон CoABotUI)",
|
||||
"rep.target.squid": "SQUID Playerbots",
|
||||
"rep.targetPublic": "Репорт будет публичным на GitHub в {repo}.",
|
||||
"rep.botsVersion": "Версия ботов",
|
||||
"rep.withDiag": "Собрать диагностику за меня (рекомендуется)",
|
||||
"rep.collectOpen": "Собрать диагностику и открыть репорт",
|
||||
"rep.collecting": "Собираю диагностику…",
|
||||
"overview.reportHint": "Служба остановилась сама?",
|
||||
"overview.reportBtn": "Собрать диагностику и сообщить",
|
||||
|
||||
// Realmlist switcher and modules page
|
||||
"realm.label": "Реалм",
|
||||
@@ -769,7 +779,9 @@ const ru: Partial<Record<keyof typeof en, string>> = {
|
||||
"mod.ahbot.weightsHint": "Это относительные веса, а не проценты. 0 исключает качество; большее значение повышает частоту. Если все значения по умолчанию равны нулю, включается обычное качество. Остальные фильтры продолжают действовать.",
|
||||
"mod.ahbot.noTypes": "Все типы отключены. Продавцу не из чего выбирать новые лоты.",
|
||||
"mod.noSettings": "Дополнительных настроек нет. Используйте переключатель модуля выше.",
|
||||
"mod.ahbot.setup": "Укажите GUID отдельного персонажа аукциониста, включите продавца и модуль. Персонаж должен быть офлайн. Фильтр CoA оставляет предметы из таблиц добычи, торговцев и профессий; ограничения уровней применяются дополнительно. Нужна сборка сервера с фильтром аукциона CoA.",
|
||||
"mod.ahbot.setup": "Включите модуль и продавца. Сервер сам создаст персонажа аукциона (аккаунт AHBOT) при первом запуске, GUID вводить не нужно. Один персонаж выставляет лоты в аукционах обеих фракций. Фильтр CoA оставляет предметы из таблиц добычи, торговцев и профессий; ограничения уровней действуют дополнительно. Нужна сборка сервера с фильтром аукциона CoA и автоматическим персонажем аукциона.",
|
||||
"mod.enchanter.add": "Разместить НПС зачарователя: встаньте в нужное место и введите команду .npc add 601015",
|
||||
"mod.enchanter.remove": "Удалить НПС зачарователя: возьмите НПС в цель и введите команду .npc delete",
|
||||
"mod.ahbot.allSettings": "Все настройки",
|
||||
"err.bot_modules_conflict.title": "Включены две системы ботов",
|
||||
"err.bot_modules_conflict.message": "Выключите CoA Companions или SQUID Playerbots в разделе «Модули» перед запуском сервера.",
|
||||
@@ -836,6 +848,14 @@ const ru: Partial<Record<keyof typeof en, string>> = {
|
||||
"upd.current": "У вас последняя версия ({v}).",
|
||||
"client.job.checking": "Проверка клиента…",
|
||||
"client.job.updating": "Обновление клиента",
|
||||
"fr.lan.address": "Сетевой адрес",
|
||||
"fr.lan.automatic": "Автоматически",
|
||||
"fr.lan.default": "По умолчанию",
|
||||
"fr.lan.custom": "Другой адрес…",
|
||||
"fr.lan.customIpv4": "Свой IPv4-адрес",
|
||||
"fr.lan.unavailable": "Выбранный адрес недоступен",
|
||||
"fr.lan.unavailableText": "Выбранный адрес сейчас не назначен обнаруженному сетевому интерфейсу. Выберите другой адрес, переключитесь на автоматический выбор или намеренно сохраните этот адрес.",
|
||||
"fr.lan.invalid": "Некорректный IPv4-адрес",
|
||||
};
|
||||
|
||||
export default ru;
|
||||
+24
-4
@@ -383,7 +383,6 @@ const zh = {
|
||||
"upd.backNote": "回滚将恢复文件和设置。如果数据库更新已开始,所有数据库也将从更新前的备份恢复。之后的进度将丢失。",
|
||||
"upd.goBackTo": "回滚至版本 {v}",
|
||||
"upd.goBackBefore": "回滚至更新前的版本",
|
||||
"upd.autoRestored": "更新验证失败。之前的服务器已自动恢复。",
|
||||
"upd.title": "服务器更新",
|
||||
"upd.text": "更新均经过真实性签名校验,并在执行前自动备份,随时可安全撤销。",
|
||||
"upd.check": "检查更新",
|
||||
@@ -715,9 +714,9 @@ const zh = {
|
||||
"rep.expectedHint": "描述你期望的正常表现。",
|
||||
"rep.steps": "复现步骤",
|
||||
"rep.attachTitle": "日志与截图附件",
|
||||
"rep.attachText": "生成一份诊断包文件(已自动脱敏密码与私有 IP 等敏感信息),并在浏览器打开 GitHub 页面后,将其连同截图或录屏一起拖拽上传。",
|
||||
"rep.attachText": "一键收集诊断信息:管理器与服务器日志、崩溃报告、Windows 崩溃记录和更新日志(已去除密码与地址)。文件所在文件夹会自动打开;请将该文件连同截图或录屏一起拖入 GitHub 页面。",
|
||||
"rep.makeFile": "生成诊断包文件",
|
||||
"rep.fileSaved": "已保存至 {path}。请将该文件拖入 GitHub Issue 中。",
|
||||
"rep.fileSaved": "已保存至 {path}。文件夹已打开。请将该文件拖入 GitHub Issue 中。",
|
||||
"rep.privacy": "上传前请注意检查并移除日志中可能包含的私有密码、Token 或其他敏感隐私信息。",
|
||||
"rep.open": "在 GitHub 上打开报告",
|
||||
"rep.copy": "复制报告文本",
|
||||
@@ -727,6 +726,17 @@ const zh = {
|
||||
"rep.opened": "已在浏览器中打开 GitHub。请检查内容、附上日志文件并点击“Submit new issue”。",
|
||||
"rep.openedLong": "报告内容较长超出 URL 长度限制,已自动复制到剪贴板。请在已打开的 GitHub 页面中按 Ctrl+V 粘贴描述,附上文件后提交。",
|
||||
"rep.copied": "已复制到剪贴板。",
|
||||
"rep.targetTitle": "问题与什么有关?",
|
||||
"rep.target.manager": "CoA Server Manager、服务器或其他模块",
|
||||
"rep.target.companions": "CoA Companions(机器人与 CoABotUI 插件)",
|
||||
"rep.target.squid": "SQUID Playerbots",
|
||||
"rep.targetPublic": "该报告将公开发布在 GitHub 的 {repo}。",
|
||||
"rep.botsVersion": "机器人版本",
|
||||
"rep.withDiag": "替我收集诊断信息(推荐)",
|
||||
"rep.collectOpen": "收集诊断信息并打开报告",
|
||||
"rep.collecting": "正在收集诊断信息…",
|
||||
"overview.reportHint": "某个服务自己停止了?",
|
||||
"overview.reportBtn": "收集诊断信息并反馈",
|
||||
|
||||
// Realmlist switcher and modules page
|
||||
"realm.label": "服务器列表",
|
||||
@@ -752,7 +762,9 @@ const zh = {
|
||||
"mod.noSettings": "没有其他设置,请使用上方模块开关。",
|
||||
"err.bot_modules_conflict.title": "已启用两个机器人模块",
|
||||
"err.bot_modules_conflict.message": "启动服务器前,请在模块中关闭CoA Companions或SQUID Playerbots。",
|
||||
"mod.ahbot.setup": "填写独立拍卖角色的GUID,并启用卖家和模块。角色必须离线。CoA筛选使用掉落、商人和专业物品表,等级限制另行生效。需要包含CoA拍卖筛选的服务器版本。",
|
||||
"mod.ahbot.setup": "启用模块和卖家即可。服务器首次启动时会自动创建拍卖角色(账号AHBOT),无需填写GUID。一个角色即可在双方阵营的拍卖行上架。CoA筛选使用掉落、商人和专业物品表,等级限制另行生效。需要包含CoA拍卖筛选和自动拍卖角色的服务器版本。",
|
||||
"mod.enchanter.add": "放置附魔师NPC:站在想要的位置,输入 .npc add 601015",
|
||||
"mod.enchanter.remove": "删除附魔师NPC:选中该NPC,输入 .npc delete",
|
||||
"mod.ahbot.allSettings": "所有拍卖设置",
|
||||
"mod.title": "模块管理",
|
||||
"mod.intro": "服务器内置的可选扩展特性。可按需开关、访问其 GitHub 页面或调整独立参数。",
|
||||
@@ -819,6 +831,14 @@ const zh = {
|
||||
"client.job.updating": "正在更新游戏客户端",
|
||||
"err.docker_unavailable.title": "Docker 不可用",
|
||||
"err.docker_unavailable.message": "此服务器通过 Docker 运行。请安装并启动 Docker,确保当前用户有权使用它,然后重试。",
|
||||
"fr.lan.address": "网络地址",
|
||||
"fr.lan.automatic": "自动",
|
||||
"fr.lan.default": "默认",
|
||||
"fr.lan.custom": "自定义地址…",
|
||||
"fr.lan.customIpv4": "自定义 IPv4 地址",
|
||||
"fr.lan.unavailable": "所选地址不可用",
|
||||
"fr.lan.unavailableText": "所选地址目前未分配给检测到的本地网络接口。请选择其他地址、切换到自动,或有意保留此地址。",
|
||||
"fr.lan.invalid": "无效的 IPv4 地址",
|
||||
} as const;
|
||||
|
||||
export default zh;
|
||||
+27
-20
@@ -95,12 +95,6 @@ export interface UiError {
|
||||
fields?: FieldError[];
|
||||
}
|
||||
|
||||
export interface UpdateExecutionResult {
|
||||
disposition: "updated" | "rejected" | "restored" | "recovery-required";
|
||||
txn: UpdateTxn | null;
|
||||
message: string | null;
|
||||
}
|
||||
|
||||
export type Scope = "bots" | "server";
|
||||
export type Restart = "runtime" | "world" | "full";
|
||||
export type JsonValue = string | number | boolean;
|
||||
@@ -240,6 +234,19 @@ export interface ReportContext {
|
||||
windows: string;
|
||||
install_kind: "new" | "imported";
|
||||
server_version: string | null;
|
||||
/** where the form starts: the bot system that is switched on, else the Manager */
|
||||
suggested_target: ReportTargetId;
|
||||
/** the release of the bot system that is on */
|
||||
bots_version: string | null;
|
||||
}
|
||||
|
||||
export type ReportTargetId = "manager" | "companions" | "squid";
|
||||
|
||||
/** A place a problem report can go: its GitHub repository as `owner/name`. */
|
||||
export interface ReportTarget {
|
||||
id: ReportTargetId;
|
||||
repo: string;
|
||||
ours: boolean;
|
||||
}
|
||||
|
||||
export interface InstallRequirements {
|
||||
@@ -276,23 +283,18 @@ export interface UpdatePreview {
|
||||
items: UpdatePlanItem[];
|
||||
conflicts: string[];
|
||||
migrations: number;
|
||||
pending_migrations?: number;
|
||||
download_bytes: number;
|
||||
}
|
||||
|
||||
export interface UpdateTxn {
|
||||
id: string;
|
||||
state: "prepared" | "stopping" | "snapshotting" | "trialing" | "applying" | "applied" | "migrating" | "validating" | "committing" | "restoring" | "needs-decision" | "committed" | "rolled-back" | "failed";
|
||||
failure_stage?: UpdateTxn["state"];
|
||||
state: "prepared" | "applying" | "applied" | "needs-decision" | "committed" | "rolled-back" | "failed";
|
||||
from_version: string | null;
|
||||
to_version: string;
|
||||
recovery_point: string | null;
|
||||
databases_started: boolean;
|
||||
message: string | null;
|
||||
outcome?: "updated" | "rejected" | "restored" | "recovery-required" | null;
|
||||
manifest_sha256?: string | null;
|
||||
was_running?: boolean;
|
||||
recovery_verified?: boolean;
|
||||
trial_completed?: boolean;
|
||||
}
|
||||
|
||||
export interface Population {
|
||||
@@ -359,9 +361,16 @@ export interface ClientDownloadCheck {
|
||||
|
||||
export type FriendsMode = "local" | "lan" | "direct" | "private";
|
||||
|
||||
export interface LanAddress {
|
||||
interface: string;
|
||||
address: string;
|
||||
is_default: boolean;
|
||||
}
|
||||
|
||||
export interface FriendsStatus {
|
||||
settings: { mode: FriendsMode; host: string | null };
|
||||
settings: { mode: FriendsMode; host: string | null; lan_address_override: string | null };
|
||||
lan_ip: string | null;
|
||||
lan_addresses: LanAddress[];
|
||||
exposure: { port: number; what: string; reachable_from_network: boolean; listening: boolean }[];
|
||||
servers_open: boolean;
|
||||
firewall: { auth: boolean; world: boolean };
|
||||
@@ -430,6 +439,7 @@ export const api = {
|
||||
allSettings: (id: string) => invoke<AllSetting[]>("all_settings", { id }),
|
||||
allSettingsSave: (id: string, changes: Record<string, string>) => invoke<string[]>("all_settings_save", { id, changes }),
|
||||
reportContext: (id: string) => invoke<ReportContext>("report_context", { id }),
|
||||
reportTargets: () => invoke<ReportTarget[]>("report_targets"),
|
||||
listAccounts: (id: string) => invoke<AccountInfo[]>("list_accounts", { id }),
|
||||
accountSetPassword: (id: string, name: string, password: string) => invoke<void>("account_set_password", { id, name, password }),
|
||||
accountSetAccess: (id: string, name: string, level: number) => invoke<void>("account_set_access", { id, name, level }),
|
||||
@@ -441,11 +451,8 @@ export const api = {
|
||||
invoke<void>("create_account", { id, username, password, administrator }),
|
||||
checkUpdate: (id: string, source?: string) => invoke<UpdatePreview>("check_update", { id, source: source ?? null }),
|
||||
pendingUpdate: (id: string) => invoke<UpdateTxn | null>("pending_update", { id }),
|
||||
lastUpdate: (id: string) => invoke<UpdateTxn | null>("last_update", { id }),
|
||||
recoverUpdate: (id: string) => invoke<UpdateTxn | null>("recover_update", { id }),
|
||||
applyUpdate: (id: string, resolutions: Record<string, "keep" | "replace">, source?: string) =>
|
||||
invoke<UpdateExecutionResult>("apply_update", { id, source: source ?? null, resolutions }),
|
||||
lastUpdateResult: (id: string) => invoke<UpdateExecutionResult | null>("last_update_result", { id }),
|
||||
invoke<{ txn: UpdateTxn }>("apply_update", { id, source: source ?? null, resolutions }),
|
||||
rollbackUpdate: (id: string, txn: string) => invoke<UpdateTxn>("rollback_update", { id, txn }),
|
||||
retryUpdateValidation: (id: string, txn: string) => invoke<UpdateTxn>("retry_update_validation", { id, txn }),
|
||||
population: (id: string) => invoke<Population | null>("get_population", { id }),
|
||||
@@ -470,8 +477,8 @@ export const api = {
|
||||
play: (id: string) => invoke<DriverOutcome>("play", { id }),
|
||||
friendsStatus: (id: string) => invoke<FriendsStatus>("friends_status", { id }),
|
||||
friendsCheckInternet: () => invoke<InternetCheck>("friends_check_internet"),
|
||||
friendsEnable: (id: string, mode: FriendsMode, host?: string, useUpnp = false) =>
|
||||
invoke<{ host: string; restart_required: boolean; note: string | null }>("friends_enable", { id, mode, host: host ?? null, useUpnp }),
|
||||
friendsEnable: (id: string, mode: FriendsMode, host?: string, useUpnp = false, lanAddressOverride: string | null = null) =>
|
||||
invoke<{ host: string; restart_required: boolean; note: string | null }>("friends_enable", { id, mode, host: host ?? null, useUpnp, lanAddressOverride }),
|
||||
friendsPackage: (id: string) => invoke<string>("friends_package", { id }),
|
||||
runDiagnostics: (id: string) => invoke<{ checks: DiagCheck[]; problems: number }>("run_diagnostics", { id }),
|
||||
verifyFiles: (id: string) => invoke<{ path: string; kind: "missing" | "changed" }[]>("verify_files", { id }),
|
||||
|
||||
@@ -86,8 +86,8 @@ for (const [key, title, desc] of [
|
||||
for (let n = 1; n <= 3; n++) add(`EC.P${n}`, "string", [`NPC phrase ${n}`, `Реплика НПС ${n}`, `NPC-Satz ${n}`, `Phrase du PNJ ${n}`, `Frase del PNJ ${n}`, `NPC台词 ${n}`], ["Text spoken by the NPC. Keep the enclosing quotes.", "Текст реплики НПС. Сохраните кавычки вокруг текста.", "Gesprochener Text. Anführungszeichen beibehalten.", "Texte prononcé. Conservez les guillemets.", "Texto hablado. Conserva las comillas.", "NPC发言内容,请保留外层引号。"], { advanced: true });
|
||||
|
||||
const ah = "AuctionHouseBot.";
|
||||
add(ah + "GUIDs", "string", ["Auction characters", "Персонажи аукциона", "Auktionscharaktere", "Personnages d’enchères", "Personajes de subasta", "拍卖角色"], ["Character GUIDs separated by commas, without spaces. Use dedicated offline characters, not companion bots. 0 selects nobody.", "GUID персонажей через запятую без пробелов. Используйте отдельных офлайн-персонажей, не ботов-компаньонов. 0 — никто.", "Charakter-GUIDs durch Kommas, ohne Leerzeichen. Separate Offline-Charaktere verwenden, keine Begleiter-Bots. 0 wählt niemanden.", "GUID séparés par des virgules sans espaces. Utilisez des personnages dédiés hors ligne, pas des bots compagnons. 0 ne sélectionne personne.", "GUID separados por comas sin espacios. Usa personajes dedicados desconectados, no bots acompañantes. 0 no selecciona a nadie.", "角色GUID以逗号分隔,不加空格。使用专用离线角色,勿用伙伴机器人。0不选择任何角色。"]);
|
||||
add(ah + "EnableSeller", "bool", ["Post auctions", "Выставлять лоты", "Auktionen einstellen", "Publier des enchères", "Publicar subastas", "发布拍卖"], ["Let the auction characters sell items. The module switch and valid character GUIDs are also required.", "Разрешает персонажам продавать предметы. Нужны включённый модуль и действительные GUID персонажей.", "Erlaubt Verkäufe. Modulschalter und gültige Charakter-GUIDs sind ebenfalls erforderlich.", "Autorise les ventes. Le module doit être activé et les GUID valides.", "Permite vender. También requiere el módulo activado y GUID válidos.", "允许拍卖角色出售物品,还需启用模块并填写有效角色GUID。"]);
|
||||
add(ah + "GUIDs", "string", ["Auction characters", "Персонажи аукциона", "Auktionscharaktere", "Personnages d’enchères", "Personajes de subasta", "拍卖角色"], ["Leave 0 and the server creates and uses its own auction character. To use your own, enter GUIDs separated by commas, without spaces; use dedicated offline characters, not companion bots.", "Оставьте 0, и сервер сам создаст и будет использовать своего персонажа аукциона. Чтобы использовать своих, укажите GUID через запятую без пробелов; нужны отдельные офлайн-персонажи, не боты-компаньоны.", "Bei 0 legt der Server selbst einen Auktionscharakter an und nutzt ihn. Eigene Charaktere: GUIDs durch Kommas, ohne Leerzeichen; separate Offline-Charaktere verwenden, keine Begleiter-Bots.", "Laissez 0 : le serveur crée et utilise son propre personnage d’enchères. Pour les vôtres, indiquez des GUID séparés par des virgules sans espaces ; personnages dédiés hors ligne, pas des bots compagnons.", "Deja 0 y el servidor crea y usa su propio personaje de subastas. Para usar los tuyos, indica GUID separados por comas sin espacios; personajes dedicados desconectados, no bots acompañantes.", "保持0时由服务器自动创建并使用拍卖角色。要使用自己的角色,请以逗号分隔填写GUID,不加空格;使用专用离线角色,勿用伙伴机器人。"], { advanced: true });
|
||||
add(ah + "EnableSeller", "bool", ["Post auctions", "Выставлять лоты", "Auktionen einstellen", "Publier des enchères", "Publicar subastas", "发布拍卖"], ["Let the auction characters sell items. The module switch is also required.", "Разрешает персонажам продавать предметы. Нужен включённый модуль.", "Erlaubt Verkäufe. Der Modulschalter muss ebenfalls aktiv sein.", "Autorise les ventes. Le module doit aussi être activé.", "Permite vender. También requiere el módulo activado.", "允许拍卖角色出售物品,还需启用模块。"]);
|
||||
add(ah + "CoA.ObtainableItemsOnly", "bool", ["Only obtainable items", "Только доступные в игре предметы", "Nur erhältliche Gegenstände", "Objets accessibles uniquement", "Solo objetos obtenibles", "仅可获取物品"], ["List items from world loot, vendors and professions. Other item filters still apply.", "Выставляет предметы из добычи, торговцев и профессий. Остальные фильтры продолжают действовать.", "Listet Gegenstände aus Beute, Händlern und Berufen. Weitere Filter gelten weiterhin.", "Publie les objets de butin, vendeurs et métiers. Les autres filtres s’appliquent.", "Publica objetos de botín, vendedores y profesiones. Los demás filtros siguen activos.", "发布来自掉落、商人和专业的物品,其他筛选仍生效。"]);
|
||||
add(ah + "ItemsPerCycle", "int", ["Listings per cycle", "Лотов за цикл", "Angebote pro Durchlauf", "Annonces par cycle", "Anuncios por ciclo", "每轮上架数量"], ["Maximum items posted during one auction update.", "Максимум предметов за одно обновление аукциона.", "Maximale Angebote pro Auktionsaktualisierung.", "Nombre maximal d’objets par mise à jour.", "Máximo de objetos por actualización.", "每轮拍卖更新最多上架的物品数量。"], { min: 0 });
|
||||
for (const [kind, titles] of [
|
||||
@@ -104,7 +104,7 @@ for (const [faction, names] of [
|
||||
`${names[0]}: ${maximum ? "maximum" : "minimum"} listings`, `${names[1]}: ${maximum ? "максимум" : "минимум"} лотов`, `${names[2]}: ${maximum ? "maximale" : "minimale"} Angebote`, `${names[3]} : annonces ${maximum ? "maximales" : "minimales"}`, `${names[4]}: anuncios ${maximum ? "máximos" : "mínimos"}`, `${names[5]}:${maximum ? "最多" : "最少"}上架数量`,
|
||||
], ["Target listing count for this auction house. Keep the minimum no higher than the maximum.", "Целевое число лотов этого аукциона. Минимум не должен превышать максимум.", "Zielanzahl für dieses Auktionshaus. Minimum nicht höher als Maximum einstellen.", "Nombre cible pour cet hôtel des ventes. Le minimum ne doit pas dépasser le maximum.", "Cantidad objetivo para esta casa de subastas. El mínimo no debe superar el máximo.", "此拍卖行的目标上架数量,最小值不得超过最大值。"], { min: 0 });
|
||||
}
|
||||
add(ah + "Buyer.Enabled", "bool", ["Buy player auctions", "Покупать лоты игроков", "Spielerauktionen kaufen", "Acheter les enchères des joueurs", "Comprar subastas de jugadores", "购买玩家拍卖"], ["Enable the auction buyer. It spends the auction characters’ money.", "Включает покупателя. Он тратит деньги персонажей аукциона.", "Aktiviert Käufe mit dem Geld der Auktionscharaktere.", "Active les achats avec l’argent des personnages d’enchères.", "Activa las compras con el dinero de los personajes de subasta.", "启用拍卖买家,会花费拍卖角色的金币。"]);
|
||||
add(ah + "Buyer.Enabled", "bool", ["Buy player auctions", "Покупать лоты игроков", "Spielerauktionen kaufen", "Acheter les enchères des joueurs", "Comprar subastas de jugadores", "购买玩家拍卖"], ["The auctioneer bot buys listings.", "Бот-аукционист покупает лоты.", "Der Auktionator-Bot kauft Angebote.", "Le bot commissaire-priseur achète des annonces.", "El bot subastador compra anuncios.", "拍卖机器人会购买拍卖品。"]);
|
||||
add(ah + "Buyer.BuyCandidatesPerBuyCycle", "int", ["Purchase candidates per cycle", "Кандидатов на покупку за цикл", "Kaufkandidaten pro Durchlauf", "Achats potentiels par cycle", "Candidatos de compra por ciclo", "每轮购买候选数量"], ["How many auctions the buyer considers per cycle.", "Сколько лотов покупатель рассматривает за цикл.", "Anzahl geprüfter Auktionen pro Durchlauf.", "Nombre d’enchères examinées par cycle.", "Subastas examinadas por ciclo.", "买家每轮考虑的拍卖数量。"], { min: 0 });
|
||||
add(ah + "Buyer.AcceptablePriceModifier", "float", ["Buyer price multiplier", "Множитель цены покупателя", "Kaufpreisfaktor", "Multiplicateur du prix d’achat", "Multiplicador del precio de compra", "买家价格倍率"], ["1 uses the calculated price. Higher values allow more expensive purchases.", "1 — расчётная цена. Большие значения допускают более дорогие покупки.", "1 nutzt den berechneten Preis. Höhere Werte erlauben teurere Käufe.", "1 utilise le prix calculé. Une valeur supérieure autorise des achats plus chers.", "1 usa el precio calculado. Valores mayores permiten compras más caras.", "1使用计算价格,增大后允许更高价购买。"], { min: 0 });
|
||||
add(ah + "MaxBuyoutPriceInCopper", "int", ["Maximum buyout (copper)", "Максимальная цена выкупа (медь)", "Maximaler Sofortkauf (Kupfer)", "Rachat maximal (cuivre)", "Compra máxima (cobre)", "最高一口价(铜币)"], ["Upper price limit. 10,000 copper = 1 gold.", "Верхний предел цены. 10 000 меди = 1 золото.", "Preisobergrenze. 10.000 Kupfer = 1 Gold.", "Prix maximal. 10 000 cuivre = 1 or.", "Precio máximo. 10 000 cobre = 1 oro.", "价格上限,10000铜币=1金币。"], { min: 0 });
|
||||
|
||||
+13
-4
@@ -1,9 +1,14 @@
|
||||
import type { ReportTarget, ReportTargetId } from "./api";
|
||||
|
||||
/** The text of a problem report, always in English so whoever reads it on GitHub can follow it; the person's own words go in as typed. */
|
||||
export interface ReportInput {
|
||||
managerVersion: string;
|
||||
windows: string;
|
||||
installKind: "new" | "imported";
|
||||
serverVersion: string | null;
|
||||
/** where the report goes; a bot repository is told which Manager and bot release it came from */
|
||||
target: ReportTargetId;
|
||||
botsVersion: string | null;
|
||||
what: string;
|
||||
expected: string;
|
||||
steps: string;
|
||||
@@ -11,7 +16,10 @@ export interface ReportInput {
|
||||
diagnostics: boolean;
|
||||
}
|
||||
|
||||
export const NEW_ISSUE_URL = "https://github.com/Corfirean/coa-server-manager/issues/new";
|
||||
/** The "new issue" page of a repository given as `owner/name`. */
|
||||
export function newIssueUrl(repo: string): string {
|
||||
return `https://github.com/${repo}/issues/new`;
|
||||
}
|
||||
const PRIVACY = "> Please remove passwords, tokens, private IP information or other sensitive data before posting logs.";
|
||||
|
||||
export function reportBody(r: ReportInput): string {
|
||||
@@ -23,6 +31,7 @@ export function reportBody(r: ReportInput): string {
|
||||
`**Windows version:** ${r.windows || "unknown"} `,
|
||||
`**Fresh install or imported server:** ${r.installKind === "new" ? "Fresh install" : "Imported server"} `,
|
||||
...(r.serverVersion ? [`**Server version:** ${r.serverVersion} `] : []),
|
||||
...(r.target !== "manager" ? [`**Bot system:** ${r.target === "squid" ? "SQUID Playerbots" : "CoA Companions"}${r.botsVersion ? ` ${r.botsVersion}` : ""} `] : []),
|
||||
"",
|
||||
"**What happened?** ",
|
||||
text(r.what, "Describe the problem."),
|
||||
@@ -54,9 +63,9 @@ export function encodeQuery(s: string): string {
|
||||
.join("");
|
||||
}
|
||||
|
||||
/** A link that opens GitHub's "new issue" page with the title and text filled in. */
|
||||
export function issueUrl(title: string, body: string): string {
|
||||
return `${NEW_ISSUE_URL}?labels=bug&title=${encodeQuery(title)}&body=${encodeQuery(body)}`;
|
||||
/** A link that opens GitHub's "new issue" page of `target` with the title and text filled in. The bug label is only asked for in our own repositories. */
|
||||
export function issueUrl(target: Pick<ReportTarget, "repo" | "ours">, title: string, body: string): string {
|
||||
return `${newIssueUrl(target.repo)}?${target.ours ? "labels=bug&" : ""}title=${encodeQuery(title)}&body=${encodeQuery(body)}`;
|
||||
}
|
||||
|
||||
/** Links longer than this are not reliable in every browser; the full text is then copied to the clipboard instead. */
|
||||
|
||||
+30
-29
@@ -1,6 +1,7 @@
|
||||
import { useSyncExternalStore } from "react";
|
||||
import { listen } from "@tauri-apps/api/event";
|
||||
import { api, asUiError, type UiError, type UpdatePreview, type UpdateTxn } from "@/lib/api";
|
||||
import { isUpdateCurrent } from "./serverUpdateStatus";
|
||||
|
||||
/**
|
||||
* Server update status for the main screen and the navigation: checked when the app starts and every five minutes,
|
||||
@@ -16,11 +17,13 @@ export interface ServerUpdateState {
|
||||
error: string | null;
|
||||
/** The full error of the last update attempt, for the Settings card. */
|
||||
uiError: UiError | null;
|
||||
stateError: UiError | null;
|
||||
stateRevision: number;
|
||||
/** 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 } | { recovered: UpdateTxn } | null;
|
||||
result: { committed: string } | { pending: UpdateTxn } | null;
|
||||
}
|
||||
|
||||
const EMPTY: ServerUpdateState = { preview: null, available: false, checking: false, applying: false, step: null, percent: 0, error: null, uiError: null, 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 };
|
||||
const states = new Map<string, ServerUpdateState>();
|
||||
const listeners = new Set<() => void>();
|
||||
export const CHECK_EVERY_MS = 5 * 60 * 1000;
|
||||
@@ -37,10 +40,10 @@ export async function checkServerUpdate(id: string): Promise<void> {
|
||||
set(id, { checking: true });
|
||||
try {
|
||||
const p = await api.checkUpdate(id);
|
||||
set(id, { preview: p, available: p.to_version !== (p.from_version ?? ""), error: null });
|
||||
set(id, { preview: p, available: !isUpdateCurrent(p), error: null });
|
||||
} catch (e) {
|
||||
// offline or no package published: keep what we knew and stay quiet
|
||||
set(id, { error: asUiError(e).human.code });
|
||||
// A cached offer is no longer safe after an update or failed recheck.
|
||||
set(id, { preview: null, available: false, error: asUiError(e).human.code });
|
||||
} finally {
|
||||
set(id, { checking: false });
|
||||
}
|
||||
@@ -48,21 +51,7 @@ export async function checkServerUpdate(id: string): Promise<void> {
|
||||
|
||||
/** Check now and then every five minutes. Returns the function that stops it. */
|
||||
export function startServerUpdatePolling(id: string): () => void {
|
||||
void (async () => {
|
||||
try {
|
||||
const pending = await api.pendingUpdate(id);
|
||||
if (pending) {
|
||||
set(id, { applying: true, step: "Recovering the interrupted update", result: null });
|
||||
const recovered = await api.recoverUpdate(id);
|
||||
if (recovered) set(id, { result: recovered.state === "committed" ? { committed: recovered.to_version } : { recovered } });
|
||||
}
|
||||
} catch (e) {
|
||||
const ui = asUiError(e);
|
||||
set(id, { error: ui.human.code, uiError: ui });
|
||||
return;
|
||||
} finally { set(id, { applying: false, step: null }); }
|
||||
await checkServerUpdate(id);
|
||||
})();
|
||||
void checkServerUpdate(id);
|
||||
const t = setInterval(() => void checkServerUpdate(id), CHECK_EVERY_MS);
|
||||
return () => clearInterval(t);
|
||||
}
|
||||
@@ -71,6 +60,20 @@ export function clearServerUpdateResult(id: string) {
|
||||
set(id, { result: null, uiError: null });
|
||||
}
|
||||
|
||||
export async function refreshServerUpdateState(id: string): Promise<UpdateTxn | null> {
|
||||
try {
|
||||
const pending = await api.pendingUpdate(id);
|
||||
const current = get(id).result;
|
||||
set(id, { stateError: null, stateRevision: get(id).stateRevision + 1,
|
||||
...(pending ? { available: false, preview: null } : {}),
|
||||
result: pending ? { pending } : current && "committed" in current ? current : null });
|
||||
return pending;
|
||||
} catch (e) {
|
||||
set(id, { stateError: asUiError(e), stateRevision: get(id).stateRevision + 1, available: false, preview: null });
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Apply an update. Without options this is the main-screen button: the pending update, only when no file needs a
|
||||
* decision. With options (the Settings card) the owner has already chosen what to do with each changed file and may
|
||||
@@ -79,7 +82,8 @@ export function clearServerUpdateResult(id: string) {
|
||||
*/
|
||||
export async function applyServerUpdate(id: string, opts?: { choices: Record<string, "keep" | "replace">; source?: string }): Promise<boolean> {
|
||||
const p = get(id).preview;
|
||||
if (get(id).applying) return false;
|
||||
const current = get(id);
|
||||
if (current.applying || current.stateError || (current.result && "pending" in current.result)) return false;
|
||||
if (!opts && (!p || p.conflicts.length > 0)) return false;
|
||||
set(id, { applying: true, step: null, percent: 0, error: null, uiError: null, result: null });
|
||||
let un: (() => void) | undefined;
|
||||
@@ -90,20 +94,17 @@ export async function applyServerUpdate(id: string, opts?: { choices: Record<str
|
||||
}
|
||||
try {
|
||||
const out = await api.applyUpdate(id, opts?.choices ?? {}, opts?.source);
|
||||
if (out.disposition === "updated" && out.txn) {
|
||||
set(id, { result: { committed: out.txn.to_version } });
|
||||
return true;
|
||||
}
|
||||
if (out.txn) set(id, { result: out.disposition === "restored" ? { recovered: out.txn } : { pending: out.txn } });
|
||||
const ui = asUiError(out.message ?? out.disposition);
|
||||
set(id, { error: ui.human.code, uiError: ui });
|
||||
return false;
|
||||
set(id, { result: out.txn.state === "committed" ? { committed: out.txn.to_version ?? "" } : { pending: out.txn } });
|
||||
return true;
|
||||
} catch (e) {
|
||||
const ui = asUiError(e);
|
||||
set(id, { error: ui.human.code, uiError: ui });
|
||||
return false;
|
||||
} finally {
|
||||
un?.();
|
||||
try {
|
||||
await refreshServerUpdateState(id);
|
||||
} catch { /* The state error remains visible and prevents another apply. */ }
|
||||
set(id, { applying: false });
|
||||
void checkServerUpdate(id);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,7 @@
|
||||
import type { UpdatePreview } from "./api";
|
||||
|
||||
export function isUpdateCurrent(preview: UpdatePreview): boolean {
|
||||
return preview.from_version === preview.to_version
|
||||
&& preview.items.every((item) => item.action === "skip")
|
||||
&& (preview.pending_migrations ?? (preview.migrations === 0 ? 0 : undefined)) === 0;
|
||||
}
|
||||
@@ -5,6 +5,15 @@ import { Button } from "@/components/ui/button";
|
||||
import { Card } from "@/components/ui/card";
|
||||
import { useHuman, useT, type Key } from "@/i18n";
|
||||
|
||||
/** Convenience only; Rust validates again before applying or saving. */
|
||||
function validLanIpv4(value: string): boolean {
|
||||
if (!/^(0|[1-9]\d{0,2})(\.(0|[1-9]\d{0,2})){3}$/.test(value)) return false;
|
||||
const octets = value.split(".").map(Number);
|
||||
const [a, b] = octets;
|
||||
return octets.every((n) => n <= 255) && a > 0 && a < 224 && a !== 127
|
||||
&& !(a === 169 && b === 254) && !(a === 100 && b >= 64 && b <= 127);
|
||||
}
|
||||
|
||||
function Line({ ok, children, warn }: { ok: boolean; warn?: boolean; children: React.ReactNode }) {
|
||||
const t = useT();
|
||||
return (
|
||||
@@ -81,11 +90,28 @@ export function FriendsPage({ serverId }: { serverId: string }) {
|
||||
const [note, setNote] = useState<string | null>(null);
|
||||
const [copied, setCopied] = useState(false);
|
||||
const [needsRestart, setNeedsRestart] = useState(false);
|
||||
const [lanChoice, setLanChoice] = useState("automatic");
|
||||
const [customLan, setCustomLan] = useState("");
|
||||
|
||||
const refresh = useCallback(() => api.friendsStatus(serverId).then(setSt).catch((e) => setError(asUiError(e))), [serverId]);
|
||||
const refresh = useCallback(() => api.friendsStatus(serverId).then((status) => {
|
||||
setSt(status);
|
||||
}).catch((e) => setError(asUiError(e))), [serverId]);
|
||||
useEffect(() => {
|
||||
void refresh();
|
||||
}, [refresh]);
|
||||
let cancelled = false;
|
||||
setSt(null);
|
||||
setNet(null);
|
||||
void api.friendsStatus(serverId).then((status) => {
|
||||
if (cancelled) return;
|
||||
const saved = status.settings.lan_address_override;
|
||||
setCustomLan(saved ?? "");
|
||||
setLanChoice(saved === null ? "automatic" : status.lan_addresses.some((a) => a.address === saved) ? saved : "custom");
|
||||
setSt(status);
|
||||
}).catch((e) => { if (!cancelled) setError(asUiError(e)); });
|
||||
return () => { cancelled = true; };
|
||||
}, [serverId]);
|
||||
|
||||
const lanOverride = lanChoice === "automatic" ? null : lanChoice === "custom" ? customLan.trim() : lanChoice;
|
||||
const lanValid = lanOverride === null || validLanIpv4(lanOverride);
|
||||
|
||||
async function run(label: string, fn: () => Promise<string | void>) {
|
||||
setBusy(label);
|
||||
@@ -109,7 +135,12 @@ export function FriendsPage({ serverId }: { serverId: string }) {
|
||||
|
||||
const enable = (mode: FriendsMode) =>
|
||||
run(`enable-${mode}`, async () => {
|
||||
const r = await api.friendsEnable(serverId, mode, net?.public_ip ?? undefined, mode === "direct" && !!net?.router_found);
|
||||
const r = await api.friendsEnable(
|
||||
serverId, mode,
|
||||
mode === "direct" ? net?.public_ip ?? undefined : undefined,
|
||||
mode === "direct" && !!net?.router_found,
|
||||
mode === "lan" ? lanOverride : null,
|
||||
);
|
||||
setNeedsRestart(r.restart_required);
|
||||
return [r.restart_required ? t("fr.restartToApply") : null, r.note ? (r.note.startsWith("Your router was asked") ? t("fr.note.forwarded") : r.note.startsWith("Your router does not support") ? t("fr.note.manual") : r.note) : null].filter(Boolean).join(" ") || t("fr.ready");
|
||||
});
|
||||
@@ -119,6 +150,8 @@ export function FriendsPage({ serverId }: { serverId: string }) {
|
||||
const cur = st.settings;
|
||||
const exposed = st.exposure.filter((e) => (e.what === "database" || e.what === "server console") && e.reachable_from_network);
|
||||
const connection = cur.mode === "local" ? null : `set realmlist ${cur.host}`;
|
||||
const selectedLan = lanOverride ?? st.lan_ip;
|
||||
const lanUnavailable = lanOverride !== null && lanValid && !st.lan_addresses.some((a) => a.address === lanOverride);
|
||||
|
||||
return (
|
||||
<div className="max-w-3xl">
|
||||
@@ -157,8 +190,28 @@ export function FriendsPage({ serverId }: { serverId: string }) {
|
||||
|
||||
{m.id === "lan" && (
|
||||
<>
|
||||
<p className="mt-2 text-sm">{t("fr.yourLan")} <b className="selectable">{st.lan_ip ?? t("fr.unknown")}</b></p>
|
||||
{st.lan_ip && cur.mode !== m.id && <RealmlistLine host={st.lan_ip} />}
|
||||
<label htmlFor="lan-address" className="mt-3 block text-sm">{t("fr.lan.address")}</label>
|
||||
<select id="lan-address" value={lanChoice} disabled={!!busy}
|
||||
className="mt-1 w-full rounded-md border border-line bg-bg px-3 py-2 text-sm outline-none focus:border-gold"
|
||||
onChange={(e) => {
|
||||
if (e.target.value === "custom" && lanOverride) setCustomLan(lanOverride);
|
||||
setLanChoice(e.target.value);
|
||||
}}>
|
||||
<option value="automatic">{t("fr.lan.automatic")} — {st.lan_ip ?? t("fr.unknown")}</option>
|
||||
{st.lan_addresses.map((a) => <option key={a.address} value={a.address}>{a.interface} — {a.address}{a.is_default ? ` (${t("fr.lan.default")})` : ""}</option>)}
|
||||
{lanChoice !== "automatic" && lanChoice !== "custom" && !st.lan_addresses.some((a) => a.address === lanChoice) && <option value={lanChoice}>{lanChoice}</option>}
|
||||
<option value="custom">{t("fr.lan.custom")}</option>
|
||||
</select>
|
||||
{lanChoice === "custom" && <>
|
||||
<label htmlFor="lan-custom" className="mt-2 block text-sm">{t("fr.lan.customIpv4")}</label>
|
||||
<input id="lan-custom" value={customLan} disabled={!!busy} spellCheck={false} inputMode="decimal"
|
||||
aria-invalid={!lanValid} aria-describedby={!lanValid ? "lan-invalid" : undefined}
|
||||
className="mt-1 w-full rounded-md border border-line bg-bg px-3 py-2 text-sm outline-none focus:border-gold"
|
||||
onChange={(e) => setCustomLan(e.target.value)} />
|
||||
</>}
|
||||
{!lanValid && <p id="lan-invalid" className="mt-2 text-sm text-bad" role="alert">{t("fr.lan.invalid")}</p>}
|
||||
{lanUnavailable && <p className="mt-2 text-sm text-warn" role="status"><b>{t("fr.lan.unavailable")}</b> {t("fr.lan.unavailableText")}</p>}
|
||||
{selectedLan && lanValid && <RealmlistLine host={selectedLan} />}
|
||||
</>
|
||||
)}
|
||||
|
||||
@@ -221,7 +274,7 @@ export function FriendsPage({ serverId }: { serverId: string }) {
|
||||
<Button
|
||||
size="sm"
|
||||
variant={m.id === "private" && net?.reachability === "cgnat" ? "primary" : "secondary"}
|
||||
disabled={!!busy || (m.id === "direct" && !net?.public_ip) || (m.id === "private" && !st.tailscale.connected)}
|
||||
disabled={!!busy || (m.id === "lan" && (!lanValid || !selectedLan)) || (m.id === "direct" && !net?.public_ip) || (m.id === "private" && !st.tailscale.connected)}
|
||||
onClick={() => void enable(m.id)}
|
||||
title={m.id === "direct" && !net?.public_ip ? t("fr.checkFirst") : undefined}
|
||||
>
|
||||
|
||||
@@ -261,6 +261,12 @@ function ModuleSettings({ serverId, module, onSaved }: { serverId: string; modul
|
||||
return (
|
||||
<div className="mt-3 border-t border-line pt-3">
|
||||
{items === null && !error && <Loader2 className="h-4 w-4 animate-spin text-muted" aria-hidden />}
|
||||
{module.id === "npc-enchanter" && (
|
||||
<div className="mb-4 space-y-2 text-sm text-muted">
|
||||
<p>{t("mod.enchanter.add")}</p>
|
||||
<p>{t("mod.enchanter.remove")}</p>
|
||||
</div>
|
||||
)}
|
||||
{module.id === "ah-bot" && (
|
||||
<div className="mb-4 space-y-2 text-sm text-muted">
|
||||
<p>{t("mod.ahbot.setup")}</p>
|
||||
|
||||
@@ -64,7 +64,7 @@ function Row({ label, s }: { label: string; s: ServiceStatus }) {
|
||||
);
|
||||
}
|
||||
|
||||
export function Overview({ server, companions = true, onForget, onOpenUpdates, onRealmChanged }: { server: ServerSummary; /** the companions module is on */ companions?: boolean; onForget: () => Promise<void>; onOpenUpdates: () => void; onRealmChanged: () => void }) {
|
||||
export function Overview({ server, companions = true, onForget, onOpenUpdates, onRealmChanged, onReport }: { server: ServerSummary; /** the companions module is on */ companions?: boolean; onForget: () => Promise<void>; onOpenUpdates: () => void; onRealmChanged: () => void; /** open the problem report, which collects the diagnostics */ onReport: () => void }) {
|
||||
const t = useT();
|
||||
const human = useHuman();
|
||||
const [status, setStatus] = useState<StatusView | null>(null);
|
||||
@@ -228,6 +228,12 @@ export function Overview({ server, companions = true, onForget, onOpenUpdates, o
|
||||
/>
|
||||
{headline}
|
||||
</div>
|
||||
{!transitioning && !running && anyUp && (
|
||||
<p className="mt-2 text-sm text-muted">
|
||||
{t("overview.reportHint")}{" "}
|
||||
<button onClick={onReport} className="cursor-pointer text-gold underline hover:text-ink">{t("overview.reportBtn")}</button>
|
||||
</p>
|
||||
)}
|
||||
|
||||
<div className="mt-5 divide-y divide-line border-y border-line">
|
||||
<Row label={t("overview.database")} s={mysql} />
|
||||
|
||||
+90
-30
@@ -1,22 +1,36 @@
|
||||
import { useEffect, useMemo, useState } from "react";
|
||||
import { useEffect, useState } from "react";
|
||||
import { Loader2 } from "lucide-react";
|
||||
import { api, asUiError, type ReportContext, type UiError } from "@/lib/api";
|
||||
import { api, asUiError, type ReportContext, type ReportTarget, type ReportTargetId, type UiError } from "@/lib/api";
|
||||
import { MAX_LINK, issueUrl, reportBody } from "@/lib/report";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Card } from "@/components/ui/card";
|
||||
import { useHuman, useT } from "@/i18n";
|
||||
import { useHuman, useT, type Key } from "@/i18n";
|
||||
|
||||
const field = "mt-1 block w-full rounded-md border border-line bg-bg px-3 py-2.5 text-[15px] outline-none focus:border-gold";
|
||||
|
||||
/** A problem report that becomes a prefilled GitHub issue. Nothing is sent from here: the person reviews and submits it on GitHub. */
|
||||
const TARGET_LABEL: Record<ReportTargetId, Key> = {
|
||||
manager: "rep.target.manager",
|
||||
companions: "rep.target.companions",
|
||||
squid: "rep.target.squid",
|
||||
};
|
||||
|
||||
const FALLBACK: ReportTarget = { id: "manager", repo: "Corfirean/coa-server-manager", ours: true };
|
||||
|
||||
/**
|
||||
* A problem report that becomes a prefilled GitHub issue in the repository of whatever it is about. One button collects
|
||||
* the diagnostics (and shows the file in its folder) and opens the issue; the person reviews it and submits it on GitHub.
|
||||
*/
|
||||
export function ReportPage({ serverId }: { serverId: string }) {
|
||||
const t = useT();
|
||||
const human = useHuman();
|
||||
const [ctx, setCtx] = useState<ReportContext | null>(null);
|
||||
const [targets, setTargets] = useState<ReportTarget[]>([]);
|
||||
const [targetId, setTargetId] = useState<ReportTargetId | null>(null);
|
||||
const [title, setTitle] = useState("");
|
||||
const [what, setWhat] = useState("");
|
||||
const [expected, setExpected] = useState("");
|
||||
const [steps, setSteps] = useState("");
|
||||
const [withDiag, setWithDiag] = useState(true);
|
||||
const [file, setFile] = useState<string | null>(null);
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [note, setNote] = useState<string | null>(null);
|
||||
@@ -25,30 +39,44 @@ export function ReportPage({ serverId }: { serverId: string }) {
|
||||
|
||||
useEffect(() => {
|
||||
void api.reportContext(serverId).then(setCtx).catch(() => setCtx(null));
|
||||
void api.reportTargets().then(setTargets).catch(() => setTargets([]));
|
||||
}, [serverId]);
|
||||
|
||||
const body = useMemo(
|
||||
() =>
|
||||
reportBody({
|
||||
managerVersion: ctx?.manager_version ?? "",
|
||||
windows: ctx?.windows ?? "",
|
||||
installKind: ctx?.install_kind ?? "new",
|
||||
serverVersion: ctx?.server_version ?? null,
|
||||
what,
|
||||
expected,
|
||||
steps,
|
||||
diagnostics: file !== null,
|
||||
}),
|
||||
[ctx, what, expected, steps, file],
|
||||
);
|
||||
const issueTitle = `[Bug] ${title.trim()}`;
|
||||
// start on the bot system that is switched on, until the person picks one
|
||||
const chosen: ReportTargetId = targetId ?? ctx?.suggested_target ?? "manager";
|
||||
const shown = targets.length ? targets : [FALLBACK];
|
||||
const target = shown.find((x) => x.id === chosen) ?? shown[0];
|
||||
|
||||
function bodyFor(hasFile: boolean): string {
|
||||
return reportBody({
|
||||
managerVersion: ctx?.manager_version ?? "",
|
||||
windows: ctx?.windows ?? "",
|
||||
installKind: ctx?.install_kind ?? "new",
|
||||
serverVersion: ctx?.server_version ?? null,
|
||||
target: target.id,
|
||||
botsVersion: ctx?.bots_version ?? null,
|
||||
what,
|
||||
expected,
|
||||
steps,
|
||||
diagnostics: hasFile,
|
||||
});
|
||||
}
|
||||
const issueTitle = target.ours ? `[Bug] ${title.trim()}` : title.trim();
|
||||
const ready = title.trim().length > 0 && what.trim().length > 0;
|
||||
|
||||
async function makeFile() {
|
||||
/** Collects the diagnostics once; the Manager shows the file in its folder. */
|
||||
async function collect(): Promise<string> {
|
||||
if (file) return file;
|
||||
const path = await api.exportDiagnostics(serverId);
|
||||
setFile(path);
|
||||
return path;
|
||||
}
|
||||
|
||||
async function collectOnly() {
|
||||
setBusy(true);
|
||||
setError(null);
|
||||
try {
|
||||
setFile(await api.exportDiagnostics(serverId));
|
||||
await collect();
|
||||
} catch (e) {
|
||||
setError(asUiError(e));
|
||||
} finally {
|
||||
@@ -56,26 +84,32 @@ export function ReportPage({ serverId }: { serverId: string }) {
|
||||
}
|
||||
}
|
||||
|
||||
/** One button: collect the diagnostics (if asked), then open the issue with everything filled in. */
|
||||
async function openIssue() {
|
||||
setBusy(true);
|
||||
setError(null);
|
||||
setNote(null);
|
||||
try {
|
||||
const full = issueUrl(issueTitle, body);
|
||||
const path = withDiag ? await collect() : null;
|
||||
const body = bodyFor(path !== null);
|
||||
const full = issueUrl(target, issueTitle, body);
|
||||
if (full.length <= MAX_LINK) {
|
||||
await api.openLink(full);
|
||||
setNote(t("rep.opened"));
|
||||
} else {
|
||||
await navigator.clipboard.writeText(body);
|
||||
await api.openLink(issueUrl(issueTitle, "Paste the report text here (it was copied to the clipboard by CoA Server Manager)."));
|
||||
await api.openLink(issueUrl(target, issueTitle, "Paste the report text here (it was copied to the clipboard by CoA Server Manager)."));
|
||||
setNote(t("rep.openedLong"));
|
||||
}
|
||||
} catch (e) {
|
||||
setError(asUiError(e));
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
}
|
||||
|
||||
async function copy() {
|
||||
await navigator.clipboard.writeText(`${issueTitle}\n\n${body}`);
|
||||
await navigator.clipboard.writeText(`${issueTitle}\n\n${bodyFor(file !== null)}`);
|
||||
setNote(t("rep.copied"));
|
||||
}
|
||||
|
||||
@@ -85,6 +119,22 @@ export function ReportPage({ serverId }: { serverId: string }) {
|
||||
<p className="mt-1 text-muted">{t("q.report")}</p>
|
||||
<p className="mt-3 text-sm text-muted">{t("rep.intro")}</p>
|
||||
|
||||
<Card className="mt-6 p-6">
|
||||
<h2 className="font-semibold" id="rep-target">{t("rep.targetTitle")}</h2>
|
||||
<div role="radiogroup" aria-labelledby="rep-target" className="mt-3 space-y-2">
|
||||
{shown.map((x) => (
|
||||
<label key={x.id} className={`flex cursor-pointer items-start gap-3 rounded-md border px-3 py-2.5 ${chosen === x.id ? "border-gold" : "border-line"}`}>
|
||||
<input type="radio" name="rep-target" className="mt-1" checked={chosen === x.id} onChange={() => setTargetId(x.id)} />
|
||||
<span>
|
||||
<span className="block text-[15px]">{t(TARGET_LABEL[x.id])}</span>
|
||||
<span className="selectable block text-xs text-muted">{x.repo}</span>
|
||||
</span>
|
||||
</label>
|
||||
))}
|
||||
</div>
|
||||
<p className="mt-3 text-xs text-muted">{t("rep.targetPublic", { repo: target.repo })}</p>
|
||||
</Card>
|
||||
|
||||
<Card className="mt-6 p-6">
|
||||
<h2 className="font-semibold">{t("rep.autoTitle")}</h2>
|
||||
<dl className="mt-3 grid grid-cols-[auto_1fr] gap-x-6 gap-y-1 text-sm">
|
||||
@@ -100,6 +150,12 @@ export function ReportPage({ serverId }: { serverId: string }) {
|
||||
<dd>{ctx.server_version}</dd>
|
||||
</>
|
||||
)}
|
||||
{target.id !== "manager" && ctx?.bots_version && (
|
||||
<>
|
||||
<dt className="text-muted">{t("rep.botsVersion")}</dt>
|
||||
<dd>{ctx.bots_version}</dd>
|
||||
</>
|
||||
)}
|
||||
</dl>
|
||||
</Card>
|
||||
|
||||
@@ -125,16 +181,20 @@ export function ReportPage({ serverId }: { serverId: string }) {
|
||||
<Card className="mt-6 p-6">
|
||||
<h2 className="font-semibold">{t("rep.attachTitle")}</h2>
|
||||
<p className="mt-1 text-sm text-muted">{t("rep.attachText")}</p>
|
||||
<Button className="mt-3" size="sm" disabled={busy} onClick={() => void makeFile()}>
|
||||
{busy && <Loader2 className="h-4 w-4 animate-spin" aria-hidden />}
|
||||
{t("rep.makeFile")}
|
||||
</Button>
|
||||
<label className="mt-3 flex cursor-pointer items-start gap-3 text-sm">
|
||||
<input type="checkbox" className="mt-1" checked={withDiag} onChange={(e) => setWithDiag(e.target.checked)} />
|
||||
<span>{t("rep.withDiag")}</span>
|
||||
</label>
|
||||
{file && <p className="selectable mt-3 break-all text-sm text-ok" role="status">{t("rep.fileSaved", { path: file })}</p>}
|
||||
<p className="mt-4 text-xs text-warn">{t("rep.privacy")}</p>
|
||||
</Card>
|
||||
|
||||
<div className="mt-6 flex flex-wrap items-center gap-3">
|
||||
<Button variant="primary" disabled={!ready} onClick={() => void openIssue()}>{t("rep.open")}</Button>
|
||||
<Button variant="primary" disabled={!ready || busy} onClick={() => void openIssue()}>
|
||||
{busy && <Loader2 className="h-4 w-4 animate-spin" aria-hidden />}
|
||||
{busy ? t("rep.collecting") : withDiag ? t("rep.collectOpen") : t("rep.open")}
|
||||
</Button>
|
||||
<Button variant="ghost" disabled={busy} onClick={() => void collectOnly()}>{t("rep.makeFile")}</Button>
|
||||
<Button variant="ghost" disabled={!ready} onClick={() => void copy()}>{t("rep.copy")}</Button>
|
||||
<button onClick={() => setShowPreview((v) => !v)} aria-expanded={showPreview} className="cursor-pointer text-sm text-muted underline hover:text-ink">
|
||||
{t("rep.preview")}
|
||||
@@ -144,7 +204,7 @@ export function ReportPage({ serverId }: { serverId: string }) {
|
||||
<p className="mt-2 text-xs text-muted">{t("rep.githubNote")}</p>
|
||||
{note && <p className="mt-3 text-sm text-ok" role="status">{note}</p>}
|
||||
{error && <p className="mt-3 text-sm text-bad" role="alert">{error.human.code === "unknown" ? error.technical : human(error.human).message}</p>}
|
||||
{showPreview && <pre className="selectable mt-3 max-h-80 overflow-auto whitespace-pre-wrap rounded bg-black/40 p-3 text-xs text-muted">{`${issueTitle}\n\n${body}`}</pre>}
|
||||
{showPreview && <pre className="selectable mt-3 max-h-80 overflow-auto whitespace-pre-wrap rounded bg-black/40 p-3 text-xs text-muted">{`${issueTitle}\n\n${bodyFor(file !== null || withDiag)}`}</pre>}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,7 +1,8 @@
|
||||
import { useEffect, useState } from "react";
|
||||
import { open } from "@tauri-apps/plugin-dialog";
|
||||
import { ChevronDown, ChevronRight, Loader2 } from "lucide-react";
|
||||
import { applyServerUpdate, clearServerUpdateResult, useServerUpdate } from "@/lib/serverUpdate";
|
||||
import { applyServerUpdate, clearServerUpdateResult, refreshServerUpdateState, useServerUpdate } from "@/lib/serverUpdate";
|
||||
import { isUpdateCurrent } from "@/lib/serverUpdateStatus";
|
||||
import { api, asUiError, type UiError, type UpdatePreview, type UpdateTxn } from "@/lib/api";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Card } from "@/components/ui/card";
|
||||
@@ -23,12 +24,14 @@ export function SettingsHome({ serverId }: { serverId: string }) {
|
||||
const human = useHuman();
|
||||
const [preview, setPreview] = useState<UpdatePreview | null>(null);
|
||||
const [pending, setPending] = useState<UpdateTxn | null>(null);
|
||||
const [pendingChecked, setPendingChecked] = useState(false);
|
||||
const [pendingStateError, setPendingStateError] = useState<UiError | null>(null);
|
||||
const [localBusy, setBusy] = useState<"check" | "rollback" | "retry" | null>(null);
|
||||
// an update keeps running in the background when this tab is left, so its state is the shared one
|
||||
const busy = upd.applying ? "update" : localBusy;
|
||||
const progress = upd.applying ? { step: upd.step ?? "Starting", percent: upd.percent } : null;
|
||||
const [localError, setError] = useState<UiError | null>(null);
|
||||
const error = localError ?? upd.uiError;
|
||||
const error = pendingStateError ?? localError ?? upd.uiError;
|
||||
const [localDone, setDone] = useState<string | null>(null);
|
||||
const done = upd.result && "committed" in upd.result ? t("upd.updatedTo", { v: upd.result.committed }) : localDone;
|
||||
const [choices, setChoices] = useState<Record<string, "keep" | "replace">>({});
|
||||
@@ -36,27 +39,36 @@ export function SettingsHome({ serverId }: { serverId: string }) {
|
||||
const [source, setSource] = useState("");
|
||||
|
||||
useEffect(() => {
|
||||
void api.pendingUpdate(serverId).then(setPending).catch((e) => setError(asUiError(e)));
|
||||
void api.lastUpdateResult(serverId).then(async (result) => {
|
||||
const txn = result?.txn ?? await api.lastUpdate(serverId);
|
||||
if (result?.disposition === "rejected" || result?.disposition === "recovery-required") {
|
||||
setDone(null);
|
||||
if (result.message) setError(asUiError(result.message));
|
||||
} else if (txn?.outcome === "restored" && txn.recovery_verified) setDone(t("upd.autoRestored"));
|
||||
else if (result?.disposition === "updated" && txn) setDone(t("upd.updatedTo", { v: txn.to_version }));
|
||||
}).catch((e) => setError(asUiError(e)));
|
||||
let active = true;
|
||||
setPendingChecked(false);
|
||||
setPending(null);
|
||||
setPreview(null);
|
||||
setPendingStateError(null);
|
||||
void api.pendingUpdate(serverId).then((txn) => {
|
||||
if (active) { setPending(txn); setPendingChecked(true); }
|
||||
}).catch((e) => { if (active) setPendingStateError(asUiError(e)); });
|
||||
return () => { active = false; };
|
||||
}, [serverId]);
|
||||
|
||||
// the update finished (possibly while another tab was open): drop the stale preview, show what is left to decide
|
||||
// Every finished attempt refreshes the disk state, including failures in the background.
|
||||
useEffect(() => {
|
||||
if (!upd.result) return;
|
||||
if (!upd.stateRevision) return;
|
||||
setPreview(null);
|
||||
if ("pending" in upd.result) setPending(upd.result.pending);
|
||||
else {
|
||||
if ("recovered" in upd.result && upd.result.recovered.recovery_verified) setDone(t("upd.autoRestored"));
|
||||
void api.pendingUpdate(serverId).then(setPending).catch((e) => setError(asUiError(e)));
|
||||
}
|
||||
}, [upd.result, serverId]);
|
||||
setPendingChecked(!upd.stateError);
|
||||
setPendingStateError(upd.stateError);
|
||||
if (!upd.stateError) setPending(upd.result && "pending" in upd.result ? upd.result.pending : null);
|
||||
}, [upd.stateRevision, serverId]);
|
||||
|
||||
async function refreshPending() {
|
||||
setPendingChecked(false);
|
||||
try {
|
||||
const txn = await refreshServerUpdateState(serverId);
|
||||
setPending(txn);
|
||||
setPendingStateError(null);
|
||||
setPendingChecked(true);
|
||||
return txn;
|
||||
} catch (e) { setPendingStateError(asUiError(e)); throw e; }
|
||||
}
|
||||
|
||||
async function check() {
|
||||
setBusy("check");
|
||||
@@ -65,6 +77,8 @@ export function SettingsHome({ serverId }: { serverId: string }) {
|
||||
clearServerUpdateResult(serverId);
|
||||
setPreview(null);
|
||||
try {
|
||||
const txn = await refreshPending();
|
||||
if (txn) return;
|
||||
const p = await api.checkUpdate(serverId, source.trim() || undefined);
|
||||
setPreview(p);
|
||||
setChoices(Object.fromEntries(p.conflicts.map((c) => [c, "keep" as const])));
|
||||
@@ -76,12 +90,10 @@ export function SettingsHome({ serverId }: { serverId: string }) {
|
||||
}
|
||||
|
||||
async function update() {
|
||||
if (!pendingChecked || pendingStateError || pending) return;
|
||||
setError(null);
|
||||
setDone(null);
|
||||
await applyServerUpdate(serverId, { choices, source: source.trim() || undefined });
|
||||
const txn = await api.lastUpdate(serverId).catch(() => null);
|
||||
if (txn?.outcome === "restored" && txn.recovery_verified) setDone(t("upd.autoRestored"));
|
||||
setPending(await api.pendingUpdate(serverId).catch(() => null));
|
||||
}
|
||||
|
||||
async function rollback(txn: UpdateTxn) {
|
||||
@@ -95,6 +107,7 @@ export function SettingsHome({ serverId }: { serverId: string }) {
|
||||
} catch (e) {
|
||||
setError(asUiError(e));
|
||||
} finally {
|
||||
try { await refreshPending(); } catch { /* Keep the disk-state error visible. */ }
|
||||
setBusy(null);
|
||||
}
|
||||
}
|
||||
@@ -111,7 +124,10 @@ export function SettingsHome({ serverId }: { serverId: string }) {
|
||||
clearServerUpdateResult(serverId);
|
||||
} else setPending(result);
|
||||
} catch (e) { setError(asUiError(e)); }
|
||||
finally { setBusy(null); }
|
||||
finally {
|
||||
try { await refreshPending(); } catch { /* Keep the disk-state error visible. */ }
|
||||
setBusy(null);
|
||||
}
|
||||
}
|
||||
|
||||
async function browse() {
|
||||
@@ -179,28 +195,27 @@ export function SettingsHome({ serverId }: { serverId: string }) {
|
||||
</div>
|
||||
)}
|
||||
|
||||
{done && <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>}
|
||||
{error && (
|
||||
<p className="mt-4 text-sm text-bad" role="alert">
|
||||
{error.human.code === "unknown" ? error.technical : human(error.human).message}
|
||||
</p>
|
||||
)}
|
||||
|
||||
{preview && preview.from_version === preview.to_version && preview.items.every((i) => i.action === "skip") && (
|
||||
// The same version with no file to change: the database scripts of this package are all in the ledger already.
|
||||
{preview && isUpdateCurrent(preview) && (
|
||||
<div className="mt-5 border-t border-line pt-4">
|
||||
<p className="font-medium text-ok" role="status">{t("upd.current", { v: preview.to_version })}</p>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{preview && !(preview.from_version === preview.to_version && preview.items.every((i) => i.action === "skip")) && (
|
||||
{preview && !isUpdateCurrent(preview) && (
|
||||
<div className="mt-5 border-t border-line pt-4">
|
||||
<p className="font-medium">
|
||||
{preview.from_version ? t("upd.availableFrom", { to: preview.to_version, from: preview.from_version }) : t("upd.available", { to: preview.to_version })}
|
||||
</p>
|
||||
<p className="mt-1 text-sm text-muted">
|
||||
{preview.migrations > 0
|
||||
? t("upd.summaryDb", { size: mb(preview.download_bytes), files: preview.items.filter((i) => i.action !== "skip").length, db: preview.migrations })
|
||||
{(preview.pending_migrations ?? preview.migrations) > 0
|
||||
? t("upd.summaryDb", { size: mb(preview.download_bytes), files: preview.items.filter((i) => i.action !== "skip").length, db: preview.pending_migrations ?? preview.migrations })
|
||||
: t("upd.summary", { size: mb(preview.download_bytes), files: preview.items.filter((i) => i.action !== "skip").length })}
|
||||
</p>
|
||||
<ul className="mt-3 max-h-56 divide-y divide-line overflow-auto text-sm">
|
||||
@@ -225,7 +240,7 @@ export function SettingsHome({ serverId }: { serverId: string }) {
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
<Button className="mt-4" variant="primary" disabled={!!busy} onClick={() => void update()}>
|
||||
<Button className="mt-4" variant="primary" disabled={!!busy || !pendingChecked || !!pendingStateError || !!pending} onClick={() => void update()}>
|
||||
{busy === "update" && <Loader2 className="h-4 w-4 animate-spin" aria-hidden />}
|
||||
{t("upd.now")}
|
||||
</Button>
|
||||
|
||||
@@ -127,7 +127,7 @@ export function Shell(props: {
|
||||
|
||||
<main className="h-full flex-1 overflow-y-auto px-10 py-8">
|
||||
{page === "overview" ? (
|
||||
<Overview key={server.id} server={server} companions={botModule === "companions" && !hiddenPages.includes("bots")} onForget={() => props.onForget(server.id)} onOpenUpdates={() => setPage("settings")} onRealmChanged={reloadModules} />
|
||||
<Overview key={server.id} server={server} companions={botModule === "companions" && !hiddenPages.includes("bots")} onForget={() => props.onForget(server.id)} onOpenUpdates={() => setPage("settings")} onRealmChanged={reloadModules} onReport={() => setPage("report")} />
|
||||
) : page === "bots" || page === "server" ? (
|
||||
<SettingsPage key={`${server.id}-${page}-${botModule}`} serverId={server.id} scope={page} botModule={botModule} title={t(current.label)} question={t(current.question)} />
|
||||
) : page === "console" ? (
|
||||
|
||||
@@ -0,0 +1,62 @@
|
||||
import assert from "node:assert/strict";
|
||||
import test from "node:test";
|
||||
import { registerHooks } from "node:module";
|
||||
|
||||
let applyFailure = false;
|
||||
let stateFailure = false;
|
||||
let pending = null;
|
||||
const calls = [];
|
||||
globalThis.__hotfixApi = {
|
||||
applyUpdate: async () => { calls.push("apply"); if (applyFailure) throw new Error("SQL failure"); return { txn: { state: "committed", to_version: "2" } }; },
|
||||
pendingUpdate: async () => { calls.push("disk"); if (stateFailure) throw new Error("damaged journal"); return pending; },
|
||||
checkUpdate: async () => ({ from_version: "2", to_version: "2", items: [], conflicts: [], migrations: 1, pending_migrations: 0 }),
|
||||
};
|
||||
registerHooks({ resolve(specifier, context, next) {
|
||||
if (specifier === "react") return { shortCircuit: true, url: "data:text/javascript,export const useSyncExternalStore=(subscribe,getSnapshot)=>getSnapshot();" };
|
||||
if (specifier === "@/lib/api") return { shortCircuit: true, url: "data:text/javascript,export const api=globalThis.__hotfixApi;export const asUiError=e=>({human:{code:'unknown'},technical:e.message});" };
|
||||
if (specifier === "@tauri-apps/api/event") return { shortCircuit: true, url: "data:text/javascript,export const listen=async()=>()=>{};" };
|
||||
if (specifier === "./serverUpdateStatus" && context.parentURL?.endsWith("/serverUpdate.ts")) return { shortCircuit: true, url: new URL("../src/lib/serverUpdateStatus.ts", import.meta.url).href };
|
||||
return next(specifier, context);
|
||||
} });
|
||||
const { applyServerUpdate, refreshServerUpdateState, checkServerUpdate, useServerUpdate } = await import("../src/lib/serverUpdate.ts");
|
||||
|
||||
test("a failed update rereads its unfinished transaction from disk", async () => {
|
||||
calls.length = 0;
|
||||
applyFailure = true;
|
||||
pending = { id: "interrupted", state: "failed", message: "Recovery required" };
|
||||
assert.equal(await applyServerUpdate("failed-case", { choices: {} }), false);
|
||||
assert.deepEqual(calls, ["apply", "disk"]);
|
||||
assert.equal(await refreshServerUpdateState("failed-case"), pending);
|
||||
});
|
||||
test("unreadable state blocks another apply until a successful reread", async () => {
|
||||
calls.length = 0;
|
||||
applyFailure = false;
|
||||
stateFailure = true;
|
||||
await applyServerUpdate("corrupt-case", { choices: {} });
|
||||
assert.equal(await applyServerUpdate("corrupt-case", { choices: {} }), false);
|
||||
assert.deepEqual(calls, ["apply", "disk"]);
|
||||
stateFailure = false;
|
||||
pending = null;
|
||||
assert.equal(await refreshServerUpdateState("corrupt-case"), null);
|
||||
assert.equal(await applyServerUpdate("corrupt-case", { choices: {} }), true);
|
||||
assert.deepEqual(calls, ["apply", "disk", "disk", "apply", "disk"]);
|
||||
});
|
||||
test("refresh after recovery returns the latest disk state, then its absence", async () => {
|
||||
pending = { id: "recovery", state: "failed", message: "Restore failed at database verification" };
|
||||
assert.equal(await refreshServerUpdateState("recovery-case"), pending);
|
||||
pending = null;
|
||||
assert.equal(await refreshServerUpdateState("recovery-case"), null);
|
||||
});
|
||||
|
||||
test("a rejected recheck removes an earlier cached update offer", async () => {
|
||||
const original = globalThis.__hotfixApi.checkUpdate;
|
||||
try {
|
||||
globalThis.__hotfixApi.checkUpdate = async () => ({ from_version: "0.261005.22", to_version: "0.261005.24", items: [], migrations: 1, pending_migrations: 1 });
|
||||
await checkServerUpdate("stale-offer");
|
||||
assert.equal(useServerUpdate("stale-offer").available, true);
|
||||
globalThis.__hotfixApi.checkUpdate = async () => { throw new Error("Installed version is newer than package"); };
|
||||
await checkServerUpdate("stale-offer");
|
||||
assert.equal(useServerUpdate("stale-offer").available, false);
|
||||
assert.equal(useServerUpdate("stale-offer").preview, null);
|
||||
} finally { globalThis.__hotfixApi.checkUpdate = original; }
|
||||
});
|
||||
@@ -0,0 +1,18 @@
|
||||
import assert from "node:assert/strict";
|
||||
import test from "node:test";
|
||||
import { isUpdateCurrent } from "../src/lib/serverUpdateStatus.ts";
|
||||
|
||||
const same = { from_version: "1", to_version: "1", items: [{ action: "skip" }], migrations: 10 };
|
||||
|
||||
test("same files and version cannot hide pending database repairs", () => {
|
||||
assert.equal(isUpdateCurrent({ ...same, pending_migrations: 1 }), false);
|
||||
assert.equal(isUpdateCurrent({ ...same, pending_migrations: 0 }), true);
|
||||
});
|
||||
test("unknown history is not presented as up to date", () => {
|
||||
assert.equal(isUpdateCurrent(same), false);
|
||||
assert.equal(isUpdateCurrent({ ...same, migrations: 0 }), true);
|
||||
});
|
||||
test("file changes and new releases remain available with no pending SQL", () => {
|
||||
assert.equal(isUpdateCurrent({ ...same, pending_migrations: 0, items: [{ action: "replace" }] }), false);
|
||||
assert.equal(isUpdateCurrent({ ...same, pending_migrations: 0, to_version: "2" }), false);
|
||||
});
|
||||
@@ -1,133 +0,0 @@
|
||||
param(
|
||||
[Parameter(Mandatory)][string]$BasePackage,
|
||||
[Parameter(Mandatory)][string]$CandidatePackage,
|
||||
[string]$DataSource = '',
|
||||
[string]$PreviousPackage = '',
|
||||
[ValidateSet('coa','wildcard','dual','squid','imported')][string]$Mode = 'coa',
|
||||
[switch]$SkipBuild,
|
||||
[string]$ReportFile = '',
|
||||
[string]$Target = (Join-Path $env:RUNNER_TEMP ('coa-schema-fixture-chaos-' + [guid]::NewGuid().ToString('N')))
|
||||
)
|
||||
$ErrorActionPreference = 'Stop'
|
||||
$project = Split-Path $PSScriptRoot -Parent
|
||||
$tool = Join-Path $project 'target/debug/coa-release.exe'
|
||||
$test = Join-Path $project 'target/debug/examples/update_acceptance_e2e.exe'
|
||||
if (Test-Path -LiteralPath $Target) { throw 'Use a new disposable fixture directory.' }
|
||||
if ((Split-Path $Target -Leaf) -notlike 'coa-schema-fixture-chaos-*') { throw 'Invalid disposable fixture name.' }
|
||||
if (-not $SkipBuild) {
|
||||
& cargo build --manifest-path "$project/Cargo.toml" -p coa-release -p coa-core --example update_acceptance_e2e --features coa-core/testkit --locked
|
||||
if ($LASTEXITCODE) { throw 'Could not build acceptance tools.' }
|
||||
& cargo build --manifest-path "$project/Cargo.toml" -p coa-release --locked
|
||||
if ($LASTEXITCODE) { throw 'Could not build release tools.' }
|
||||
}
|
||||
if (-not (Test-Path -LiteralPath $tool) -or -not (Test-Path -LiteralPath $test)) { throw 'Acceptance tools are missing.' }
|
||||
& $tool extract-schema-base --package $BasePackage --fixture $Target
|
||||
if ($LASTEXITCODE) { throw 'Could not prepare the signed base.' }
|
||||
[IO.File]::WriteAllText((Join-Path $Target '.coa-chaos-fixture'), 'disposable update chaos fixture')
|
||||
# A real independent copy: a junction would allow validation to modify source data.
|
||||
if ($DataSource) {
|
||||
& robocopy $DataSource (Join-Path $Target 'Data') /E /R:1 /W:1 /NFL /NDL /NJH /NJS /NP | Out-Null
|
||||
if ($LASTEXITCODE -ge 8) { throw 'Could not copy isolated game data.' }
|
||||
} else {
|
||||
& $tool extract-game-data --package $BasePackage --fixture $Target
|
||||
if ($LASTEXITCODE) { throw 'Could not extract signed game data.' }
|
||||
}
|
||||
& $test init $Target
|
||||
if ($LASTEXITCODE) { throw 'Could not initialize sentinels.' }
|
||||
& $test seed-players $Target
|
||||
if ($LASTEXITCODE) { throw 'Could not seed real account, character and inventory records.' }
|
||||
if ($PreviousPackage) {
|
||||
& $test baseline-release $Target $PreviousPackage
|
||||
if ($LASTEXITCODE) { throw 'Previous published release could not be established.' }
|
||||
}
|
||||
& $test apply $Target $CandidatePackage
|
||||
if ($LASTEXITCODE) { throw 'Candidate failed acceptance.' }
|
||||
& $test prepare-mode $Target $Mode
|
||||
if ($LASTEXITCODE) { throw "Could not prepare $Mode installation." }
|
||||
if ($PreviousPackage) {
|
||||
# Re-establish the old signed release after mode provisioning, so the actual
|
||||
# upgrade below runs in this mode rather than only in the initial CoA setup.
|
||||
& $test baseline-release $Target $PreviousPackage
|
||||
if ($LASTEXITCODE) { throw "Previous release could not be established in $Mode mode." }
|
||||
}
|
||||
& $test seed-config $Target
|
||||
if ($LASTEXITCODE) { throw 'Could not seed a modified user configuration.' }
|
||||
& $test break-legacy-baseline $Target
|
||||
if ($LASTEXITCODE) { throw 'Could not inject missing-table baseline.' }
|
||||
& $test apply $Target $CandidatePackage
|
||||
if ($LASTEXITCODE) { throw 'Legacy missing-table baseline was not repaired.' }
|
||||
& $test verify $Target
|
||||
if ($LASTEXITCODE) { throw 'Sentinels were lost.' }
|
||||
foreach ($rejection in @('expect-corrupt-package','expect-locked-file','expect-occupied-port')) {
|
||||
& $test $rejection $Target $CandidatePackage
|
||||
if ($LASTEXITCODE) { throw "$rejection did not reject safely." }
|
||||
}
|
||||
$oldPythonFailure = $env:COA_UPDATE_PYTHON_FAILURE
|
||||
try {
|
||||
$env:COA_UPDATE_PYTHON_FAILURE = '1'
|
||||
& $test expect-rejection $Target $CandidatePackage
|
||||
if ($LASTEXITCODE) { throw 'Python failure was not restored.' }
|
||||
} finally { $env:COA_UPDATE_PYTHON_FAILURE = $oldPythonFailure }
|
||||
$oldValidation = $env:COA_UPDATE_VALIDATION
|
||||
try {
|
||||
$env:COA_UPDATE_VALIDATION = '1'
|
||||
& $test start-fixture $Target
|
||||
if ($LASTEXITCODE) { throw 'Original offline fixture could not start.' }
|
||||
$env:COA_UPDATE_PYTHON_FAILURE = '1'
|
||||
& $test expect-rejection $Target $CandidatePackage
|
||||
if ($LASTEXITCODE) { throw 'The originally running server was not restored.' }
|
||||
} finally {
|
||||
$env:COA_UPDATE_PYTHON_FAILURE = $oldPythonFailure
|
||||
& $test stop-fixture $Target
|
||||
$stopResult = $LASTEXITCODE
|
||||
$env:COA_UPDATE_VALIDATION = $oldValidation
|
||||
if ($stopResult) { throw 'The offline running-state fixture could not be stopped.' }
|
||||
}
|
||||
$oldSqlFailure = $env:COA_UPDATE_SQL_FAILURE
|
||||
try {
|
||||
& $test break-legacy-baseline $Target
|
||||
if ($LASTEXITCODE) { throw 'Could not prepare partial-DDL failure.' }
|
||||
$env:COA_UPDATE_SQL_FAILURE = 'manager_repair__20261005_reconcile_wildcard_tables'
|
||||
& $test expect-rejection $Target $CandidatePackage
|
||||
if ($LASTEXITCODE) { throw 'Partial DDL/SQL failure was not restored.' }
|
||||
} finally { $env:COA_UPDATE_SQL_FAILURE = $oldSqlFailure }
|
||||
$oldCrash = $env:COA_UPDATE_CRASH_AT
|
||||
try {
|
||||
$env:COA_UPDATE_CRASH_AT = 'snapshot-recorded'
|
||||
& $test apply $Target $CandidatePackage
|
||||
if ($LASTEXITCODE -ne 91) { throw 'The recorded-snapshot interruption was not exercised.' }
|
||||
$env:COA_UPDATE_CRASH_AT = ''
|
||||
foreach ($corruption in @('expect-corrupt-journal','expect-corrupt-recovery-point')) {
|
||||
& $test $corruption $Target
|
||||
if ($LASTEXITCODE) { throw "Corruption guard $corruption failed." }
|
||||
}
|
||||
& $test rollback $Target
|
||||
if ($LASTEXITCODE) { throw 'Recovery after removing injected corruption failed.' }
|
||||
foreach ($point in @('stopped','snapshot','trial','before-file:0','journal-file:0','written-file:0','completed-file:0','applied','before-migrations','before-sql:manager_repair__20261005_reconcile_wildcard_tables','after-sql:manager_repair__20261005_reconcile_wildcard_tables','recorded-sql:manager_repair__20261005_reconcile_wildcard_tables','migrated','validated','before-commit','commit-metadata')) {
|
||||
$env:COA_UPDATE_CRASH_AT = ''
|
||||
& $test break-legacy-baseline $Target
|
||||
if ($LASTEXITCODE) { throw 'Could not reset isolated baseline.' }
|
||||
& $test dirty-fixture $Target $CandidatePackage
|
||||
if ($LASTEXITCODE) { throw 'Could not arrange a real file replacement.' }
|
||||
$env:COA_UPDATE_CRASH_AT = $point
|
||||
& $test apply $Target $CandidatePackage
|
||||
if ($LASTEXITCODE -ne 91) { throw "Fault point $point was not exercised (exit $LASTEXITCODE)." }
|
||||
foreach ($recoveryPoint in @('restore-stopped','restore-databases','restore-files')) {
|
||||
$env:COA_UPDATE_CRASH_AT = $recoveryPoint
|
||||
& $test rollback $Target
|
||||
# restore-databases may not be reached before any live database changes.
|
||||
if ($LASTEXITCODE -notin @(0,91)) { throw "Recovery fault $recoveryPoint failed." }
|
||||
if ($LASTEXITCODE -eq 0) { break }
|
||||
}
|
||||
$env:COA_UPDATE_CRASH_AT = ''
|
||||
& $test rollback $Target
|
||||
if ($LASTEXITCODE) { throw "Recovery from $point failed." }
|
||||
}
|
||||
} finally { $env:COA_UPDATE_CRASH_AT = $oldCrash }
|
||||
$manifest = Get-Content (Join-Path $CandidatePackage 'manifest.json') -Raw | ConvertFrom-Json
|
||||
$managerSource = (& git -C $project rev-parse HEAD).Trim()
|
||||
if ($LASTEXITCODE -or $managerSource -notmatch '^[0-9a-f]{40}$') { throw 'Cannot identify the tested manager source.' }
|
||||
$report = @{ schema = 1; version = $manifest.version; manifestSha256 = (Get-FileHash (Join-Path $CandidatePackage 'manifest.json') -Algorithm SHA256).Hash.ToLower(); manager = (Get-FileHash $test -Algorithm SHA256).Hash.ToLower(); managerSource = $managerSource; mode = $Mode; baseline = $(if ($PreviousPackage) { (Get-Content (Join-Path $PreviousPackage 'manifest.json') -Raw | ConvertFrom-Json).version } else { 'base' }); result = 'passed' }
|
||||
$report.coverage = @('signed-package-corruption','locked-file','occupied-port','python-startup-failure','partial-ddl-invalid-sql','update-process-crash','recovery-process-crash','modified-config-preservation','running-state-recovery','player-data-preservation','corrupt-journal','corrupt-recovery-point')
|
||||
if (-not $ReportFile) { $ReportFile = Join-Path $CandidatePackage 'acceptance.json' }
|
||||
$report | ConvertTo-Json | Set-Content $ReportFile -Encoding utf8NoBOM
|
||||
@@ -1,81 +0,0 @@
|
||||
param(
|
||||
[Parameter(Mandatory)][string]$BasePackage,
|
||||
[Parameter(Mandatory)][string]$CandidatePackage,
|
||||
[string]$PreviousPackage = '',
|
||||
[string]$DataSource = '',
|
||||
[ValidateRange(1,5)][int]$MaxParallel = 2,
|
||||
[string]$WorkDirectory = (Join-Path $env:RUNNER_TEMP ('coa-acceptance-' + [guid]::NewGuid().ToString('N')))
|
||||
)
|
||||
$ErrorActionPreference = 'Stop'
|
||||
$project = Split-Path $PSScriptRoot -Parent
|
||||
& git -C $project diff --quiet HEAD --
|
||||
if ($LASTEXITCODE) { throw 'Release acceptance requires committed manager source; tracked changes are present.' }
|
||||
$untrackedSource = & git -C $project ls-files --others --exclude-standard -- crates src src-tauri tools .github
|
||||
if ($LASTEXITCODE -or $untrackedSource) { throw 'Release acceptance requires committed manager source; untracked source files are present.' }
|
||||
$base = (Resolve-Path -LiteralPath $BasePackage).Path
|
||||
$candidate = (Resolve-Path -LiteralPath $CandidatePackage).Path
|
||||
$previous = if ($PreviousPackage) { (Resolve-Path -LiteralPath $PreviousPackage).Path } else { '' }
|
||||
$data = if ($DataSource) { (Resolve-Path -LiteralPath $DataSource).Path } else { '' }
|
||||
if (Test-Path -LiteralPath $WorkDirectory) { throw 'Use a fresh acceptance work directory.' }
|
||||
New-Item -ItemType Directory -Path $WorkDirectory | Out-Null
|
||||
$work = (Resolve-Path -LiteralPath $WorkDirectory).Path
|
||||
& cargo build --manifest-path "$project/Cargo.toml" -p coa-core --example update_acceptance_e2e --features testkit --locked
|
||||
if ($LASTEXITCODE) { throw 'Could not build the marked-fixture acceptance tool.' }
|
||||
& cargo build --manifest-path "$project/Cargo.toml" -p coa-release --locked
|
||||
if ($LASTEXITCODE) { throw 'Could not build signature verification tools.' }
|
||||
|
||||
$queue = [Collections.Generic.Queue[object]]::new()
|
||||
foreach ($mode in @('coa','wildcard','dual','squid','imported')) {
|
||||
$queue.Enqueue(@{ mode=$mode; baseline='base'; previous='' })
|
||||
if ($previous) { $queue.Enqueue(@{ mode=$mode; baseline='previous'; previous=$previous }) }
|
||||
}
|
||||
$active = [Collections.Generic.List[object]]::new()
|
||||
$completed = [Collections.Generic.List[object]]::new()
|
||||
try {
|
||||
while ($queue.Count -or $active.Count) {
|
||||
while ($queue.Count -and $active.Count -lt $MaxParallel) {
|
||||
$job = $queue.Dequeue()
|
||||
$name = "$($job.mode)-$($job.baseline)"
|
||||
$report = Join-Path $work "$name.json"
|
||||
$target = Join-Path $work "coa-schema-fixture-chaos-$name"
|
||||
$arguments = @('-NoProfile','-File', ('"' + (Join-Path $PSScriptRoot 'update-chaos-gate.ps1') + '"'), '-SkipBuild', '-BasePackage', ('"' + $base + '"'), '-CandidatePackage', ('"' + $candidate + '"'), '-Target', ('"' + $target + '"'), '-Mode', $job.mode, '-ReportFile', ('"' + $report + '"'))
|
||||
if ($job.previous) { $arguments += @('-PreviousPackage', ('"' + $job.previous + '"')) }
|
||||
if ($data) { $arguments += @('-DataSource', ('"' + $data + '"')) }
|
||||
$process = Start-Process -FilePath (Get-Process -Id $PID).Path -ArgumentList $arguments -WindowStyle Hidden -PassThru -RedirectStandardOutput (Join-Path $work "$name.log") -RedirectStandardError (Join-Path $work "$name.errors.log")
|
||||
$active.Add(@{ process=$process; name=$name; report=$report })
|
||||
Write-Output "Started isolated $name acceptance"
|
||||
}
|
||||
foreach ($job in @($active.ToArray())) {
|
||||
$job.process.Refresh()
|
||||
if (-not $job.process.HasExited) { continue }
|
||||
$job.process.WaitForExit()
|
||||
if ($job.process.ExitCode -ne 0 -or -not (Test-Path -LiteralPath $job.report)) {
|
||||
throw "Acceptance $($job.name) failed. Logs and marked copies are preserved at $work."
|
||||
}
|
||||
$completed.Add((Get-Content -LiteralPath $job.report -Raw | ConvertFrom-Json))
|
||||
$active.Remove($job) | Out-Null
|
||||
Write-Output "Passed isolated $($job.name) acceptance"
|
||||
}
|
||||
if ($active.Count) { Start-Sleep -Seconds 1 }
|
||||
}
|
||||
} catch {
|
||||
# Do not kill recovery processes or remove their copies. Each active fixture completes
|
||||
# independently; the parent fails publication immediately.
|
||||
throw
|
||||
}
|
||||
$manifestHash = (Get-FileHash (Join-Path $candidate 'manifest.json')).Hash.ToLower()
|
||||
$manifest = Get-Content (Join-Path $candidate 'manifest.json') -Raw | ConvertFrom-Json
|
||||
foreach ($result in $completed) {
|
||||
if ($result.result -ne 'passed' -or $result.manifestSha256 -ne $manifestHash -or $result.version -ne $manifest.version -or $result.managerSource -ne $completed[0].managerSource) { throw 'Acceptance results refer to different source or package bytes.' }
|
||||
}
|
||||
$expected = if ($previous) { 10 } else { 5 }
|
||||
if ($completed.Count -ne $expected) { throw 'Incomplete update acceptance matrix.' }
|
||||
$requiredCoverage = @('signed-package-corruption','locked-file','occupied-port','python-startup-failure','partial-ddl-invalid-sql','update-process-crash','recovery-process-crash','modified-config-preservation','running-state-recovery','player-data-preservation','disk-exhaustion','write-denial','corrupt-journal','corrupt-recovery-point','database-process-crash','new-server-crash','network-action-containment','all-file-operation-phases')
|
||||
$missingCoverage = @($requiredCoverage | Where-Object {
|
||||
$required = $_
|
||||
@($completed | Where-Object { $required -notin $_.coverage }).Count -gt 0
|
||||
})
|
||||
$combined = @{ schema=1; result=$(if ($missingCoverage.Count) { 'incomplete' } else { 'passed' }); version=$manifest.version; manifestSha256=$manifestHash; manager=$completed[0].manager; managerSource=$completed[0].managerSource; scenarios=$completed.ToArray(); missingCoverage=$missingCoverage }
|
||||
$combined | ConvertTo-Json -Depth 10 | Set-Content (Join-Path $candidate 'acceptance.json') -Encoding utf8NoBOM
|
||||
if ($missingCoverage.Count) { throw "Publication is blocked: release fault coverage is incomplete ($($missingCoverage -join ', ')). Scenario results were preserved." }
|
||||
Write-Output "Passed all $expected update acceptance scenarios"
|
||||
Reference in new issue
Block a user