mirror of
https://github.com/Corfirean/coa-server-manager.git
synced 2026-11-19 03:25:56 +00:00
Compare commits
38
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
f126cb4ed0 | ||
|
|
fdbf38ee4e | ||
|
|
6091e545f8 | ||
|
|
2e6fcceb05 | ||
|
|
5ccd8871d1 | ||
|
|
abcc816581 | ||
|
|
1ee17f8415 | ||
|
|
71ffd568bb | ||
|
|
8353b791fb | ||
|
|
b81227b0ea | ||
|
|
a9fb982ab0 | ||
|
|
a822bfc99b | ||
|
|
1211de5a77 | ||
|
|
ee36692db7 | ||
|
|
ee43522019 | ||
|
|
a0d3cc08ce | ||
|
|
89e2abb642 | ||
|
|
b4dc30b84a | ||
|
|
73a6cca753 | ||
|
|
705bee7d56 | ||
|
|
5aa9b32283 | ||
|
|
711f378ae8 | ||
|
|
c29d56e2b3 | ||
|
|
d63e85bb18 | ||
|
|
c513649beb | ||
|
|
db23c9b098 | ||
|
|
f62729d281 | ||
|
|
e7744dfc7c | ||
|
|
899b7c6617 | ||
|
|
3987f1b2ff | ||
|
|
b647e62ca6 | ||
|
|
d990efcfad | ||
|
|
9f48cfc8d5 | ||
|
|
3866e219ce | ||
|
|
2224afd2ea | ||
|
|
6723a7eda1 | ||
|
|
b65b632c63 | ||
|
|
1a1976d9ad |
No files matched your search
@@ -26,5 +26,4 @@ jobs:
|
|||||||
- run: node tools/check-i18n.mjs
|
- run: node tools/check-i18n.mjs
|
||||||
- run: npm run build
|
- run: npm run build
|
||||||
- run: node --experimental-strip-types --test tools/*.test.mjs
|
- run: node --experimental-strip-types --test tools/*.test.mjs
|
||||||
- run: python -B -m unittest discover -s tools -p test_launcher_bridge.py
|
|
||||||
- run: cargo test --workspace --locked
|
- run: cargo test --workspace --locked
|
||||||
@@ -69,10 +69,11 @@ jobs:
|
|||||||
with:
|
with:
|
||||||
node-version: 22
|
node-version: 22
|
||||||
- run: npm ci
|
- run: npm ci
|
||||||
|
# tauri::generate_context! needs ../dist; without a warm target cache the tests do not compile without it.
|
||||||
|
- run: npm run build
|
||||||
- name: Tests
|
- name: Tests
|
||||||
run: cargo test --workspace --locked -- --test-threads=1
|
run: cargo test --workspace --locked -- --test-threads=1
|
||||||
- run: node --experimental-strip-types --test tools/*.test.mjs
|
- run: node --experimental-strip-types --test tools/*.test.mjs
|
||||||
- run: python -B -m unittest discover -s tools -p test_launcher_bridge.py
|
|
||||||
- name: Build and sign (publish only when requested)
|
- name: Build and sign (publish only when requested)
|
||||||
id: tauri
|
id: tauri
|
||||||
uses: tauri-apps/tauri-action@v0
|
uses: tauri-apps/tauri-action@v0
|
||||||
|
|||||||
@@ -0,0 +1,72 @@
|
|||||||
|
name: sign-local-installer
|
||||||
|
on:
|
||||||
|
push:
|
||||||
|
branches: [release/20261108-manager]
|
||||||
|
workflow_dispatch:
|
||||||
|
inputs:
|
||||||
|
build_run_id:
|
||||||
|
description: Successful manager-local run in coa-server-build
|
||||||
|
required: true
|
||||||
|
permissions:
|
||||||
|
contents: read
|
||||||
|
actions: read
|
||||||
|
jobs:
|
||||||
|
sign:
|
||||||
|
if: github.event_name == 'workflow_dispatch'
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
steps:
|
||||||
|
- uses: actions/checkout@v7
|
||||||
|
- uses: actions/setup-node@v4
|
||||||
|
with:
|
||||||
|
node-version: 22
|
||||||
|
- name: Verify local build provenance
|
||||||
|
env:
|
||||||
|
GH_TOKEN: ${{ github.token }}
|
||||||
|
BUILD_RUN: ${{ inputs.build_run_id }}
|
||||||
|
run: |
|
||||||
|
python3 - <<'PY'
|
||||||
|
import json, os, subprocess
|
||||||
|
run = os.environ['BUILD_RUN']
|
||||||
|
if not run.isdigit():
|
||||||
|
raise RuntimeError('Invalid build run')
|
||||||
|
data = json.loads(subprocess.check_output(['gh', 'api', f'repos/Corfirean/coa-server-build/actions/runs/{run}']))
|
||||||
|
if data['conclusion'] != 'success' or data['path'] != '.github/workflows/manager-local.yml':
|
||||||
|
raise RuntimeError('Not a successful local Manager build')
|
||||||
|
subprocess.run(['gh', 'run', 'download', run, '-R', 'Corfirean/coa-server-build', '-n', 'unsigned-manager-windows', '-D', '_prepared-manager'], check=True)
|
||||||
|
from pathlib import Path
|
||||||
|
import hashlib
|
||||||
|
root = Path('_prepared-manager')
|
||||||
|
meta = json.loads((root / 'prepared-source.json').read_text())
|
||||||
|
version = json.loads(Path('package.json').read_text())['version']
|
||||||
|
name = meta['installer']
|
||||||
|
if Path(name).name != name or meta['source'] != os.environ['GITHUB_SHA'] or meta['version'] != version or str(meta['run']) != run:
|
||||||
|
raise RuntimeError('Installer identity differs')
|
||||||
|
if hashlib.sha256((root / name).read_bytes()).hexdigest() != meta['sha256']:
|
||||||
|
raise RuntimeError('Installer hash differs')
|
||||||
|
PY
|
||||||
|
- run: npm ci
|
||||||
|
- name: Sign exact locally compiled bytes
|
||||||
|
env:
|
||||||
|
TAURI_SIGNING_PRIVATE_KEY: ${{ secrets.TAURI_SIGNING_PRIVATE_KEY }}
|
||||||
|
TAURI_SIGNING_PRIVATE_KEY_PASSWORD: ${{ secrets.TAURI_SIGNING_PRIVATE_KEY_PASSWORD }}
|
||||||
|
run: |
|
||||||
|
node --input-type=module <<'JS'
|
||||||
|
import { readFileSync, writeFileSync } from 'node:fs';
|
||||||
|
import { execFileSync } from 'node:child_process';
|
||||||
|
import { createHash } from 'node:crypto';
|
||||||
|
const root = '_prepared-manager/';
|
||||||
|
const meta = JSON.parse(readFileSync(root + 'prepared-source.json'));
|
||||||
|
execFileSync('node_modules/.bin/tauri', ['signer', 'sign', '--app-version', meta.version, root + meta.installer], {stdio: 'inherit'});
|
||||||
|
if (createHash('sha256').update(readFileSync(root + meta.installer)).digest('hex') !== meta.sha256) throw new Error('Signed bytes changed');
|
||||||
|
const signature = readFileSync(root + meta.installer + '.sig', 'utf8').trim();
|
||||||
|
const url = `https://github.com/Corfirean/coa-server-manager/releases/download/v${meta.version}/${encodeURIComponent(meta.installer)}`;
|
||||||
|
writeFileSync(root + 'latest.json', JSON.stringify({version: meta.version, notes: 'See the release notes.', pub_date: new Date().toISOString(), platforms: {'windows-x86_64': {signature, url}}}, null, 2) + '\n');
|
||||||
|
meta.signingRun = process.env.GITHUB_RUN_ID;
|
||||||
|
writeFileSync(root + 'prepared-source.json', JSON.stringify(meta, null, 2) + '\n');
|
||||||
|
JS
|
||||||
|
- uses: actions/upload-artifact@v4
|
||||||
|
with:
|
||||||
|
name: prepared-manager-windows
|
||||||
|
path: _prepared-manager/*
|
||||||
|
retention-days: 14
|
||||||
|
if-no-files-found: error
|
||||||
@@ -8,6 +8,12 @@ Published releases and previews. Pre-release entries do not change the stable up
|
|||||||
|
|
||||||
Dates follow GitHub publication (UTC); legacy records retain their archived dates. Newest releases first.
|
Dates follow GitHub publication (UTC); legacy records retain their archived dates. Newest releases first.
|
||||||
|
|
||||||
|
## 0.9.10 — 2026-11-08
|
||||||
|
|
||||||
|
- Custom Races patch installation recovers from interrupted downloads.
|
||||||
|
|
||||||
|
[Release](https://github.com/Corfirean/coa-server-manager/releases/tag/v0.9.10) · [Source changes](https://github.com/Corfirean/coa-server-manager/compare/v0.9.9...v0.9.10)
|
||||||
|
|
||||||
## 0.9.9 — 2026-11-04
|
## 0.9.9 — 2026-11-04
|
||||||
|
|
||||||
- Update and recovery checks use the temporary login port even with a Windows override.
|
- Update and recovery checks use the temporary login port even with a Windows override.
|
||||||
|
|||||||
Generated
+29
-4
@@ -586,7 +586,7 @@ dependencies = [
|
|||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "coa-core"
|
name = "coa-core"
|
||||||
version = "0.9.9"
|
version = "0.9.11"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"base64 0.22.1",
|
"base64 0.22.1",
|
||||||
"chrono",
|
"chrono",
|
||||||
@@ -606,6 +606,7 @@ dependencies = [
|
|||||||
"serde_json",
|
"serde_json",
|
||||||
"sha1",
|
"sha1",
|
||||||
"sha2",
|
"sha2",
|
||||||
|
"socket2",
|
||||||
"tar",
|
"tar",
|
||||||
"tempfile",
|
"tempfile",
|
||||||
"thiserror 2.0.21",
|
"thiserror 2.0.21",
|
||||||
@@ -618,6 +619,15 @@ dependencies = [
|
|||||||
"zstd",
|
"zstd",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "coa-launcher"
|
||||||
|
version = "0.9.11"
|
||||||
|
dependencies = [
|
||||||
|
"coa-core",
|
||||||
|
"serde_json",
|
||||||
|
"windows-sys 0.60.2",
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "coa-registry-proto"
|
name = "coa-registry-proto"
|
||||||
version = "0.1.0"
|
version = "0.1.0"
|
||||||
@@ -634,7 +644,7 @@ dependencies = [
|
|||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "coa-release"
|
name = "coa-release"
|
||||||
version = "0.9.9"
|
version = "0.9.11"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"chrono",
|
"chrono",
|
||||||
"coa-core",
|
"coa-core",
|
||||||
@@ -772,7 +782,7 @@ dependencies = [
|
|||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "csm-modules-preview"
|
name = "csm-modules-preview"
|
||||||
version = "0.9.9"
|
version = "0.9.11"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"coa-control-proto",
|
"coa-control-proto",
|
||||||
"coa-core",
|
"coa-core",
|
||||||
@@ -786,8 +796,8 @@ dependencies = [
|
|||||||
"tauri-plugin-process",
|
"tauri-plugin-process",
|
||||||
"tauri-plugin-single-instance",
|
"tauri-plugin-single-instance",
|
||||||
"tauri-plugin-updater",
|
"tauri-plugin-updater",
|
||||||
|
"tauri-plugin-window-state",
|
||||||
"tracing",
|
"tracing",
|
||||||
"uuid",
|
|
||||||
]
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
@@ -4657,6 +4667,21 @@ dependencies = [
|
|||||||
"zip 4.6.1",
|
"zip 4.6.1",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "tauri-plugin-window-state"
|
||||||
|
version = "2.5.0"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "5d6815cab7b212f9cfe16a9d79d8d22f9e14159e4a9460f7dec1467167a008e3"
|
||||||
|
dependencies = [
|
||||||
|
"bitflags 2.13.2",
|
||||||
|
"log",
|
||||||
|
"serde",
|
||||||
|
"serde_json",
|
||||||
|
"tauri",
|
||||||
|
"tauri-plugin",
|
||||||
|
"thiserror 2.0.21",
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "tauri-runtime"
|
name = "tauri-runtime"
|
||||||
version = "2.12.0"
|
version = "2.12.0"
|
||||||
|
|||||||
+2
-2
@@ -1,10 +1,10 @@
|
|||||||
[workspace]
|
[workspace]
|
||||||
resolver = "2"
|
resolver = "2"
|
||||||
members = ["crates/coa-core", "crates/coa-release", "crates/coa-registry-proto", "crates/coa-control-proto", "src-tauri"]
|
members = ["crates/coa-core", "crates/coa-launcher", "crates/coa-release", "crates/coa-registry-proto", "crates/coa-control-proto", "src-tauri"]
|
||||||
exclude = ["services/coa-registry", "services/coa-registry-e2e", "services/coa-coordinator", "services/coa-relay"]
|
exclude = ["services/coa-registry", "services/coa-registry-e2e", "services/coa-coordinator", "services/coa-relay"]
|
||||||
|
|
||||||
[workspace.package]
|
[workspace.package]
|
||||||
version = "0.9.9"
|
version = "0.9.11"
|
||||||
edition = "2021"
|
edition = "2021"
|
||||||
license = "AGPL-3.0-only"
|
license = "AGPL-3.0-only"
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,7 @@
|
|||||||
|
---
|
||||||
|
area: manager
|
||||||
|
type: fixed
|
||||||
|
audience: admins
|
||||||
|
title: Custom Races patch installation recovers from interrupted downloads
|
||||||
|
---
|
||||||
|
Unfinished downloads resume automatically. Invalid archives in Downloads are skipped without changing them, and damaged cached archives are downloaded again.
|
||||||
@@ -4,4 +4,4 @@ type: added
|
|||||||
audience: admins
|
audience: admins
|
||||||
title: Install the compiler for modules from the Manager
|
title: Install the compiler for modules from the Manager
|
||||||
---
|
---
|
||||||
When the C++ compiler that modules need is missing or differs from the one the core was built with, the Toolchain tab offers to install Visual Studio Build Tools with MSVC 14.44. The Manager downloads Microsoft's installer, checks that Microsoft signed it and opens it with the needed components selected; you accept Microsoft's terms there.
|
When the compiler modules need is missing or does not match the core, the Toolchain tab offers to install Visual Studio Build Tools with MSVC 14.44. The Manager checks Microsoft's signature on the installer and opens it with the needed parts selected.
|
||||||
@@ -4,4 +4,4 @@ type: added
|
|||||||
audience: admins
|
audience: admins
|
||||||
title: Modules are rebuilt automatically after a core update
|
title: Modules are rebuilt automatically after a core update
|
||||||
---
|
---
|
||||||
After the core is updated, the Manager rebuilds every enabled module for the new core before the first start, or reuses a build it already has. A module that cannot be rebuilt is switched off with the reason shown, and the core update still goes ahead. Rolling back the core puts the earlier module builds back.
|
After a core update, every enabled module is rebuilt for the new core before the first start, or an existing build is reused. A module that cannot be rebuilt is switched off with the reason shown. Rolling back the core restores the earlier builds.
|
||||||
@@ -4,4 +4,4 @@ type: added
|
|||||||
audience: admins
|
audience: admins
|
||||||
title: Moving to a core with modules installs the modules you used
|
title: Moving to a core with modules installs the modules you used
|
||||||
---
|
---
|
||||||
When a server moves to a core that loads Content Scaling, Companions or SQUID's Playerbots as modules, the Manager downloads them at the versions the core names, builds them and switches them on before the first start. Bots follow what the server used before: SQUID's Playerbots if it was switched on, otherwise Companions. A module you remove later is not installed again.
|
On a core that loads Content Scaling, Companions or SQUID's Playerbots as modules, the Manager installs them at the versions the core names before the first start. Bots follow what the server used: SQUID if it was on, else Companions. Removed modules stay removed.
|
||||||
@@ -0,0 +1,8 @@
|
|||||||
|
---
|
||||||
|
area: manager
|
||||||
|
type: changed
|
||||||
|
audience: admins
|
||||||
|
title: Dungeon Clear is shown and switched as part of SQUID's Playerbots
|
||||||
|
---
|
||||||
|
Dungeon Clear no longer has a card of its own, which said "Always on" while SQUID was off. It goes on
|
||||||
|
and off together with SQUID's Playerbots, and its settings open from the SQUID card.
|
||||||
@@ -0,0 +1,7 @@
|
|||||||
|
---
|
||||||
|
area: manager
|
||||||
|
type: changed
|
||||||
|
audience: admins
|
||||||
|
title: Modules Preview installs a bare modular core and copies classic servers
|
||||||
|
---
|
||||||
|
A new server gets the modular core and compiles no module; add modules later on the Modules page. An existing classic server is not converted: a modular server is installed next to it with its accounts, characters, world, bots and module settings copied. The old server keeps working.
|
||||||
@@ -0,0 +1,7 @@
|
|||||||
|
---
|
||||||
|
area: manager
|
||||||
|
type: added
|
||||||
|
audience: admins
|
||||||
|
title: Bot strength settings for CoA Companions
|
||||||
|
---
|
||||||
|
A Bot Strength section in the bot settings: turn bot help on or off, choose where it applies (dungeons, raids, PvP, open world) and set bot damage, healing, damage taken and tank threat. All multipliers start at 1, so nothing changes until you raise them.
|
||||||
@@ -0,0 +1,7 @@
|
|||||||
|
---
|
||||||
|
area: manager
|
||||||
|
type: changed
|
||||||
|
audience: admins
|
||||||
|
title: The Manager starts and stops servers without Python
|
||||||
|
---
|
||||||
|
Start, stop and forced stop run inside the Manager, and errors name their cause (a busy port, missing files, a startup failure). Servers that include Scripts/coa-launcher.exe also run the world supervisor and bug-report relay without Python.
|
||||||
@@ -0,0 +1,7 @@
|
|||||||
|
---
|
||||||
|
area: manager
|
||||||
|
type: fixed
|
||||||
|
audience: admins
|
||||||
|
title: Server Migration shows the real server and makes a real modular copy
|
||||||
|
---
|
||||||
|
The page read nothing and reported a transfer that did not happen. It now shows the server's version, database state and counts, then makes the same modular copy as "Manage another server". World settings from Server Configuration now go along with the copy.
|
||||||
@@ -172,6 +172,7 @@
|
|||||||
"Corfirean/coa-server-manager:20261030-window-lifecycle.md",
|
"Corfirean/coa-server-manager:20261030-window-lifecycle.md",
|
||||||
"Corfirean/coa-server-manager:20261031-dungeon-clear-dependency.md",
|
"Corfirean/coa-server-manager:20261031-dungeon-clear-dependency.md",
|
||||||
"Corfirean/coa-server-manager:20261031-launcher-diagnostics-export.md",
|
"Corfirean/coa-server-manager:20261031-launcher-diagnostics-export.md",
|
||||||
|
"Corfirean/coa-server-manager:20261031-recover-client-patch-downloads.md",
|
||||||
"Corfirean/coa-server-manager:20261031-server-logging-controls.md",
|
"Corfirean/coa-server-manager:20261031-server-logging-controls.md",
|
||||||
"Corfirean/coa-server-manager:20261031-validation-bot-population.md",
|
"Corfirean/coa-server-manager:20261031-validation-bot-population.md",
|
||||||
"Corfirean/coa-server-manager:20261031-validation-mysql-reuse.md",
|
"Corfirean/coa-server-manager:20261031-validation-mysql-reuse.md",
|
||||||
@@ -900,6 +901,17 @@
|
|||||||
],
|
],
|
||||||
"commit": "173248efbe24da9b4c1b5ca12fa7580fcd1e8ea7",
|
"commit": "173248efbe24da9b4c1b5ca12fa7580fcd1e8ea7",
|
||||||
"compare": "https://github.com/Corfirean/coa-server-manager/compare/v0.9.8...v0.9.9"
|
"compare": "https://github.com/Corfirean/coa-server-manager/compare/v0.9.8...v0.9.9"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"tag": "v0.9.10",
|
||||||
|
"version": "0.9.10",
|
||||||
|
"date": "2026-11-08",
|
||||||
|
"url": "https://github.com/Corfirean/coa-server-manager/releases/tag/v0.9.10",
|
||||||
|
"notes": [
|
||||||
|
"Custom Races patch installation recovers from interrupted downloads"
|
||||||
|
],
|
||||||
|
"commit": "711f378ae82f75d3fc64368c042889c773315c54",
|
||||||
|
"compare": "https://github.com/Corfirean/coa-server-manager/compare/v0.9.9...v0.9.10"
|
||||||
}
|
}
|
||||||
]
|
]
|
||||||
}
|
}
|
||||||
@@ -5,6 +5,7 @@ edition.workspace = true
|
|||||||
license.workspace = true
|
license.workspace = true
|
||||||
|
|
||||||
[dependencies]
|
[dependencies]
|
||||||
|
socket2 = "0.6"
|
||||||
serde = { version = "1", features = ["derive"] }
|
serde = { version = "1", features = ["derive"] }
|
||||||
serde_json = "1"
|
serde_json = "1"
|
||||||
sha2 = "0.10"
|
sha2 = "0.10"
|
||||||
@@ -37,7 +38,7 @@ rand_core = { version = "0.6", features = ["getrandom"] }
|
|||||||
ed25519-dalek = { version = "2", features = ["rand_core"] }
|
ed25519-dalek = { version = "2", features = ["rand_core"] }
|
||||||
|
|
||||||
[target.'cfg(windows)'.dependencies]
|
[target.'cfg(windows)'.dependencies]
|
||||||
windows-sys = { version = "0.60", features = ["Win32_Foundation", "Win32_Storage_FileSystem", "Win32_System_Threading", "Win32_System_SystemInformation", "Win32_System_Diagnostics_ToolHelp", "Win32_NetworkManagement_IpHelper", "Win32_Networking_WinSock", "Win32_Security_Cryptography", "Win32_UI_Shell", "Win32_System_Registry", "Win32_UI_WindowsAndMessaging"] }
|
windows-sys = { version = "0.60", features = ["Win32_Foundation", "Win32_Storage_FileSystem", "Win32_System_Threading", "Win32_System_Console", "Win32_System_SystemInformation", "Win32_System_Diagnostics_ToolHelp", "Win32_NetworkManagement_IpHelper", "Win32_Networking_WinSock", "Win32_Security_Cryptography", "Win32_UI_Shell", "Win32_System_Registry", "Win32_UI_WindowsAndMessaging"] }
|
||||||
|
|
||||||
[features]
|
[features]
|
||||||
testkit = []
|
testkit = []
|
||||||
@@ -0,0 +1,7 @@
|
|||||||
|
//! Analyze a module by its GitHub link, as "Add from a link" does. usage: analyze_url <url> <cache dir>
|
||||||
|
fn main() {
|
||||||
|
let a: Vec<String> = std::env::args().skip(1).collect();
|
||||||
|
let r = coa_core::analyzer::analyze_github_repository(&a[0], Some(std::path::Path::new(&a[1]))).expect("analysis");
|
||||||
|
println!("{} @ {} cache_hit={:?}", r.repository_name, r.commit, r.cache_hit);
|
||||||
|
println!("classification {:?}; hooks {}; sql {}; cmake {}", r.classification, r.hooks.len(), r.sql_files.len(), r.has_cmakelists);
|
||||||
|
}
|
||||||
@@ -0,0 +1,58 @@
|
|||||||
|
//! Real MSVC + CMake + Ninja: after the build cache is packed and unpacked, a rebuild with nothing changed
|
||||||
|
//! compiles nothing, and a rebuild after one source changed compiles only that source.
|
||||||
|
//! usage: build_cache_ninja_check <empty folder>
|
||||||
|
use std::path::Path;
|
||||||
|
use std::process::Command;
|
||||||
|
|
||||||
|
fn build(root: &Path, dir: &Path, tc: &coa_core::build_engine::ToolchainStatus) -> String {
|
||||||
|
let bat = root.join("run.bat");
|
||||||
|
let ninja = Path::new(tc.ninja_path.as_ref().unwrap()).parent().unwrap().display().to_string();
|
||||||
|
std::fs::write(&bat, format!(
|
||||||
|
"@echo off\r\ncall \"{}\" > nul 2>&1\r\nset \"PATH={};%PATH%\"\r\n\"{}\" -G Ninja -S \"{}\" -B \"{}\\build\" -DCMAKE_BUILD_TYPE=RelWithDebInfo > nul\r\n\"{}\" --build \"{}\\build\" -- -d explain\r\n",
|
||||||
|
tc.vcvars64_path.as_ref().unwrap(), ninja, tc.cmake_path.as_ref().unwrap(), dir.display(), dir.display(), tc.cmake_path.as_ref().unwrap(), dir.display()
|
||||||
|
)).unwrap();
|
||||||
|
let out = Command::new("cmd.exe").args(["/c", &bat.to_string_lossy()]).output().unwrap();
|
||||||
|
assert!(out.status.success(), "{}{}", String::from_utf8_lossy(&out.stdout), String::from_utf8_lossy(&out.stderr));
|
||||||
|
String::from_utf8_lossy(&out.stdout).into_owned() + &String::from_utf8_lossy(&out.stderr)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn compiled(log: &str) -> usize {
|
||||||
|
log.lines().filter(|l| l.contains("Building CXX object")).count()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn main() {
|
||||||
|
let root = std::path::PathBuf::from(std::env::args().nth(1).expect("usage: build_cache_ninja_check <empty folder>"));
|
||||||
|
assert!(!root.exists() || std::fs::read_dir(&root).unwrap().next().is_none(), "folder must be new or empty");
|
||||||
|
std::fs::create_dir_all(root.join(".manager")).unwrap();
|
||||||
|
let tc = coa_core::build_engine::detect_toolchain();
|
||||||
|
assert!(tc.msvc_available && tc.cmake_available && tc.ninja_available, "toolchain: {tc:?}");
|
||||||
|
|
||||||
|
let dir = coa_core::build_cache::prepare(&root, "probe", "fp").unwrap();
|
||||||
|
std::fs::write(dir.join("CMakeLists.txt"), "cmake_minimum_required(VERSION 3.22)\nproject(p CXX)\nadd_library(p SHARED a.cpp b.cpp c.cpp)\n").unwrap();
|
||||||
|
for f in ["a", "b", "c"] {
|
||||||
|
std::fs::write(dir.join(format!("{f}.cpp")), format!("#include <vector>\n#include <string>\n__declspec(dllexport) int {f}() {{ return (int)std::vector<std::string>(3).size(); }}\n")).unwrap();
|
||||||
|
}
|
||||||
|
let first = build(&root, &dir, &tc);
|
||||||
|
println!("first build compiled {}", compiled(&first));
|
||||||
|
assert_eq!(compiled(&first), 3);
|
||||||
|
|
||||||
|
coa_core::build_cache::finish(&root, "probe");
|
||||||
|
let s = coa_core::build_cache::summary(&root, None);
|
||||||
|
println!("packed: {} bytes from {} unpacked", s.total_bytes, s.modules[0].unpacked_bytes);
|
||||||
|
assert!(!dir.exists());
|
||||||
|
|
||||||
|
let dir = coa_core::build_cache::prepare(&root, "probe", "fp").unwrap();
|
||||||
|
let again = build(&root, &dir, &tc);
|
||||||
|
println!("after unpack, nothing changed: compiled {}\n{}", compiled(&again), again.lines().filter(|l| l.contains("explain")).take(8).collect::<Vec<_>>().join("\n"));
|
||||||
|
assert_eq!(compiled(&again), 0, "nothing should be recompiled");
|
||||||
|
coa_core::build_cache::finish(&root, "probe");
|
||||||
|
|
||||||
|
let dir = coa_core::build_cache::prepare(&root, "probe", "fp").unwrap();
|
||||||
|
std::thread::sleep(std::time::Duration::from_secs(2));
|
||||||
|
std::fs::write(dir.join("b.cpp"), "__declspec(dllexport) int b() { return 2; }\n").unwrap();
|
||||||
|
let one = build(&root, &dir, &tc);
|
||||||
|
println!("after one change: compiled {}", compiled(&one));
|
||||||
|
assert_eq!(compiled(&one), 1);
|
||||||
|
coa_core::build_cache::finish(&root, "probe");
|
||||||
|
println!("PASS");
|
||||||
|
}
|
||||||
@@ -0,0 +1,194 @@
|
|||||||
|
//! Build the AzerothCore catalogue's modules against a plugin-host realm's SDK and record, per module, the
|
||||||
|
//! evidence: commit, analysis, build result, compiler errors and the core functions the host does not export.
|
||||||
|
//! A rerun skips modules that already have a result; `summary` aggregates the results.
|
||||||
|
//!
|
||||||
|
//! usage: catalog_build_sweep run <realm> <work dir> <how many, by stars>
|
||||||
|
//! catalog_build_sweep summary <work dir>
|
||||||
|
//! The realm needs only Core/worldserver.exe (a plugin host) and its .manager/sdk; use a disposable copy.
|
||||||
|
use std::collections::BTreeMap;
|
||||||
|
use std::path::{Path, PathBuf};
|
||||||
|
|
||||||
|
use serde::{Deserialize, Serialize};
|
||||||
|
|
||||||
|
#[derive(Serialize, Deserialize, Default)]
|
||||||
|
struct Outcome {
|
||||||
|
slug: String,
|
||||||
|
stars: u32,
|
||||||
|
category: String,
|
||||||
|
pushed_at: Option<String>,
|
||||||
|
commit: Option<String>,
|
||||||
|
/// "built" | "link-missing-exports" | "compile-error" | "not-a-plugin" | "analysis-failed" | "build-error"
|
||||||
|
result: String,
|
||||||
|
detail: Option<String>,
|
||||||
|
classification: Option<String>,
|
||||||
|
seconds: f64,
|
||||||
|
/// Core functions the plugin needs that worldserver.exe does not export (MSVC decorated names).
|
||||||
|
missing_exports: Vec<String>,
|
||||||
|
/// Demangled form of each missing export, for reading.
|
||||||
|
missing_readable: Vec<String>,
|
||||||
|
compile_errors: Vec<String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
fn file_name(slug: &str) -> String {
|
||||||
|
slug.replace('/', "__")
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The decorated name and its readable form out of an LNK2019/LNK2001 message.
|
||||||
|
fn missing_symbol(message: &str) -> Option<(String, String)> {
|
||||||
|
let readable = message.split('"').nth(1).unwrap_or("").to_string();
|
||||||
|
let start = message.find("(?")?;
|
||||||
|
let end = message[start..].find(')')? + start;
|
||||||
|
Some((message[start + 1..end].to_string(), readable))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn run(realm: &Path, work: &Path, count: usize) {
|
||||||
|
let results = work.join("results");
|
||||||
|
std::fs::create_dir_all(&results).unwrap();
|
||||||
|
let sources = work.join("sources");
|
||||||
|
let catalogue = coa_core::catalogue::fetch_or_load_catalogue(&work.join("catalogue"), false).expect("catalogue");
|
||||||
|
let mut items: Vec<_> = catalogue
|
||||||
|
.items
|
||||||
|
.into_iter()
|
||||||
|
.filter(|i| !matches!(i.coa_status, coa_core::catalogue::CoaCompatibilityStatus::Incompatible | coa_core::catalogue::CoaCompatibilityStatus::Blocked))
|
||||||
|
.collect();
|
||||||
|
items.sort_by(|a, b| b.stars.cmp(&a.stars));
|
||||||
|
let tc = coa_core::build_engine::detect_toolchain_for(Some(realm));
|
||||||
|
assert!(tc.msvc_available && tc.cmake_available && tc.ninja_available && tc.sdk_dir.is_some(), "toolchain/SDK for the realm: {tc:?}");
|
||||||
|
|
||||||
|
for (n, item) in items.iter().take(count).enumerate() {
|
||||||
|
let out = results.join(format!("{}.json", file_name(&item.full_name)));
|
||||||
|
if out.is_file() {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
let started = std::time::Instant::now();
|
||||||
|
let mut o = Outcome {
|
||||||
|
slug: item.full_name.clone(),
|
||||||
|
stars: item.stars,
|
||||||
|
category: item.category.clone(),
|
||||||
|
pushed_at: item.pushed_at.clone(),
|
||||||
|
..Default::default()
|
||||||
|
};
|
||||||
|
println!("[{}/{}] {} ★{}", n + 1, count.min(items.len()), item.full_name, item.stars);
|
||||||
|
match coa_core::analyzer::analyze_github_repository(&item.html_url, Some(&sources)) {
|
||||||
|
Err(e) => {
|
||||||
|
o.result = "analysis-failed".into();
|
||||||
|
o.detail = Some(e.to_string());
|
||||||
|
}
|
||||||
|
Ok(report) => {
|
||||||
|
o.commit = Some(report.commit.clone());
|
||||||
|
o.classification = Some(format!("{:?}", report.classification));
|
||||||
|
let path = PathBuf::from(&report.repository_path);
|
||||||
|
let path = if path.is_dir() { path } else {
|
||||||
|
sources.join("github").join(&item.owner).join(&item.name).join(&report.commit)
|
||||||
|
};
|
||||||
|
match coa_core::build_engine::build_module_with_bundle(&path, &[], realm, None, None) {
|
||||||
|
Err(e) => {
|
||||||
|
let text = e.to_string();
|
||||||
|
o.result = if text.contains("NO_LOADER_FOUND") || text.contains("No C++") || text.contains("MANUAL_ADAPTER") {
|
||||||
|
"not-a-plugin".into()
|
||||||
|
} else {
|
||||||
|
"build-error".into()
|
||||||
|
};
|
||||||
|
o.detail = Some(text);
|
||||||
|
}
|
||||||
|
Ok(b) if b.success => o.result = "built".into(),
|
||||||
|
Ok(b) => {
|
||||||
|
for e in &b.errors {
|
||||||
|
if e.error_code == "LNK2019" || e.error_code == "LNK2001" {
|
||||||
|
if let Some((mangled, readable)) = missing_symbol(&e.message) {
|
||||||
|
if !o.missing_exports.contains(&mangled) {
|
||||||
|
o.missing_exports.push(mangled);
|
||||||
|
o.missing_readable.push(readable);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} else if !e.error_code.starts_with("LNK") {
|
||||||
|
o.compile_errors.push(format!("{} {}:{} {}", e.error_code, e.file.rsplit(['/', '\\']).next().unwrap_or(""), e.line, e.message.lines().next().unwrap_or("")));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
o.result = if o.compile_errors.is_empty() && !o.missing_exports.is_empty() {
|
||||||
|
"link-missing-exports".into()
|
||||||
|
} else {
|
||||||
|
"compile-error".into()
|
||||||
|
};
|
||||||
|
o.compile_errors.truncate(10);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
o.seconds = started.elapsed().as_secs_f64();
|
||||||
|
println!(" -> {} ({:.0}s){}", o.result, o.seconds, if o.missing_exports.is_empty() { String::new() } else { format!(", {} missing exports", o.missing_exports.len()) });
|
||||||
|
std::fs::write(&out, serde_json::to_vec_pretty(&o).unwrap()).unwrap();
|
||||||
|
// source downloads of finished modules are not needed again
|
||||||
|
let _ = std::fs::remove_dir_all(sources.join("github").join(&item.owner).join(&item.name));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn summary(work: &Path) {
|
||||||
|
let mut all: Vec<Outcome> = std::fs::read_dir(work.join("results")).unwrap()
|
||||||
|
.flatten()
|
||||||
|
.filter_map(|e| serde_json::from_slice(&std::fs::read(e.path()).ok()?).ok())
|
||||||
|
.collect();
|
||||||
|
all.sort_by(|a, b| b.stars.cmp(&a.stars));
|
||||||
|
let mut by_result: BTreeMap<&str, usize> = BTreeMap::new();
|
||||||
|
for o in &all {
|
||||||
|
*by_result.entry(o.result.as_str()).or_default() += 1;
|
||||||
|
}
|
||||||
|
let mut symbols: BTreeMap<String, (String, Vec<String>)> = BTreeMap::new();
|
||||||
|
for o in all.iter().filter(|o| o.result == "link-missing-exports") {
|
||||||
|
for (m, r) in o.missing_exports.iter().zip(&o.missing_readable) {
|
||||||
|
symbols.entry(m.clone()).or_insert_with(|| (r.clone(), Vec::new())).1.push(o.slug.clone());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let mut lines = vec![format!("modules: {}", all.len())];
|
||||||
|
for (r, n) in &by_result {
|
||||||
|
lines.push(format!(" {r}: {n}"));
|
||||||
|
}
|
||||||
|
lines.push(format!("distinct missing exports (modules that only lack exports): {}", symbols.len()));
|
||||||
|
let mut sym: Vec<_> = symbols.iter().collect();
|
||||||
|
sym.sort_by(|a, b| b.1 .1.len().cmp(&a.1 .1.len()));
|
||||||
|
for (_, (readable, mods)) in sym.iter().take(40) {
|
||||||
|
lines.push(format!(" {:>3} {}", mods.len(), readable));
|
||||||
|
}
|
||||||
|
// why modules do not compile: a header they need is not there (a dependency: playerbots, a library), or
|
||||||
|
// the core's API differs from the one they were written for
|
||||||
|
let mut kinds: BTreeMap<String, usize> = BTreeMap::new();
|
||||||
|
for o in all.iter().filter(|o| o.result == "compile-error") {
|
||||||
|
let header = o.compile_errors.iter().find(|e| e.starts_with("C1083")).and_then(|e| {
|
||||||
|
let start = e.find(": ")? + 2;
|
||||||
|
Some(e[start..].split(':').next()?.trim().to_string())
|
||||||
|
});
|
||||||
|
let kind = match header {
|
||||||
|
Some(h) => format!("missing header {h}"),
|
||||||
|
None => format!("core API differs ({})", o.compile_errors.first().map(|e| e.split(' ').next().unwrap_or("")).unwrap_or("")),
|
||||||
|
};
|
||||||
|
*kinds.entry(kind).or_default() += 1;
|
||||||
|
}
|
||||||
|
lines.push(String::new());
|
||||||
|
lines.push("compile errors by cause:".into());
|
||||||
|
let mut k: Vec<_> = kinds.into_iter().collect();
|
||||||
|
k.sort_by(|a, b| b.1.cmp(&a.1));
|
||||||
|
for (kind, n) in k.iter().take(25) {
|
||||||
|
lines.push(format!(" {n:>3} {kind}"));
|
||||||
|
}
|
||||||
|
lines.push(String::new());
|
||||||
|
for o in &all {
|
||||||
|
lines.push(format!("{:<22} ★{:<5} {:<48} {}", o.result, o.stars, o.slug,
|
||||||
|
if o.result == "link-missing-exports" { format!("{} exports", o.missing_exports.len()) }
|
||||||
|
else { o.detail.clone().or_else(|| o.compile_errors.first().cloned()).unwrap_or_default().chars().take(110).collect() }));
|
||||||
|
}
|
||||||
|
let text = lines.join("\n");
|
||||||
|
println!("{text}");
|
||||||
|
std::fs::write(work.join("summary.txt"), &text).unwrap();
|
||||||
|
// the exports a core build would add, one decorated name per line
|
||||||
|
let def: Vec<&String> = symbols.keys().collect();
|
||||||
|
std::fs::write(work.join("missing-exports.txt"), def.iter().map(|s| s.as_str()).collect::<Vec<_>>().join("\n")).unwrap();
|
||||||
|
}
|
||||||
|
|
||||||
|
fn main() {
|
||||||
|
let a: Vec<String> = std::env::args().skip(1).collect();
|
||||||
|
match a.first().map(String::as_str) {
|
||||||
|
Some("run") => run(Path::new(&a[1]), Path::new(&a[2]), a[3].parse().unwrap()),
|
||||||
|
Some("summary") => summary(Path::new(&a[1])),
|
||||||
|
_ => eprintln!("usage: catalog_build_sweep run <realm> <work> <count> | summary <work>"),
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,23 @@
|
|||||||
|
//! How the module categories fall on a real catalogue: counts per category and a few modules of each.
|
||||||
|
//! usage: catalogue_categories <catalogue.json downloaded from azerothcore.org>
|
||||||
|
fn main() {
|
||||||
|
let path = std::env::args().nth(1).expect("usage: catalogue_categories <catalogue.json>");
|
||||||
|
let raw: coa_core::catalogue::OfficialCatalogueRaw =
|
||||||
|
serde_json::from_slice(&std::fs::read(path).unwrap()).unwrap();
|
||||||
|
let overlay = coa_core::catalogue::load_coa_overlay(None);
|
||||||
|
let items = coa_core::catalogue::normalize_catalogue(&raw, &overlay);
|
||||||
|
let mut by: std::collections::BTreeMap<String, Vec<(u32, String, String)>> = Default::default();
|
||||||
|
for i in &items {
|
||||||
|
let c = coa_core::catalogue::categorize(&i.full_name, &i.name, &i.description, &i.topics);
|
||||||
|
by.entry(c).or_default().push((i.stars, i.full_name.clone(), i.description.chars().take(70).collect()));
|
||||||
|
}
|
||||||
|
println!("modules: {}", items.len());
|
||||||
|
for c in coa_core::catalogue::categories() {
|
||||||
|
let mut list = by.remove(&c.code).unwrap_or_default();
|
||||||
|
list.sort_by(|a, b| b.0.cmp(&a.0));
|
||||||
|
println!("\n== {} ({}) {}", c.code, c.ru, list.len());
|
||||||
|
for (s, n, d) in list.iter().take(6) {
|
||||||
|
println!(" {s:>5} {n:<45} {d}");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,114 @@
|
|||||||
|
//! The Rust launcher on a DISPOSABLE repack, side by side with Scripts/manage.py:
|
||||||
|
//!
|
||||||
|
//! 1. install the stable server into a new folder on unused ports;
|
||||||
|
//! 2. coa-launcher start-all, then manage.py status-json must see every service;
|
||||||
|
//! 3. manage.py stop-all stops what coa-launcher started;
|
||||||
|
//! 4. manage.py start-all, coa-launcher status-json sees it, coa-launcher stop-all stops it;
|
||||||
|
//! 5. both stop-alls leave nothing of the repack running.
|
||||||
|
//!
|
||||||
|
//! usage: launcher_e2e <new folder ending in -fixture> <coa-launcher.exe>
|
||||||
|
use std::path::Path;
|
||||||
|
use std::process::Command;
|
||||||
|
|
||||||
|
use coa_core::install::{install_base, Params};
|
||||||
|
use coa_core::registry::Registry;
|
||||||
|
|
||||||
|
fn free_port() -> u16 {
|
||||||
|
std::net::TcpListener::bind("127.0.0.1:0").unwrap().local_addr().unwrap().port()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn run(exe: &Path, args: &[&str]) -> (bool, String) {
|
||||||
|
let out = Command::new(exe).args(args).output().unwrap();
|
||||||
|
let text = String::from_utf8_lossy(&out.stdout).into_owned() + &String::from_utf8_lossy(&out.stderr);
|
||||||
|
(out.status.success(), text)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn launcher(root: &Path, exe: &Path, action: &str) -> (bool, String) {
|
||||||
|
let r = root.to_string_lossy().into_owned();
|
||||||
|
let t = std::time::Instant::now();
|
||||||
|
let out = run(exe, &["--root", &r, action]);
|
||||||
|
println!("[coa-launcher {action}] ok={} in {:?}\n{}", out.0, t.elapsed(), indent(&out.1));
|
||||||
|
out
|
||||||
|
}
|
||||||
|
|
||||||
|
fn manage(root: &Path, action: &str) -> (bool, String) {
|
||||||
|
let python = root.join("Runtime/python/python.exe");
|
||||||
|
let script = root.join("Scripts/manage.py").to_string_lossy().into_owned();
|
||||||
|
let t = std::time::Instant::now();
|
||||||
|
let out = run(&python, &["-B", &script, action]);
|
||||||
|
println!("[manage.py {action}] ok={} in {:?}\n{}", out.0, t.elapsed(), indent(&out.1));
|
||||||
|
out
|
||||||
|
}
|
||||||
|
|
||||||
|
fn indent(s: &str) -> String {
|
||||||
|
s.lines().map(|l| format!(" {l}")).collect::<Vec<_>>().join("\n")
|
||||||
|
}
|
||||||
|
|
||||||
|
fn status(out: &str) -> serde_json::Value {
|
||||||
|
let line = out.lines().rev().find(|l| l.trim_start().starts_with('{')).expect("a JSON status line");
|
||||||
|
serde_json::from_str(line).unwrap()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn all(v: &serde_json::Value, running: bool) -> bool {
|
||||||
|
["mysql", "auth", "world", "relay"].iter().all(|k| v[*k] == running)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn main() {
|
||||||
|
let a: Vec<String> = std::env::args().skip(1).collect();
|
||||||
|
let root = Path::new(&a[0]);
|
||||||
|
let exe = Path::new(&a[1]);
|
||||||
|
assert!(a[0].ends_with("-fixture"), "a folder ending in -fixture is required");
|
||||||
|
if root.join("Core/worldserver.exe").is_file() {
|
||||||
|
println!("reusing the installed fixture");
|
||||||
|
} else {
|
||||||
|
install(root);
|
||||||
|
}
|
||||||
|
test(root, exe);
|
||||||
|
}
|
||||||
|
|
||||||
|
fn install(root: &Path) {
|
||||||
|
assert!(!root.exists(), "a new folder is required");
|
||||||
|
let reg_dir = std::env::temp_dir().join("coa-launcher-e2e-registry");
|
||||||
|
let _ = std::fs::remove_dir_all(®_dir);
|
||||||
|
let reg = Registry::at(reg_dir.join("installs.json"));
|
||||||
|
// what the Manager installs: the stable release's installation image
|
||||||
|
let image = coa_core::install::Source::Installation(Box::new(coa_core::channels::resolve("stable").expect("stable channel")));
|
||||||
|
let installed = install_base(
|
||||||
|
&Params { source: image, dest: root.into(), trusted_key: coa_core::signing::EMBEDDED_PUBLIC_KEY, registry: ®, cancel: Default::default() },
|
||||||
|
&|s| eprintln!(" {:>3}% {}", s.percent, s.step),
|
||||||
|
)
|
||||||
|
.expect("install");
|
||||||
|
println!("installed {}", installed.version);
|
||||||
|
let repack = root.join("Settings/repack.json");
|
||||||
|
let mut cfg: serde_json::Value = serde_json::from_slice(&std::fs::read(&repack).unwrap()).unwrap();
|
||||||
|
for k in ["mysqlPort", "authPort", "worldPort", "raPort"] {
|
||||||
|
cfg[k] = free_port().into();
|
||||||
|
}
|
||||||
|
std::fs::write(&repack, serde_json::to_vec_pretty(&cfg).unwrap()).unwrap();
|
||||||
|
}
|
||||||
|
|
||||||
|
fn test(root: &Path, exe: &Path) {
|
||||||
|
// 2. Rust starts, Python sees it
|
||||||
|
assert!(launcher(root, exe, "start-all").0, "coa-launcher start-all");
|
||||||
|
let seen = status(&manage(root, "status-json").1);
|
||||||
|
assert!(all(&seen, true), "manage.py must see the services coa-launcher started: {seen}");
|
||||||
|
// 3. Python stops what Rust started
|
||||||
|
assert!(manage(root, "stop-all").0, "manage.py stop-all");
|
||||||
|
assert!(all(&status(&launcher(root, exe, "status-json").1), false));
|
||||||
|
|
||||||
|
// 4. Python starts, Rust sees and stops it
|
||||||
|
assert!(manage(root, "start-all").0, "manage.py start-all");
|
||||||
|
let seen = status(&launcher(root, exe, "status-json").1);
|
||||||
|
assert!(all(&seen, true), "coa-launcher must see the services manage.py started: {seen}");
|
||||||
|
assert!(launcher(root, exe, "stop-all").0, "coa-launcher stop-all");
|
||||||
|
assert!(all(&status(&manage(root, "status-json").1), false));
|
||||||
|
|
||||||
|
// 5. Rust alone, a second time (start on a server it stopped)
|
||||||
|
assert!(launcher(root, exe, "start-all").0);
|
||||||
|
assert!(launcher(root, exe, "stop-all").0);
|
||||||
|
let left = coa_core::process::find_by_exe(&root.join("mysql/bin/mysqld.exe")).len()
|
||||||
|
+ coa_core::process::find_by_exe(&root.join("Core/worldserver.exe")).len()
|
||||||
|
+ coa_core::process::find_by_exe(&root.join("Core/authserver.exe")).len();
|
||||||
|
assert_eq!(left, 0, "nothing of the repack may be left running");
|
||||||
|
println!("LAUNCHER E2E PASS");
|
||||||
|
}
|
||||||
@@ -0,0 +1,149 @@
|
|||||||
|
//! The Manager's start/stop (`driver`) on the Rust launcher, on a DISPOSABLE repack:
|
||||||
|
//!
|
||||||
|
//! 1. driver start-all: every service runs, the console answers, manage.py is not touched and sees the services;
|
||||||
|
//! 2. driver stop-all stops everything;
|
||||||
|
//! 3. manage.py start-all, then driver stop-all stops what Python started;
|
||||||
|
//! 4. a taken world port fails with the typed "port in use" code (no stderr parsing), then stop-all;
|
||||||
|
//! 5. driver start-all, then the forced stop;
|
||||||
|
//! 6. with a realm profile: the realm row gets the profile's name, manage.py is still not edited;
|
||||||
|
//! 7. nothing of the repack is left running.
|
||||||
|
//!
|
||||||
|
//! usage: manager_launcher_e2e <existing folder ending in -fixture>
|
||||||
|
use std::path::Path;
|
||||||
|
use std::process::Command;
|
||||||
|
use std::time::Instant;
|
||||||
|
|
||||||
|
use coa_core::driver::{self, Verb};
|
||||||
|
use coa_core::error::ErrorCode;
|
||||||
|
use coa_core::launcher::{services, settings::Settings, state};
|
||||||
|
|
||||||
|
fn indent(s: &str) -> String {
|
||||||
|
s.lines().map(|l| format!(" {l}")).collect::<Vec<_>>().join("\n")
|
||||||
|
}
|
||||||
|
|
||||||
|
fn drive(root: &Path, verb: Verb) -> driver::DriverOutcome {
|
||||||
|
let t = Instant::now();
|
||||||
|
let out = driver::run(root, verb).expect("driver");
|
||||||
|
println!("[driver {verb:?}] ok={} code={:?} in {:?}\n{}", out.ok, out.code, t.elapsed(), indent(&out.output));
|
||||||
|
out
|
||||||
|
}
|
||||||
|
|
||||||
|
fn manage(root: &Path, action: &str) -> (bool, String) {
|
||||||
|
let python = root.join("Runtime/python/python.exe");
|
||||||
|
let script = root.join("Scripts/manage.py").to_string_lossy().into_owned();
|
||||||
|
let t = Instant::now();
|
||||||
|
let out = Command::new(python).args(["-B", &script, action]).output().unwrap();
|
||||||
|
let text = String::from_utf8_lossy(&out.stdout).into_owned() + &String::from_utf8_lossy(&out.stderr);
|
||||||
|
println!("[manage.py {action}] ok={} in {:?}\n{}", out.status.success(), t.elapsed(), indent(&text));
|
||||||
|
(out.status.success(), text)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn python_status(root: &Path) -> serde_json::Value {
|
||||||
|
let (ok, out) = manage(root, "status-json");
|
||||||
|
assert!(ok);
|
||||||
|
let line = out.lines().rev().find(|l| l.trim_start().starts_with('{')).expect("a JSON status line");
|
||||||
|
serde_json::from_str(line).unwrap()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn all(v: &serde_json::Value, running: bool) -> bool {
|
||||||
|
["mysql", "auth", "world", "relay"].iter().all(|k| v[*k] == running)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn nothing_running(root: &Path) -> bool {
|
||||||
|
["mysql", "auth", "world", "supervisor", "relay"].iter().all(|n| state::running(root, n).is_none())
|
||||||
|
&& ["mysql/bin/mysqld.exe", "Core/authserver.exe", "Core/worldserver.exe"]
|
||||||
|
.iter()
|
||||||
|
.all(|exe| coa_core::process::find_by_exe(&root.join(exe)).is_empty())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn console(root: &Path) -> String {
|
||||||
|
let cfg = Settings::load(root, 0).unwrap();
|
||||||
|
let mut ra = coa_core::ra::Ra::connect_to(cfg.ra_port, &cfg.ra_username, &cfg.ra_password).unwrap();
|
||||||
|
ra.run("server info").unwrap()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn realm_name(root: &Path) -> String {
|
||||||
|
services::mysql(root, Some("SELECT name FROM acore_auth.realmlist WHERE id=1;"), None).unwrap()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn main() {
|
||||||
|
let a: Vec<String> = std::env::args().skip(1).collect();
|
||||||
|
let root = Path::new(&a[0]);
|
||||||
|
assert!(a[0].ends_with("-fixture"), "a folder ending in -fixture is required");
|
||||||
|
assert!(nothing_running(root), "the fixture must be stopped before the test");
|
||||||
|
let manage_py = root.join("Scripts/manage.py");
|
||||||
|
let original = std::fs::read(&manage_py).unwrap();
|
||||||
|
let profile = root.join("Settings/realm-profile.json");
|
||||||
|
assert!(!profile.exists(), "the fixture starts without a realm profile");
|
||||||
|
|
||||||
|
// 1
|
||||||
|
let started = drive(root, Verb::StartAll);
|
||||||
|
assert!(started.ok, "start-all");
|
||||||
|
assert!(all(&python_status(root), true), "manage.py sees what the Manager started");
|
||||||
|
let info = console(root);
|
||||||
|
println!("[console] {}", info.lines().next().unwrap_or(""));
|
||||||
|
assert_eq!(std::fs::read(&manage_py).unwrap(), original, "manage.py is not rewritten");
|
||||||
|
assert_eq!(realm_name(root), "AzerothCore", "no profile: the launcher's own realm name");
|
||||||
|
|
||||||
|
let shipped = root.join("Scripts/coa-launcher.exe");
|
||||||
|
let supervisor = state::running(root, "supervisor").expect("a supervisor");
|
||||||
|
println!("[supervisor] {}", supervisor.exe);
|
||||||
|
let expected = if shipped.is_file() { "coa-launcher.exe" } else { "python.exe" };
|
||||||
|
assert!(supervisor.exe.to_lowercase().ends_with(expected), "the world is supervised by {expected}");
|
||||||
|
let relay = state::running(root, "relay").expect("a bug-report relay");
|
||||||
|
println!("[relay] {}", relay.exe);
|
||||||
|
assert!(relay.exe.to_lowercase().ends_with(expected), "the relay is run by {expected}");
|
||||||
|
assert!(state::running(root, "relay-ready").is_some_and(|r| r.pid == relay.pid), "the relay reported ready");
|
||||||
|
|
||||||
|
// 2
|
||||||
|
assert!(drive(root, Verb::StopAll).ok, "stop-all");
|
||||||
|
assert!(nothing_running(root), "1-2 left something running");
|
||||||
|
|
||||||
|
// 2b: the repack's Python launcher stops a world the Manager started
|
||||||
|
assert!(drive(root, Verb::StartAll).ok);
|
||||||
|
assert!(manage(root, "stop-all").0, "manage.py stops what the Manager started");
|
||||||
|
assert!(nothing_running(root), "2b left something running");
|
||||||
|
|
||||||
|
// 3
|
||||||
|
assert!(manage(root, "start-all").0);
|
||||||
|
assert!(drive(root, Verb::StopAll).ok, "driver stops what manage.py started");
|
||||||
|
assert!(nothing_running(root), "3 left something running");
|
||||||
|
|
||||||
|
// 4
|
||||||
|
let cfg = Settings::load(root, 0).unwrap();
|
||||||
|
let blocker = std::net::TcpListener::bind(("127.0.0.1", cfg.world_port)).unwrap();
|
||||||
|
let refused = drive(root, Verb::StartAll);
|
||||||
|
assert!(!refused.ok);
|
||||||
|
assert_eq!(refused.code, Some(ErrorCode::PortInUse), "typed port error");
|
||||||
|
assert!(refused.output.contains(&format!("Port {}", cfg.world_port)));
|
||||||
|
drop(blocker);
|
||||||
|
assert!(drive(root, Verb::StopAll).ok);
|
||||||
|
assert!(nothing_running(root), "4 left something running");
|
||||||
|
|
||||||
|
// 5
|
||||||
|
assert!(drive(root, Verb::StartAll).ok);
|
||||||
|
let t = Instant::now();
|
||||||
|
let forced = driver::force_stop(root).expect("force stop");
|
||||||
|
println!("[driver force_stop] ok={} in {:?}\n{}", forced.ok, t.elapsed(), indent(&forced.output));
|
||||||
|
assert!(forced.ok && forced.output.contains("Force-stopped"));
|
||||||
|
assert!(nothing_running(root), "5 left something running");
|
||||||
|
|
||||||
|
// 6
|
||||||
|
std::fs::write(&profile, br#"{"active":"coa","wildcard_created":false}"#).unwrap();
|
||||||
|
let result = std::panic::catch_unwind(|| {
|
||||||
|
assert!(drive(root, Verb::StartAll).ok, "start-all with a realm profile");
|
||||||
|
assert_eq!(realm_name(root), "Conquest of Azeroth");
|
||||||
|
assert_eq!(std::fs::read(&manage_py).unwrap(), original, "manage.py is not edited for a realm profile either");
|
||||||
|
assert!(drive(root, Verb::StopAll).ok);
|
||||||
|
});
|
||||||
|
std::fs::remove_file(&profile).unwrap();
|
||||||
|
std::fs::write(&manage_py, &original).unwrap();
|
||||||
|
if result.is_err() {
|
||||||
|
let _ = driver::run(root, Verb::StopAll);
|
||||||
|
panic!("step 6 failed");
|
||||||
|
}
|
||||||
|
|
||||||
|
// 7
|
||||||
|
assert!(nothing_running(root), "something of the repack is still running");
|
||||||
|
println!("PASS: the Manager starts and stops through the Rust launcher, interoperates with manage.py, typed errors");
|
||||||
|
}
|
||||||
@@ -0,0 +1,197 @@
|
|||||||
|
//! 0.9.10 install paths of the Modules Preview, end to end on DISPOSABLE servers under <work>:
|
||||||
|
//!
|
||||||
|
//! 1. fresh: a new server goes on to the preview core with the bare core (no module is compiled).
|
||||||
|
//! 2. copy: a classic server (stopped) gets a modular copy next to it: accounts, characters, the world and
|
||||||
|
//! module settings arrive, the old server's files are byte-for-byte unchanged, the copy takes the
|
||||||
|
//! preview core with the modules the old server had switched on.
|
||||||
|
//! 3. copy-running: the same copy step from a classic server whose database is running.
|
||||||
|
//!
|
||||||
|
//! usage: preview_bare_and_copy_e2e <empty work folder> [fresh|copy|all]
|
||||||
|
use std::collections::BTreeMap;
|
||||||
|
use std::path::{Path, PathBuf};
|
||||||
|
|
||||||
|
use coa_core::install::{install_base, Params, Source};
|
||||||
|
use coa_core::registry::Registry;
|
||||||
|
use coa_core::update::{self, RepackEnv};
|
||||||
|
|
||||||
|
const KEY: &str = coa_core::signing::EMBEDDED_PUBLIC_KEY;
|
||||||
|
type R<T> = Result<T, Box<dyn std::error::Error>>;
|
||||||
|
|
||||||
|
fn free_port() -> u16 {
|
||||||
|
std::net::TcpListener::bind("127.0.0.1:0").unwrap().local_addr().unwrap().port()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn sql(root: &Path, q: &str) -> String {
|
||||||
|
coa_core::backup::with_database(root, |db| db.query(q)).unwrap_or_else(|e| panic!("{q}: {e}"))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn install(root: &Path, reg: &Registry) -> R<()> {
|
||||||
|
let image = coa_core::channels::stable_source()?;
|
||||||
|
let t = std::time::Instant::now();
|
||||||
|
let done = install_base(
|
||||||
|
&Params { source: Source::Installation(Box::new(image)), dest: root.into(), trusted_key: KEY, registry: reg, cancel: Default::default() },
|
||||||
|
&|s| eprintln!(" {:>3}% {}", s.percent, s.step),
|
||||||
|
)?;
|
||||||
|
println!("[{}] installed {} in {:?}", root.display(), done.version, t.elapsed());
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn set_free_ports(root: &Path) -> R<()> {
|
||||||
|
let repack = root.join("Settings/repack.json");
|
||||||
|
let mut cfg: serde_json::Value = serde_json::from_slice(&std::fs::read(&repack)?)?;
|
||||||
|
for k in ["mysqlPort", "authPort", "worldPort", "raPort"] {
|
||||||
|
cfg[k] = free_port().into();
|
||||||
|
}
|
||||||
|
std::fs::write(&repack, serde_json::to_vec_pretty(&cfg)?)?;
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The same steps as the Manager's install_preview_core.
|
||||||
|
fn preview_core(root: &Path) -> R<update::Outcome> {
|
||||||
|
let meta_dir = coa_core::registry::metadata_dir_for(root)?;
|
||||||
|
let (_, meta) = coa_core::registry::MetaDir::open(&meta_dir)?;
|
||||||
|
let source = coa_core::update_route::select(&meta, coa_core::channels::preview_update_source()?, KEY)?.source;
|
||||||
|
let env = RepackEnv { root, meta_dir: &meta_dir };
|
||||||
|
let t = std::time::Instant::now();
|
||||||
|
let out = coa_core::install::with_scratch_ports(root, || update::apply(
|
||||||
|
&update::Params { root, meta_dir: &meta_dir, source, trusted_key: KEY, cancel: Default::default(), resolutions: Default::default(), env: &env, fail_after_ops: None },
|
||||||
|
&|phase, percent| println!(" {percent}% {phase}"),
|
||||||
|
));
|
||||||
|
let _ = coa_core::driver::run(root, coa_core::driver::Verb::StopAll);
|
||||||
|
let out = out?;
|
||||||
|
println!("[{}] preview core: {:?} in {:?}; modules {:?}", root.display(), out.txn.state, t.elapsed(), out.modules);
|
||||||
|
assert_eq!(out.txn.state, update::State::Committed);
|
||||||
|
assert!(coa_core::provenance::realm_host_fingerprint(root).is_some(), "the plugin host is installed");
|
||||||
|
Ok(out)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// sha256 of every file under the old server, except the launcher's own run state.
|
||||||
|
fn tree(root: &Path) -> BTreeMap<String, String> {
|
||||||
|
fn walk(base: &Path, dir: &Path, out: &mut BTreeMap<String, String>) {
|
||||||
|
for e in std::fs::read_dir(dir).into_iter().flatten().flatten() {
|
||||||
|
let p = e.path();
|
||||||
|
if p.is_dir() {
|
||||||
|
walk(base, &p, out);
|
||||||
|
} else {
|
||||||
|
let rel = p.strip_prefix(base).unwrap().to_string_lossy().replace('\\', "/");
|
||||||
|
out.insert(rel, coa_core::fsx::sha256_file(&p).unwrap_or_else(|e| format!("unreadable: {e}")));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let mut out = BTreeMap::new();
|
||||||
|
walk(root, root, &mut out);
|
||||||
|
out
|
||||||
|
}
|
||||||
|
|
||||||
|
fn fresh(work: &Path, reg: &Registry) -> R<()> {
|
||||||
|
let root = work.join("fresh-fixture");
|
||||||
|
install(&root, reg)?; // shipped ports, as in the Manager: another server may be running on them
|
||||||
|
coa_core::rebuild::decline_recommended(&root)?;
|
||||||
|
let out = preview_core(&root)?;
|
||||||
|
assert!(out.modules.is_empty(), "a new server compiles nothing: {:?}", out.modules);
|
||||||
|
let registry = coa_core::plugins::load_registry(&root)?;
|
||||||
|
assert!(registry.plugins.values().all(|e| !e.installed), "no plugin installed: {:?}", registry.plugins.keys());
|
||||||
|
let boot: serde_json::Value = serde_json::from_slice(&std::fs::read(root.join("Core/plugins/plugin-boot-report.json"))?)?;
|
||||||
|
println!("boot report: {boot}");
|
||||||
|
assert_eq!(boot["anyFaulted"], serde_json::json!(false));
|
||||||
|
println!("FRESH PASS");
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn copy(work: &Path, reg: &Registry) -> R<()> {
|
||||||
|
// A classic server with data of its own.
|
||||||
|
let old = work.join("classic-fixture");
|
||||||
|
install(&old, reg)?;
|
||||||
|
set_free_ports(&old)?; // the test runs this "old" server; it must not meet a real one on the shipped ports
|
||||||
|
sql(&old, "INSERT INTO acore_auth.account (username, salt, verifier, email, reg_mail) \
|
||||||
|
VALUES ('E2ECOPY', UNHEX(REPEAT('11',32)), UNHEX(REPEAT('22',32)), '', '')");
|
||||||
|
let account = sql(&old, "SELECT id FROM acore_auth.account WHERE username='E2ECOPY'").trim().to_string();
|
||||||
|
sql(&old, &format!("SET SESSION sql_mode=''; INSERT INTO acore_characters.characters (guid, account, name, race, class, gender, level, money) \
|
||||||
|
VALUES (900001, {account}, 'Copytest', 1, 1, 0, 42, 123456)"));
|
||||||
|
let conf = old.join("Core/configs/modules/mod-coa-content-scaling.conf");
|
||||||
|
let conf_text = std::fs::read_to_string(&conf).unwrap_or_default() + "\n# e2e owner edit\n";
|
||||||
|
std::fs::write(&conf, &conf_text)?;
|
||||||
|
let fingerprint = |root: &Path| sql(root, "SELECT CONCAT((SELECT COUNT(*) FROM acore_auth.account),'|',(SELECT COUNT(*) FROM acore_characters.characters),'|',\
|
||||||
|
(SELECT CONCAT(name,':',level,':',money) FROM acore_characters.characters WHERE guid=900001))").trim().to_string();
|
||||||
|
let expected = fingerprint(&old);
|
||||||
|
let counts = sql(&old, "SELECT CONCAT((SELECT COUNT(*) FROM acore_auth.account),'|',(SELECT COUNT(*) FROM acore_characters.characters))").trim().to_string();
|
||||||
|
// A world setting changed on the Server Configuration page lives in the old server's template.
|
||||||
|
let old_meta = coa_core::registry::metadata_dir_for(&old)?;
|
||||||
|
let rate = BTreeMap::from([("Rate.XP.Kill".to_string(), "3".to_string())]);
|
||||||
|
assert_eq!(coa_core::allsettings::save(&old, &old_meta, &rate)?, ["Rate.XP.Kill"]);
|
||||||
|
let _ = coa_core::driver::run(&old, coa_core::driver::Verb::StopAll);
|
||||||
|
println!("old server data: {expected}");
|
||||||
|
assert!(coa_core::modular_copy::is_classic(&old));
|
||||||
|
let before_preview = tree(&old);
|
||||||
|
let p = coa_core::modular_copy::preview(&old)?;
|
||||||
|
println!("preview (stopped): {p:?}");
|
||||||
|
assert!(p.classic && !p.modular && p.database == "stopped" && p.accounts.is_none());
|
||||||
|
assert!(p.database_bytes > 0 && p.config_files.iter().any(|f| f.ends_with("mod-coa-content-scaling.conf")));
|
||||||
|
assert_eq!(tree(&old), before_preview, "the preview changed the old server's files");
|
||||||
|
|
||||||
|
// 2. copy of the stopped server, then the preview core on the copy.
|
||||||
|
let before = tree(&old);
|
||||||
|
let new = work.join("copy-fixture");
|
||||||
|
install(&new, reg)?;
|
||||||
|
let report = coa_core::modular_copy::copy_data(&old, &new, &|w| println!(" copy: {w}"))?;
|
||||||
|
println!("copy report: {report:?}");
|
||||||
|
assert_eq!(report.read_from, "copy of the stopped database");
|
||||||
|
assert_eq!(tree(&old), before, "the old server's files changed");
|
||||||
|
let observed = coa_core::process::observe(&new, &coa_core::layout::read_ports(&new));
|
||||||
|
assert_eq!(observed.mysql.state, coa_core::process::ServiceState::Stopped, "a database of the copy is still running: {:?}", observed.mysql);
|
||||||
|
assert!(!coa_core::registry::metadata_dir_for(&new)?.join("import").exists(), "the private copy of the old data is removed");
|
||||||
|
assert_eq!(std::fs::read_to_string(new.join("Core/configs/modules/mod-coa-content-scaling.conf"))?, conf_text);
|
||||||
|
assert_eq!(report.world_settings, ["Rate.XP.Kill"], "skipped: {:?}", report.world_settings_skipped);
|
||||||
|
let world_value = |root: &Path| coa_core::allsettings::list(root).unwrap().into_iter().find(|i| i.key == "Rate.XP.Kill").map(|i| i.value);
|
||||||
|
assert_eq!(world_value(&new).as_deref(), Some("3"));
|
||||||
|
let out = preview_core(&new)?;
|
||||||
|
println!("modules on the copy: {:?}", out.modules);
|
||||||
|
let got = fingerprint(&new);
|
||||||
|
let _ = coa_core::driver::run(&new, coa_core::driver::Verb::StopAll);
|
||||||
|
assert_eq!(got, expected, "data of the copy after the preview core");
|
||||||
|
assert_eq!(tree(&old), before, "the old server's files changed");
|
||||||
|
println!("COPY (stopped) PASS");
|
||||||
|
|
||||||
|
// 3. copy while the old database runs: read from it, change nothing.
|
||||||
|
let started = coa_core::driver::run(&old, coa_core::driver::Verb::StartMysql)?;
|
||||||
|
assert!(started.ok, "{}", started.output);
|
||||||
|
let data_before: BTreeMap<String, String> = tree(&old).into_iter().filter(|(k, _)| !k.starts_with("mysql/") && !k.starts_with(".state/") && !k.starts_with("Core/configs/")).collect();
|
||||||
|
let rows_before = fingerprint(&old);
|
||||||
|
let p = coa_core::modular_copy::preview(&old)?;
|
||||||
|
println!("preview (running): accounts {:?} characters {:?} schemas {:?}", p.accounts, p.characters, p.schemas);
|
||||||
|
assert_eq!(p.database, "running");
|
||||||
|
assert_eq!(format!("{}|{}", p.accounts.unwrap(), p.characters.unwrap()), counts);
|
||||||
|
assert!(p.schemas.iter().any(|s| s == "acore_characters"));
|
||||||
|
let new2 = work.join("copy-running-fixture");
|
||||||
|
install(&new2, reg)?;
|
||||||
|
let report = coa_core::modular_copy::copy_data(&old, &new2, &|w| println!(" copy: {w}"));
|
||||||
|
let rows_after = fingerprint(&old);
|
||||||
|
let _ = coa_core::driver::run(&old, coa_core::driver::Verb::StopAll);
|
||||||
|
let report = report?;
|
||||||
|
assert_eq!(report.read_from, "running database");
|
||||||
|
assert_eq!(rows_after, rows_before);
|
||||||
|
let data_after: BTreeMap<String, String> = tree(&old).into_iter().filter(|(k, _)| !k.starts_with("mysql/") && !k.starts_with(".state/") && !k.starts_with("Core/configs/")).collect();
|
||||||
|
assert_eq!(data_after, data_before, "files outside the database changed");
|
||||||
|
assert_eq!(fingerprint(&new2), expected);
|
||||||
|
assert_eq!(world_value(&new2).as_deref(), Some("3"));
|
||||||
|
let _ = coa_core::driver::run(&new2, coa_core::driver::Verb::StopAll);
|
||||||
|
println!("COPY (running) PASS");
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn main() -> R<()> {
|
||||||
|
let a: Vec<String> = std::env::args().skip(1).collect();
|
||||||
|
let work = PathBuf::from(a.first().expect("usage: preview_bare_and_copy_e2e <empty work folder> [fresh|copy|all]"));
|
||||||
|
let mode = a.get(1).map(String::as_str).unwrap_or("all");
|
||||||
|
assert!(!work.exists() || std::fs::read_dir(&work)?.next().is_none(), "work folder must be new or empty");
|
||||||
|
std::fs::create_dir_all(&work)?;
|
||||||
|
let reg = Registry::at(work.join("installs.json"));
|
||||||
|
if mode == "fresh" || mode == "all" {
|
||||||
|
fresh(&work, ®)?;
|
||||||
|
}
|
||||||
|
if mode == "copy" || mode == "all" {
|
||||||
|
copy(&work, ®)?;
|
||||||
|
}
|
||||||
|
println!("ALL PASS ({mode})");
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
@@ -0,0 +1,170 @@
|
|||||||
|
//! The Rust bug-report relay against the repack's `BugReport/relay.py`, offline (a scripted service, no network):
|
||||||
|
//!
|
||||||
|
//! 1. the same reports and the same service answers give the same `.status` files and journal rows;
|
||||||
|
//! 2. each relay continues the other's journal: what one delivered is never sent again by the other, and a post the
|
||||||
|
//! other left in progress is uncertain.
|
||||||
|
//!
|
||||||
|
//! usage: relay_equivalence <repack folder with Runtime/python and BugReport/relay.py>
|
||||||
|
use std::path::{Path, PathBuf};
|
||||||
|
use std::process::Command;
|
||||||
|
use std::sync::{Arc, Mutex};
|
||||||
|
|
||||||
|
use coa_core::launcher::relay::{Failure, Relay, Service};
|
||||||
|
|
||||||
|
const REPORTS: [(&str, &str); 5] = [
|
||||||
|
("1-00000000000000a1", "COABUG1\r\nQuest broken\r\nThe NPC is gone.\r\n"),
|
||||||
|
("9-00000000000000b2", "COABUG1\nRate limited\nBody text\n"),
|
||||||
|
("3-00000000000000c3", "COABUG1\nRejected\nBody\n"),
|
||||||
|
("4-00000000000000d4", "COABUG1\nxy\nTitle too short\n"),
|
||||||
|
("5-00000000000000e5", "COABUG1\nUnknown outcome\nBody\n"),
|
||||||
|
];
|
||||||
|
|
||||||
|
/// The answers per title, in the vocabulary of both relays.
|
||||||
|
fn answer(title: &str) -> std::result::Result<u64, Failure> {
|
||||||
|
match title {
|
||||||
|
"Quest broken" => Ok(101),
|
||||||
|
"Rate limited" => Err(Failure::Limited(60)),
|
||||||
|
"Rejected" => Err(Failure::Invalid),
|
||||||
|
_ => Err(Failure::Uncertain),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const PYTHON: &str = r#"
|
||||||
|
import importlib.util, sys, json
|
||||||
|
from pathlib import Path
|
||||||
|
spec = importlib.util.spec_from_file_location("relay", sys.argv[1]); relay = importlib.util.module_from_spec(spec); spec.loader.exec_module(relay)
|
||||||
|
spool = Path(sys.argv[2]); calls = []
|
||||||
|
class Fake:
|
||||||
|
def create(self, title, body):
|
||||||
|
calls.append(title)
|
||||||
|
if title == "Quest broken": return 101
|
||||||
|
if title == "Rate limited": raise relay.DeliveryError("limited", 60)
|
||||||
|
if title == "Rejected": raise relay.DeliveryError("invalid")
|
||||||
|
raise relay.DeliveryError("uncertain")
|
||||||
|
t = [float(sys.argv[3])]
|
||||||
|
def clock():
|
||||||
|
t[0] += 3
|
||||||
|
return t[0]
|
||||||
|
r = relay.Relay(spool, Fake(), clock=clock)
|
||||||
|
for path in sorted(spool.glob("*.report")):
|
||||||
|
r.process(path)
|
||||||
|
r.close()
|
||||||
|
print(json.dumps(calls))
|
||||||
|
"#;
|
||||||
|
|
||||||
|
struct Scripted(Arc<Mutex<Vec<String>>>);
|
||||||
|
impl Service for Scripted {
|
||||||
|
fn create(&self, title: &str, _: &str) -> std::result::Result<u64, Failure> {
|
||||||
|
self.0.lock().unwrap().push(title.into());
|
||||||
|
answer(title)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn spool(dir: &Path) -> PathBuf {
|
||||||
|
std::fs::create_dir_all(dir).unwrap();
|
||||||
|
for (key, text) in REPORTS {
|
||||||
|
std::fs::write(dir.join(format!("{key}.report")), text).unwrap();
|
||||||
|
}
|
||||||
|
dir.into()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn python(repack: &Path, spool: &Path, start: f64) -> Vec<String> {
|
||||||
|
let out = Command::new(repack.join("Runtime/python/python.exe"))
|
||||||
|
.args(["-I", "-B", "-c", PYTHON])
|
||||||
|
.arg(repack.join("BugReport/relay.py"))
|
||||||
|
.arg(spool)
|
||||||
|
.arg(start.to_string())
|
||||||
|
.output()
|
||||||
|
.unwrap();
|
||||||
|
assert!(out.status.success(), "{}", String::from_utf8_lossy(&out.stderr));
|
||||||
|
serde_json::from_slice(&out.stdout).unwrap()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The clock of both relays: `start`, then 3 seconds later at every reading.
|
||||||
|
fn rust(spool: &Path, start: f64) -> Vec<String> {
|
||||||
|
let calls = Arc::new(Mutex::new(Vec::new()));
|
||||||
|
let t = Mutex::new(start);
|
||||||
|
let clock = move || {
|
||||||
|
let mut v = t.lock().unwrap();
|
||||||
|
*v += 3.0;
|
||||||
|
*v
|
||||||
|
};
|
||||||
|
let relay = Relay::with_clock(spool, Scripted(calls.clone()), Box::new(clock)).unwrap();
|
||||||
|
relay.pass().unwrap();
|
||||||
|
drop(relay);
|
||||||
|
let c = calls.lock().unwrap().clone();
|
||||||
|
c
|
||||||
|
}
|
||||||
|
|
||||||
|
/// `.status` files and journal rows (without the post time).
|
||||||
|
fn snapshot(spool: &Path) -> (Vec<(String, String)>, Vec<String>) {
|
||||||
|
let mut statuses: Vec<(String, String)> = std::fs::read_dir(spool)
|
||||||
|
.unwrap()
|
||||||
|
.flatten()
|
||||||
|
.filter(|e| e.path().extension().is_some_and(|x| x == "status"))
|
||||||
|
.map(|e| (e.file_name().to_string_lossy().into_owned(), std::fs::read_to_string(e.path()).unwrap()))
|
||||||
|
.collect();
|
||||||
|
statuses.sort();
|
||||||
|
let db = rusqlite::Connection::open(spool.join("relay.sqlite3")).unwrap();
|
||||||
|
let mut q = db.prepare("SELECT key, digest, marker, state, number, next_try FROM deliveries ORDER BY key").unwrap();
|
||||||
|
let rows = q
|
||||||
|
.query_map([], |r| {
|
||||||
|
Ok(format!(
|
||||||
|
"{}|{}|{}|{}|{:?}|{}",
|
||||||
|
r.get::<_, String>(0)?,
|
||||||
|
r.get::<_, String>(1)?,
|
||||||
|
r.get::<_, String>(2)?,
|
||||||
|
r.get::<_, String>(3)?,
|
||||||
|
r.get::<_, Option<i64>>(4)?,
|
||||||
|
r.get::<_, f64>(5)?
|
||||||
|
))
|
||||||
|
})
|
||||||
|
.unwrap()
|
||||||
|
.map(Result::unwrap)
|
||||||
|
.collect();
|
||||||
|
(statuses, rows)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn main() {
|
||||||
|
let repack = PathBuf::from(std::env::args().nth(1).expect("repack folder"));
|
||||||
|
let work = tempfile::tempdir().unwrap();
|
||||||
|
|
||||||
|
// 1
|
||||||
|
let (a, b) = (spool(&work.path().join("python")), spool(&work.path().join("rust")));
|
||||||
|
let py_calls = python(&repack, &a, 1000.0);
|
||||||
|
let rs_calls = rust(&b, 1000.0);
|
||||||
|
println!("python posted {py_calls:?}\nrust posted {rs_calls:?}");
|
||||||
|
assert_eq!(py_calls, rs_calls, "the same reports are posted");
|
||||||
|
let (pa, pb) = (snapshot(&a), snapshot(&b));
|
||||||
|
for s in &pa.0 {
|
||||||
|
println!(" {} = {}", s.0, s.1.trim());
|
||||||
|
}
|
||||||
|
assert_eq!(pa, pb, "the same statuses and journal");
|
||||||
|
|
||||||
|
|
||||||
|
// 2: each continues the other's journal. Before the retry times nothing is sent again; after them only the
|
||||||
|
// rate-limited report is (created, rejected and uncertain ones never are).
|
||||||
|
assert!(python(&repack, &b, 1000.0).is_empty(), "Python does not resend what Rust handled");
|
||||||
|
assert!(rust(&a, 1000.0).is_empty(), "Rust does not resend what Python handled");
|
||||||
|
// Later passes: the queued reports go out, a refused or uncertain one never again.
|
||||||
|
for start in [5000.0, 6000.0, 7000.0] {
|
||||||
|
let (p, r) = (python(&repack, &b, start), rust(&a, start));
|
||||||
|
println!("at {start}: python on rust's journal posted {p:?}, rust on python's posted {r:?}");
|
||||||
|
assert_eq!(p, r, "the same retries");
|
||||||
|
assert!(!p.iter().any(|t| t == "Quest broken" || t == "Unknown outcome"), "created and uncertain are final");
|
||||||
|
}
|
||||||
|
assert_eq!(snapshot(&a), snapshot(&b), "the same after a retry by the other relay");
|
||||||
|
for dir in [&a, &b] {
|
||||||
|
let db = rusqlite::Connection::open(dir.join("relay.sqlite3")).unwrap();
|
||||||
|
db.execute("UPDATE deliveries SET state='posting' WHERE key='9-00000000000000b2'", []).unwrap();
|
||||||
|
}
|
||||||
|
python(&repack, &b, 9000.0);
|
||||||
|
rust(&a, 9000.0);
|
||||||
|
for dir in [&a, &b] {
|
||||||
|
let db = rusqlite::Connection::open(dir.join("relay.sqlite3")).unwrap();
|
||||||
|
let state: String = db.query_row("SELECT state FROM deliveries WHERE key='9-00000000000000b2'", [], |r| r.get(0)).unwrap();
|
||||||
|
assert_eq!(state, "uncertain", "an interrupted post is not retried ({})", dir.display());
|
||||||
|
}
|
||||||
|
assert_eq!(snapshot(&a), snapshot(&b), "still the same after the crossover");
|
||||||
|
println!("PASS: relay journals, statuses and posts are the same in Python and Rust");
|
||||||
|
}
|
||||||
@@ -0,0 +1,103 @@
|
|||||||
|
//! SQUID database provisioning in Rust gives exactly what Scripts/squid_playerbots.py gives, on a DISPOSABLE repack:
|
||||||
|
//! the same journals (coa_squid_migrations, coa_squid_pending) in every schema, the same acore_playerbots tables
|
||||||
|
//! with the same row counts, the same playerbots.conf. Each side starts from the same state (SQUID never
|
||||||
|
//! provisioned), and a second run of each must change nothing.
|
||||||
|
//!
|
||||||
|
//! usage: squid_equivalence <fixture ending in -fixture> <coa-launcher.exe>
|
||||||
|
use std::path::Path;
|
||||||
|
use std::process::Command;
|
||||||
|
|
||||||
|
use coa_core::launcher::{services, squid};
|
||||||
|
|
||||||
|
fn sql(root: &Path, q: &str) -> String {
|
||||||
|
services::mysql(root, Some(q), None).unwrap_or_else(|e| panic!("{q}: {e}"))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// What provisioning leaves behind, comparable between runs.
|
||||||
|
fn snapshot(root: &Path) -> String {
|
||||||
|
let mut out = Vec::new();
|
||||||
|
for schema in ["acore_characters", "acore_world", "acore_playerbots"] {
|
||||||
|
let tables = sql(root, &format!("SELECT TABLE_NAME FROM information_schema.TABLES WHERE TABLE_SCHEMA='{schema}' ORDER BY TABLE_NAME;"));
|
||||||
|
for t in tables.lines() {
|
||||||
|
if schema != "acore_playerbots" && !t.starts_with("coa_squid") {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
let n = sql(root, &format!("SELECT COUNT(*) FROM `{schema}`.`{t}`;"));
|
||||||
|
out.push(format!("{schema}.{t} rows={n}"));
|
||||||
|
if t == "coa_squid_migrations" || t == "coa_squid_pending" {
|
||||||
|
for row in sql(root, &format!("SELECT path, sha256 FROM `{schema}`.`{t}` ORDER BY path;")).lines() {
|
||||||
|
out.push(format!(" {row}"));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let conf = std::fs::read_to_string(root.join("Core/configs/modules/playerbots.conf")).unwrap();
|
||||||
|
out.push(format!("playerbots.conf:\n{}", conf.replace("\r\n", "\n")));
|
||||||
|
out.join("\n")
|
||||||
|
}
|
||||||
|
|
||||||
|
fn reset(root: &Path, conf: &[u8]) {
|
||||||
|
sql(root, "DROP DATABASE IF EXISTS acore_playerbots;");
|
||||||
|
for schema in ["acore_characters", "acore_world"] {
|
||||||
|
sql(root, &format!("DROP TABLE IF EXISTS `{schema}`.coa_squid_migrations, `{schema}`.coa_squid_pending;"));
|
||||||
|
}
|
||||||
|
std::fs::write(root.join("Core/configs/modules/playerbots.conf"), conf).unwrap();
|
||||||
|
}
|
||||||
|
|
||||||
|
fn python(root: &Path) {
|
||||||
|
let harness = root.join(".state/squid_harness.py");
|
||||||
|
std::fs::write(
|
||||||
|
&harness,
|
||||||
|
"import sys, pathlib\nroot = pathlib.Path(sys.argv[1])\nsys.path.insert(0, str(root / 'Scripts'))\nsys.argv = ['manage.py']\nimport manage\nfrom squid_playerbots import prepare_playerbots\nprepare_playerbots(manage.ROOT, manage.settings(), manage.mysql)\n",
|
||||||
|
)
|
||||||
|
.unwrap();
|
||||||
|
let out = Command::new(root.join("Runtime/python/python.exe")).arg("-B").arg(&harness).arg(root).output().unwrap();
|
||||||
|
assert!(out.status.success(), "python: {}{}", String::from_utf8_lossy(&out.stdout), String::from_utf8_lossy(&out.stderr));
|
||||||
|
print!("{}", String::from_utf8_lossy(&out.stdout));
|
||||||
|
}
|
||||||
|
|
||||||
|
fn rust(root: &Path) {
|
||||||
|
let cfg = coa_core::launcher::Settings::load(root, 0).unwrap();
|
||||||
|
squid::prepare_playerbots(root, cfg.mysql_port, &|q| services::mysql(root, Some(q), None), &|m| println!("{m}")).unwrap();
|
||||||
|
}
|
||||||
|
|
||||||
|
fn main() {
|
||||||
|
let a: Vec<String> = std::env::args().skip(1).collect();
|
||||||
|
let root = Path::new(&a[0]);
|
||||||
|
let exe = Path::new(&a[1]);
|
||||||
|
assert!(a[0].ends_with("-fixture"));
|
||||||
|
let modules = root.join("Core/configs/modules");
|
||||||
|
// SQUID on, Companions off
|
||||||
|
let companions = std::fs::read_to_string(modules.join("mod_coa_playerbots.conf")).unwrap();
|
||||||
|
std::fs::write(modules.join("mod_coa_playerbots.conf"), companions.replace("CoaBots.Enable = 1", "CoaBots.Enable = 0")).unwrap();
|
||||||
|
let squid_conf = std::fs::read_to_string(modules.join("playerbots.conf")).unwrap().replace("AiPlayerbot.Enabled = 0", "AiPlayerbot.Enabled = 1");
|
||||||
|
let r = root.to_string_lossy().into_owned();
|
||||||
|
let started = Command::new(exe).args(["--root", &r, "start-mysql"]).output().unwrap();
|
||||||
|
assert!(started.status.success(), "{}", String::from_utf8_lossy(&started.stderr));
|
||||||
|
|
||||||
|
reset(root, squid_conf.as_bytes());
|
||||||
|
let t = std::time::Instant::now();
|
||||||
|
python(root);
|
||||||
|
println!("python provisioned in {:?}", t.elapsed());
|
||||||
|
let by_python = snapshot(root);
|
||||||
|
python(root);
|
||||||
|
assert_eq!(snapshot(root), by_python, "a second Python run changed something");
|
||||||
|
|
||||||
|
reset(root, squid_conf.as_bytes());
|
||||||
|
let t = std::time::Instant::now();
|
||||||
|
rust(root);
|
||||||
|
println!("rust provisioned in {:?}", t.elapsed());
|
||||||
|
let by_rust = snapshot(root);
|
||||||
|
rust(root);
|
||||||
|
assert_eq!(snapshot(root), by_rust, "a second Rust run changed something");
|
||||||
|
|
||||||
|
if by_python != by_rust {
|
||||||
|
std::fs::write(root.join(".state/squid-python.txt"), &by_python).unwrap();
|
||||||
|
std::fs::write(root.join(".state/squid-rust.txt"), &by_rust).unwrap();
|
||||||
|
panic!("Rust and Python differ: see .state/squid-python.txt and squid-rust.txt");
|
||||||
|
}
|
||||||
|
println!("{} lines of journal/table/config state are identical", by_rust.lines().count());
|
||||||
|
let stopped = Command::new(exe).args(["--root", &r, "stop-all"]).output().unwrap();
|
||||||
|
assert!(stopped.status.success());
|
||||||
|
println!("SQUID EQUIVALENCE PASS");
|
||||||
|
}
|
||||||
@@ -1032,8 +1032,13 @@ pub fn analyze_github_repository(url_str: &str, cache_base_dir: Option<&Path>) -
|
|||||||
let marker_file = commit_cache_dir.join(".coa_tree_digest");
|
let marker_file = commit_cache_dir.join(".coa_tree_digest");
|
||||||
|
|
||||||
let cache_hit = commit_cache_dir.exists() && marker_file.exists();
|
let cache_hit = commit_cache_dir.exists() && marker_file.exists();
|
||||||
|
let pinned = resolved_commit.len() == 40 && resolved_commit.bytes().all(|b| b.is_ascii_hexdigit());
|
||||||
let target_dir = if cache_hit {
|
let target_dir = if cache_hit {
|
||||||
commit_cache_dir
|
commit_cache_dir
|
||||||
|
} else if pinned {
|
||||||
|
// GitHub's archive of the exact commit, without the game-client files some repositories carry (they
|
||||||
|
// are not needed to build a server module and used to push such repositories over the size limit).
|
||||||
|
crate::module_sources::fetch_pinned(&owner, &repo, &resolved_commit, &base_cache)?
|
||||||
} else {
|
} else {
|
||||||
// Clone into temporary staging directory
|
// Clone into temporary staging directory
|
||||||
let staging_id = format!("{}_{}_{}", owner, repo, std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap().as_millis());
|
let staging_id = format!("{}_{}_{}", owner, repo, std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap().as_millis());
|
||||||
|
|||||||
@@ -0,0 +1,355 @@
|
|||||||
|
//! The compiler's work kept between builds of a module, small on disk.
|
||||||
|
//!
|
||||||
|
//! A build works in `<meta>/build-cache/<module>/` (sources, CMake/Ninja state, object files). Between builds
|
||||||
|
//! that folder is packed into `<module>.tar.zst` (object files compress about 4x) with a small record of the
|
||||||
|
//! core it was made for. Before the next build it is unpacked again, so Ninja recompiles only what changed.
|
||||||
|
//!
|
||||||
|
//! Object files made for another core are useless (every one depends on the core's headers), so a cache for
|
||||||
|
//! another core is dropped instead of unpacked. The whole cache is kept under a size limit: the modules built
|
||||||
|
//! longest ago go first. Incremental-link files (`.ilk`) and linker maps are not kept.
|
||||||
|
|
||||||
|
use std::fs;
|
||||||
|
use std::io::{BufReader, BufWriter};
|
||||||
|
use std::path::{Path, PathBuf};
|
||||||
|
|
||||||
|
use serde::{Deserialize, Serialize};
|
||||||
|
|
||||||
|
use crate::error::{Error, Result};
|
||||||
|
|
||||||
|
/// Packed caches above this total are removed, the least recently built first.
|
||||||
|
pub const LIMIT_BYTES: u64 = 2 * 1024 * 1024 * 1024;
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||||
|
struct Record {
|
||||||
|
/// ABI fingerprint of the core the objects were compiled for.
|
||||||
|
fingerprint: String,
|
||||||
|
/// Unix seconds of the last build.
|
||||||
|
last_used: i64,
|
||||||
|
unpacked_bytes: u64,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Serialize)]
|
||||||
|
pub struct CacheEntry {
|
||||||
|
pub module: String,
|
||||||
|
/// Bytes on disk now (packed, or unpacked while a build runs).
|
||||||
|
pub bytes: u64,
|
||||||
|
pub unpacked_bytes: u64,
|
||||||
|
pub last_used: i64,
|
||||||
|
/// Made for the core this server runs now (otherwise it is dropped at the next build).
|
||||||
|
pub current_core: bool,
|
||||||
|
pub packed: bool,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Serialize)]
|
||||||
|
pub struct CacheSummary {
|
||||||
|
pub modules: Vec<CacheEntry>,
|
||||||
|
pub total_bytes: u64,
|
||||||
|
/// Downloaded module sources (shared by all servers of this Manager).
|
||||||
|
pub sources_bytes: u64,
|
||||||
|
pub limit_bytes: u64,
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn root(realm_root: &Path) -> PathBuf {
|
||||||
|
crate::plugins::meta_dir(realm_root).join("build-cache")
|
||||||
|
}
|
||||||
|
|
||||||
|
fn valid_id(id: &str) -> bool {
|
||||||
|
!id.is_empty() && id.len() <= 100 && id.chars().all(|c| c.is_ascii_alphanumeric() || matches!(c, '-' | '_' | '.')) && id != "." && id != ".."
|
||||||
|
}
|
||||||
|
|
||||||
|
fn paths(realm_root: &Path, id: &str) -> Result<(PathBuf, PathBuf, PathBuf)> {
|
||||||
|
if !valid_id(id) {
|
||||||
|
return Err(Error::Invalid(format!("Invalid module id for the build cache: {id}")));
|
||||||
|
}
|
||||||
|
let r = root(realm_root);
|
||||||
|
Ok((r.join(id), r.join(format!("{id}.tar.zst")), r.join(format!("{id}.json"))))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn now() -> i64 {
|
||||||
|
chrono::Utc::now().timestamp()
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) fn dir_bytes(dir: &Path) -> u64 {
|
||||||
|
fs::read_dir(dir)
|
||||||
|
.map(|rd| {
|
||||||
|
rd.flatten()
|
||||||
|
.map(|e| match e.metadata() {
|
||||||
|
Ok(m) if m.is_dir() => dir_bytes(&e.path()),
|
||||||
|
Ok(m) => m.len(),
|
||||||
|
Err(_) => 0,
|
||||||
|
})
|
||||||
|
.sum()
|
||||||
|
})
|
||||||
|
.unwrap_or(0)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn read_record(path: &Path) -> Option<Record> {
|
||||||
|
serde_json::from_slice(&fs::read(path).ok()?).ok()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The working folder for a build of `id` for the core `fingerprint`, with the earlier work of a build for the
|
||||||
|
/// same core unpacked into it. A cache for another core is dropped.
|
||||||
|
pub fn prepare(realm_root: &Path, id: &str, fingerprint: &str) -> Result<PathBuf> {
|
||||||
|
let (dir, archive, record) = paths(realm_root, id)?;
|
||||||
|
let rec = read_record(&record);
|
||||||
|
let same_core = rec.as_ref().is_some_and(|r| r.fingerprint == fingerprint);
|
||||||
|
if !same_core {
|
||||||
|
// made for another core (or unknown): its objects would all be rebuilt anyway
|
||||||
|
if dir.exists() {
|
||||||
|
fs::remove_dir_all(&dir)?;
|
||||||
|
}
|
||||||
|
let _ = fs::remove_file(&archive);
|
||||||
|
let _ = fs::remove_file(&record);
|
||||||
|
} else if archive.is_file() {
|
||||||
|
if dir.exists() {
|
||||||
|
fs::remove_dir_all(&dir)?; // an older, interrupted working folder: the archive is the newer state
|
||||||
|
}
|
||||||
|
unpack(&archive, &dir).map_err(|e| {
|
||||||
|
let _ = fs::remove_dir_all(&dir);
|
||||||
|
Error::Invalid(format!("The build cache of {id} could not be unpacked: {e}"))
|
||||||
|
})?;
|
||||||
|
fs::remove_file(&archive)?;
|
||||||
|
}
|
||||||
|
fs::create_dir_all(&dir)?;
|
||||||
|
let unpacked_bytes = dir_bytes(&dir);
|
||||||
|
crate::fsx::atomic_write_json(&record, &Record { fingerprint: fingerprint.into(), last_used: now(), unpacked_bytes })?;
|
||||||
|
Ok(dir)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// After a build (successful or not): drop what does not speed up the next one, pack the rest, keep the total
|
||||||
|
/// under the limit. Never fails the build: problems only cost the cache.
|
||||||
|
pub fn finish(realm_root: &Path, id: &str) {
|
||||||
|
let Ok((dir, archive, record)) = paths(realm_root, id) else { return };
|
||||||
|
if !dir.is_dir() {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
remove_by_ext(&dir, &["ilk", "map"]);
|
||||||
|
let unpacked_bytes = dir_bytes(&dir);
|
||||||
|
let tmp = archive.with_extension("zst.partial");
|
||||||
|
match pack(&dir, &tmp).and_then(|_| fs::rename(&tmp, &archive).map_err(Into::into)) {
|
||||||
|
Ok(()) => {
|
||||||
|
let _ = fs::remove_dir_all(&dir);
|
||||||
|
if let Some(mut r) = read_record(&record) {
|
||||||
|
r.last_used = now();
|
||||||
|
r.unpacked_bytes = unpacked_bytes;
|
||||||
|
let _ = crate::fsx::atomic_write_json(&record, &r);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Err(e) => {
|
||||||
|
tracing::warn!(module = id, error = %e, "build cache not packed; it is kept unpacked");
|
||||||
|
let _ = fs::remove_file(&tmp);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
enforce_limit(realm_root, LIMIT_BYTES, Some(id));
|
||||||
|
}
|
||||||
|
|
||||||
|
fn remove_by_ext(dir: &Path, exts: &[&str]) {
|
||||||
|
for e in fs::read_dir(dir).into_iter().flatten().flatten() {
|
||||||
|
let p = e.path();
|
||||||
|
if p.is_dir() {
|
||||||
|
remove_by_ext(&p, exts);
|
||||||
|
} else if p.extension().and_then(|x| x.to_str()).is_some_and(|x| exts.iter().any(|w| w.eq_ignore_ascii_case(x))) {
|
||||||
|
let _ = fs::remove_file(p);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn pack(dir: &Path, out: &Path) -> Result<()> {
|
||||||
|
let file = BufWriter::new(fs::File::create(out)?);
|
||||||
|
let mut enc = zstd::Encoder::new(file, 3)?;
|
||||||
|
let _ = enc.multithread(std::thread::available_parallelism().map(|n| n.get() as u32).unwrap_or(1).min(8));
|
||||||
|
{
|
||||||
|
let mut tar = tar::Builder::new(&mut enc);
|
||||||
|
tar.follow_symlinks(false);
|
||||||
|
// modification times are kept: Ninja decides from them what is up to date
|
||||||
|
tar.mode(tar::HeaderMode::Complete);
|
||||||
|
tar.append_dir_all(".", dir)?;
|
||||||
|
tar.finish()?;
|
||||||
|
}
|
||||||
|
enc.finish()?;
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn unpack(archive: &Path, dir: &Path) -> Result<()> {
|
||||||
|
fs::create_dir_all(dir)?;
|
||||||
|
let dec = zstd::Decoder::new(BufReader::new(fs::File::open(archive)?))?;
|
||||||
|
let mut tar = tar::Archive::new(dec);
|
||||||
|
tar.set_preserve_mtime(true);
|
||||||
|
for entry in tar.entries()? {
|
||||||
|
let mut entry = entry?;
|
||||||
|
// unpack_in refuses paths that would leave `dir`
|
||||||
|
if !entry.unpack_in(dir)? {
|
||||||
|
return Err(Error::PathRejected(format!("build cache entry {}", entry.path()?.display())));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Everything in the build cache of this server, largest first.
|
||||||
|
pub fn summary(realm_root: &Path, sources_dir: Option<&Path>) -> CacheSummary {
|
||||||
|
let current = crate::provenance::realm_host_fingerprint(realm_root);
|
||||||
|
let r = root(realm_root);
|
||||||
|
let mut modules = Vec::new();
|
||||||
|
for e in fs::read_dir(&r).into_iter().flatten().flatten() {
|
||||||
|
let name = e.file_name().to_string_lossy().into_owned();
|
||||||
|
let Some(id) = name.strip_suffix(".json") else { continue };
|
||||||
|
let Ok((dir, archive, record)) = paths(realm_root, id) else { continue };
|
||||||
|
let Some(rec) = read_record(&record) else { continue };
|
||||||
|
let packed = archive.is_file();
|
||||||
|
let bytes = if packed { fs::metadata(&archive).map(|m| m.len()).unwrap_or(0) } else { dir_bytes(&dir) };
|
||||||
|
modules.push(CacheEntry {
|
||||||
|
module: id.to_string(),
|
||||||
|
bytes,
|
||||||
|
unpacked_bytes: rec.unpacked_bytes,
|
||||||
|
last_used: rec.last_used,
|
||||||
|
current_core: current.as_deref() == Some(rec.fingerprint.as_str()),
|
||||||
|
packed,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
// working folders of an older Manager, without a record
|
||||||
|
for e in fs::read_dir(&r).into_iter().flatten().flatten() {
|
||||||
|
let name = e.file_name().to_string_lossy().into_owned();
|
||||||
|
if e.path().is_dir() && valid_id(&name) && !modules.iter().any(|m| m.module == name) {
|
||||||
|
let bytes = dir_bytes(&e.path());
|
||||||
|
modules.push(CacheEntry { module: name, bytes, unpacked_bytes: bytes, last_used: 0, current_core: false, packed: false });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
modules.sort_by(|a, b| b.bytes.cmp(&a.bytes));
|
||||||
|
CacheSummary {
|
||||||
|
total_bytes: modules.iter().map(|m| m.bytes).sum(),
|
||||||
|
sources_bytes: sources_dir.map(dir_bytes).unwrap_or(0),
|
||||||
|
limit_bytes: LIMIT_BYTES,
|
||||||
|
modules,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Remove the cache of one module, or of all. The next build of a module compiles it in full.
|
||||||
|
pub fn clear(realm_root: &Path, module: Option<&str>) -> Result<u64> {
|
||||||
|
let before = summary(realm_root, None).total_bytes;
|
||||||
|
match module {
|
||||||
|
Some(id) => {
|
||||||
|
let (dir, archive, record) = paths(realm_root, id)?;
|
||||||
|
if dir.exists() {
|
||||||
|
fs::remove_dir_all(dir)?;
|
||||||
|
}
|
||||||
|
let _ = fs::remove_file(archive);
|
||||||
|
let _ = fs::remove_file(record);
|
||||||
|
}
|
||||||
|
None => {
|
||||||
|
let r = root(realm_root);
|
||||||
|
if r.exists() {
|
||||||
|
fs::remove_dir_all(&r)?;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Ok(before.saturating_sub(summary(realm_root, None).total_bytes))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Keep the packed caches under `limit`, dropping the least recently built (never `keep`).
|
||||||
|
fn enforce_limit(realm_root: &Path, limit: u64, keep: Option<&str>) {
|
||||||
|
let mut s = summary(realm_root, None);
|
||||||
|
s.modules.sort_by_key(|m| m.last_used);
|
||||||
|
let mut total = s.total_bytes;
|
||||||
|
for m in &s.modules {
|
||||||
|
if total <= limit {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
if Some(m.module.as_str()) == keep {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if clear(realm_root, Some(&m.module)).is_ok() {
|
||||||
|
tracing::info!(module = %m.module, bytes = m.bytes, "build cache over its limit: oldest removed");
|
||||||
|
total = total.saturating_sub(m.bytes);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Downloaded module sources the Manager keeps (`<cache>/github`, `<cache>/staging`).
|
||||||
|
pub fn clear_sources(sources_dir: &Path) -> Result<u64> {
|
||||||
|
let before = dir_bytes(sources_dir);
|
||||||
|
for sub in ["github", "staging"] {
|
||||||
|
let p = sources_dir.join(sub);
|
||||||
|
if p.exists() {
|
||||||
|
fs::remove_dir_all(p)?;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Ok(before.saturating_sub(dir_bytes(sources_dir)))
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
use std::time::{Duration, SystemTime};
|
||||||
|
|
||||||
|
fn server() -> tempfile::TempDir {
|
||||||
|
let d = tempfile::tempdir().unwrap();
|
||||||
|
fs::create_dir_all(d.path().join(".manager")).unwrap();
|
||||||
|
d
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_cache_is_packed_between_builds_and_comes_back_with_its_times() {
|
||||||
|
let s = server();
|
||||||
|
let dir = prepare(s.path(), "companions", "fp1").unwrap();
|
||||||
|
fs::create_dir_all(dir.join("build/obj")).unwrap();
|
||||||
|
fs::write(dir.join("build/obj/a.obj"), vec![7u8; 100_000]).unwrap();
|
||||||
|
fs::write(dir.join("build/x.ilk"), b"incremental link").unwrap();
|
||||||
|
let old = SystemTime::now() - Duration::from_secs(3600);
|
||||||
|
fs::File::options().write(true).open(dir.join("build/obj/a.obj")).unwrap().set_modified(old).unwrap();
|
||||||
|
finish(s.path(), "companions");
|
||||||
|
assert!(!dir.exists(), "packed between builds");
|
||||||
|
let sum = summary(s.path(), None);
|
||||||
|
assert_eq!(sum.modules.len(), 1);
|
||||||
|
assert!(sum.modules[0].packed && sum.modules[0].bytes < 100_000 / 4, "compressed: {}", sum.modules[0].bytes);
|
||||||
|
|
||||||
|
let dir = prepare(s.path(), "companions", "fp1").unwrap();
|
||||||
|
assert_eq!(fs::read(dir.join("build/obj/a.obj")).unwrap().len(), 100_000);
|
||||||
|
assert!(!dir.join("build/x.ilk").exists(), "incremental-link files are not kept");
|
||||||
|
let mtime = fs::metadata(dir.join("build/obj/a.obj")).unwrap().modified().unwrap();
|
||||||
|
let drift = mtime.duration_since(old).unwrap_or_else(|e| e.duration());
|
||||||
|
assert!(drift < Duration::from_secs(2), "modification time kept (drift {drift:?})");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_cache_for_another_core_is_dropped() {
|
||||||
|
let s = server();
|
||||||
|
let dir = prepare(s.path(), "scaling", "old-core").unwrap();
|
||||||
|
fs::write(dir.join("a.obj"), b"old").unwrap();
|
||||||
|
finish(s.path(), "scaling");
|
||||||
|
let dir = prepare(s.path(), "scaling", "new-core").unwrap();
|
||||||
|
assert!(!dir.join("a.obj").exists());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn clear_removes_one_module_or_all_and_bad_ids_are_refused() {
|
||||||
|
let s = server();
|
||||||
|
for id in ["a", "b"] {
|
||||||
|
let d = prepare(s.path(), id, "fp").unwrap();
|
||||||
|
fs::write(d.join("x.obj"), b"x").unwrap();
|
||||||
|
finish(s.path(), id);
|
||||||
|
}
|
||||||
|
clear(s.path(), Some("a")).unwrap();
|
||||||
|
assert_eq!(summary(s.path(), None).modules.iter().map(|m| m.module.as_str()).collect::<Vec<_>>(), ["b"]);
|
||||||
|
clear(s.path(), None).unwrap();
|
||||||
|
assert!(summary(s.path(), None).modules.is_empty());
|
||||||
|
assert!(clear(s.path(), Some("../x")).is_err());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn the_least_recently_built_go_first_over_the_limit() {
|
||||||
|
let s = server();
|
||||||
|
for (n, id) in ["old", "new"].iter().enumerate() {
|
||||||
|
let d = prepare(s.path(), id, "fp").unwrap();
|
||||||
|
fs::write(d.join("x.obj"), vec![n as u8; 50_000]).unwrap();
|
||||||
|
finish(s.path(), id);
|
||||||
|
let rec = root(s.path()).join(format!("{id}.json"));
|
||||||
|
let mut r = read_record(&rec).unwrap();
|
||||||
|
r.last_used = 1000 + n as i64;
|
||||||
|
crate::fsx::atomic_write_json(&rec, &r).unwrap();
|
||||||
|
}
|
||||||
|
let total = summary(s.path(), None).total_bytes;
|
||||||
|
enforce_limit(s.path(), total - 1, None);
|
||||||
|
let left: Vec<String> = summary(s.path(), None).modules.into_iter().map(|m| m.module).collect();
|
||||||
|
assert_eq!(left, ["new"]);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -977,8 +977,25 @@ pub fn build_module_with_bundle(
|
|||||||
.unwrap_or_else(|| with_plugin_id(&adapter_source, &plugin_id));
|
.unwrap_or_else(|| with_plugin_id(&adapter_source, &plugin_id));
|
||||||
|
|
||||||
// 2. Prepare the persistent staging directory
|
// 2. Prepare the persistent staging directory
|
||||||
let default_staging = realm_root.join(".manager").join("build-cache").join(&module_id);
|
// The Manager's own builds use the module's build cache (unpacked for the build, packed again afterwards);
|
||||||
let staging_dir = custom_staging_dir.map(PathBuf::from).unwrap_or(default_staging);
|
// a caller-chosen folder is used as it is.
|
||||||
|
let staging_dir = match custom_staging_dir {
|
||||||
|
Some(p) => PathBuf::from(p),
|
||||||
|
None => crate::build_cache::prepare(realm_root, &module_id, &sdk_abi_fingerprint(Path::new(&sdk_dir))?)?,
|
||||||
|
};
|
||||||
|
struct PackAfter<'a>(Option<(&'a Path, String)>);
|
||||||
|
impl Drop for PackAfter<'_> {
|
||||||
|
fn drop(&mut self) {
|
||||||
|
if let Some((root, id)) = self.0.take() {
|
||||||
|
crate::build_cache::finish(root, &id);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let _pack_after = PackAfter(custom_staging_dir.is_none().then(|| (realm_root, module_id.clone())));
|
||||||
|
let log_path = match custom_staging_dir {
|
||||||
|
Some(_) => staging_dir.join("build.log"),
|
||||||
|
None => crate::build_cache::root(realm_root).join(format!("{module_id}.log")),
|
||||||
|
};
|
||||||
fs::create_dir_all(&staging_dir)?;
|
fs::create_dir_all(&staging_dir)?;
|
||||||
let staging_src = staging_dir.join("src");
|
let staging_src = staging_dir.join("src");
|
||||||
fs::create_dir_all(&staging_src)?;
|
fs::create_dir_all(&staging_src)?;
|
||||||
@@ -1142,11 +1159,11 @@ if errorlevel 1 exit /b 103
|
|||||||
}
|
}
|
||||||
|
|
||||||
// The full log stays next to the build, so a failure can always be read afterwards.
|
// The full log stays next to the build, so a failure can always be read afterwards.
|
||||||
let _ = fs::write(staging_dir.join("build.log"), all_logs.join("
|
let _ = fs::write(&log_path, all_logs.join("
|
||||||
"));
|
"));
|
||||||
let mut errors = parse_msvc_errors(&all_logs);
|
let mut errors = parse_msvc_errors(&all_logs);
|
||||||
if exit_code != 0 && errors.is_empty() {
|
if exit_code != 0 && errors.is_empty() {
|
||||||
errors.push(unparsed_failure(exit_code, &all_logs, &staging_dir.join("build.log")));
|
errors.push(unparsed_failure(exit_code, &all_logs, &log_path));
|
||||||
}
|
}
|
||||||
|
|
||||||
let expected_dll_path = build_output_dir.join(format!("{}.dll", safe_target_name));
|
let expected_dll_path = build_output_dir.join(format!("{}.dll", safe_target_name));
|
||||||
@@ -1332,7 +1349,11 @@ mod tests {
|
|||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn test_detect_toolchain() {
|
fn test_detect_toolchain() {
|
||||||
let tc = detect_toolchain_for(Some(Path::new("C:/games/coa-work/plugin-spike/server-v03")));
|
let realm = Path::new("C:/games/coa-work/plugin-spike/server-v03");
|
||||||
|
if !realm.join("worldserver.exe").is_file() {
|
||||||
|
return; // needs the local spike realm and its SDK (not on CI runners)
|
||||||
|
}
|
||||||
|
let tc = detect_toolchain_for(Some(realm));
|
||||||
assert!(tc.msvc_available, "MSVC vcvars64.bat should be detected");
|
assert!(tc.msvc_available, "MSVC vcvars64.bat should be detected");
|
||||||
assert!(tc.cmake_available, "CMake should be detected");
|
assert!(tc.cmake_available, "CMake should be detected");
|
||||||
assert!(tc.ninja_available, "Ninja should be detected");
|
assert!(tc.ninja_available, "Ninja should be detected");
|
||||||
|
|||||||
@@ -170,6 +170,178 @@ pub struct PublicCatalogueItem {
|
|||||||
pub coa_status_source: String, // "Overlay", "VerifiedCatalog", "AutoPublic"
|
pub coa_status_source: String, // "Overlay", "VerifiedCatalog", "AutoPublic"
|
||||||
pub conflict_reason: Option<String>,
|
pub conflict_reason: Option<String>,
|
||||||
pub is_coa_recommended: bool,
|
pub is_coa_recommended: bool,
|
||||||
|
/// Functional category code (see `coa-module-categories.json`); "other" when nothing fits.
|
||||||
|
#[serde(default)]
|
||||||
|
pub category: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||||
|
pub struct CategoryInfo {
|
||||||
|
pub code: String,
|
||||||
|
pub ru: String,
|
||||||
|
pub en: String,
|
||||||
|
#[serde(default)]
|
||||||
|
pub keywords: Vec<String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Deserialize)]
|
||||||
|
struct CategoryDocument {
|
||||||
|
categories: Vec<CategoryInfo>,
|
||||||
|
/// Owner-reviewed assignments (lowercase `owner/repo` -> category code).
|
||||||
|
repos: BTreeMap<String, String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
static EMBEDDED_CATEGORIES_JSON: &str = include_str!("coa-module-categories.json");
|
||||||
|
|
||||||
|
fn category_document() -> &'static CategoryDocument {
|
||||||
|
static DOC: std::sync::OnceLock<CategoryDocument> = std::sync::OnceLock::new();
|
||||||
|
DOC.get_or_init(|| {
|
||||||
|
serde_json::from_str(EMBEDDED_CATEGORIES_JSON).unwrap_or(CategoryDocument { categories: Vec::new(), repos: BTreeMap::new() })
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn categories() -> Vec<CategoryInfo> {
|
||||||
|
category_document().categories.clone()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Lowercase words of a text: letters and digits, so `mod-pvp-titles` gives `mod`, `pvp`, `titles`.
|
||||||
|
fn words(text: &str) -> Vec<String> {
|
||||||
|
text.to_lowercase()
|
||||||
|
.split(|c: char| !c.is_alphanumeric() && c != '+')
|
||||||
|
.filter(|w| !w.is_empty())
|
||||||
|
.map(str::to_string)
|
||||||
|
.collect()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn keyword_hits(keyword: &str, text_words: &[String]) -> usize {
|
||||||
|
let kw = words(keyword);
|
||||||
|
match kw.as_slice() {
|
||||||
|
[] => 0,
|
||||||
|
// one word: whole-word match; words of 4+ letters also match their plural or longer forms
|
||||||
|
[k] => text_words.iter().filter(|w| *w == k || (k.chars().count() >= 4 && w.starts_with(k.as_str()))).count(),
|
||||||
|
// a phrase: its words in a row
|
||||||
|
many => text_words.windows(many.len()).filter(|win| win.iter().zip(many).all(|(a, b)| a == b)).count(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The category of a module: the owner-reviewed list first, then the keywords of each category against the
|
||||||
|
/// repository's name (counted twice), description and topics; "other" when no keyword matches.
|
||||||
|
pub fn categorize(slug: &str, name: &str, description: &str, topics: &[String]) -> String {
|
||||||
|
let doc = category_document();
|
||||||
|
if let Some(code) = doc.repos.get(&normalize_repo_slug(slug)) {
|
||||||
|
return code.clone();
|
||||||
|
}
|
||||||
|
let name_words = words(name);
|
||||||
|
let mut body = words(description);
|
||||||
|
for t in topics.iter().filter(|t| !t.starts_with("azerothcore") && !matches!(t.as_str(), "wow" | "wotlk" | "world-of-warcraft")) {
|
||||||
|
body.extend(words(t));
|
||||||
|
}
|
||||||
|
let mut best: Option<(&str, usize)> = None;
|
||||||
|
for c in &doc.categories {
|
||||||
|
let score: usize = c.keywords.iter().map(|k| 2 * keyword_hits(k, &name_words) + keyword_hits(k, &body)).sum();
|
||||||
|
if score > 0 && best.is_none_or(|(_, s)| score > s) {
|
||||||
|
best = Some((&c.code, score));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
best.map(|(c, _)| c.to_string()).unwrap_or_else(|| "other".into())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Statuses and categories come from the current overlay and category list on every read, never from what a
|
||||||
|
/// cache stored: a corrected overlay must show at once. Entries an earlier version made up for overlay rules the
|
||||||
|
/// public catalogue does not contain (marked with the `coa-verified` topic) are dropped.
|
||||||
|
fn finalize(items: Vec<PublicCatalogueItem>, overlay: &CoaOverlayDocument) -> Vec<PublicCatalogueItem> {
|
||||||
|
let rules: BTreeMap<String, &CoaOverlayRule> =
|
||||||
|
overlay.rules.iter().map(|r| (normalize_repo_slug(&r.repo_slug), r)).collect();
|
||||||
|
items
|
||||||
|
.into_iter()
|
||||||
|
.filter(|i| !i.topics.iter().any(|t| t == "coa-verified"))
|
||||||
|
.map(|mut i| {
|
||||||
|
let slug = normalize_repo_slug(&i.full_name);
|
||||||
|
match rules.get(&slug) {
|
||||||
|
Some(rule) => {
|
||||||
|
i.coa_status = rule.status;
|
||||||
|
i.coa_status_source = "Overlay".into();
|
||||||
|
i.conflict_reason = rule.reason.clone();
|
||||||
|
i.is_coa_recommended = rule.is_recommended || rule.status == CoaCompatibilityStatus::Recommended;
|
||||||
|
}
|
||||||
|
None => {
|
||||||
|
i.coa_status = CoaCompatibilityStatus::Unverified;
|
||||||
|
i.coa_status_source = "AutoPublic".into();
|
||||||
|
i.conflict_reason = None;
|
||||||
|
i.is_coa_recommended = false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
i.category = categorize(&slug, &i.name, &i.description, &i.topics);
|
||||||
|
i
|
||||||
|
})
|
||||||
|
.collect()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn respond(items: Vec<PublicCatalogueItem>, overlay: &CoaOverlayDocument, cached_at: String, is_offline: bool, etag: Option<String>) -> PublicCatalogueResponse {
|
||||||
|
let items = finalize(items, overlay);
|
||||||
|
PublicCatalogueResponse {
|
||||||
|
total_count: items.len(),
|
||||||
|
recommended_count: items.iter().filter(|i| i.is_coa_recommended).count(),
|
||||||
|
cached_at,
|
||||||
|
is_offline,
|
||||||
|
etag,
|
||||||
|
items,
|
||||||
|
categories: categories().into_iter().map(|c| CategoryInfo { keywords: Vec::new(), ..c }).collect(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Last push (`pushed_at`) of GitHub repositories given as `owner/name`, for modules the public catalogue does
|
||||||
|
/// not list. Kept in `cache_file` for 12 hours; a repository GitHub does not answer for is `None` and asked
|
||||||
|
/// again next time.
|
||||||
|
pub fn repo_last_push(cache_file: &Path, repos: &[String]) -> Result<BTreeMap<String, Option<String>>> {
|
||||||
|
#[derive(Serialize, Deserialize, Default)]
|
||||||
|
struct Cache {
|
||||||
|
at: i64,
|
||||||
|
pushed: BTreeMap<String, String>,
|
||||||
|
}
|
||||||
|
let now = Utc::now().timestamp();
|
||||||
|
let mut cache: Cache = fs::read(cache_file).ok().and_then(|b| serde_json::from_slice(&b).ok()).unwrap_or_default();
|
||||||
|
if now - cache.at > 12 * 3600 {
|
||||||
|
cache = Cache { at: now, pushed: BTreeMap::new() };
|
||||||
|
}
|
||||||
|
let name_ok = |s: Option<&str>| {
|
||||||
|
s.is_some_and(|s| !s.is_empty() && s.len() <= 100 && s.chars().all(|c| c.is_ascii_alphanumeric() || matches!(c, '-' | '_' | '.')))
|
||||||
|
};
|
||||||
|
let valid = |r: &str| {
|
||||||
|
let mut parts = r.split('/');
|
||||||
|
name_ok(parts.next()) && name_ok(parts.next()) && parts.next().is_none()
|
||||||
|
};
|
||||||
|
let client = reqwest::blocking::Client::builder()
|
||||||
|
.connect_timeout(Duration::from_secs(CONNECT_TIMEOUT_SECS))
|
||||||
|
.timeout(Duration::from_secs(10))
|
||||||
|
.build()
|
||||||
|
.map_err(|e| Error::Invalid(e.to_string()))?;
|
||||||
|
let mut out = BTreeMap::new();
|
||||||
|
for repo in repos.iter().map(|r| r.trim().to_ascii_lowercase()).filter(|r| valid(r)) {
|
||||||
|
if let Some(v) = cache.pushed.get(&repo) {
|
||||||
|
out.insert(repo, Some(v.clone()));
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
let pushed = client
|
||||||
|
.get(format!("https://api.github.com/repos/{repo}"))
|
||||||
|
.header(reqwest::header::USER_AGENT, "CSM-Modules-Preview")
|
||||||
|
.header(reqwest::header::ACCEPT, "application/vnd.github+json")
|
||||||
|
.send()
|
||||||
|
.ok()
|
||||||
|
.filter(|r| r.status().is_success())
|
||||||
|
.and_then(|r| r.text().ok())
|
||||||
|
.and_then(|t| serde_json::from_str::<serde_json::Value>(&t).ok())
|
||||||
|
.and_then(|v| v.get("pushed_at")?.as_str().map(str::to_string));
|
||||||
|
if let Some(p) = &pushed {
|
||||||
|
cache.pushed.insert(repo.clone(), p.clone());
|
||||||
|
}
|
||||||
|
out.insert(repo, pushed);
|
||||||
|
}
|
||||||
|
if let Some(dir) = cache_file.parent() {
|
||||||
|
let _ = fs::create_dir_all(dir);
|
||||||
|
}
|
||||||
|
let _ = fsx::atomic_write_json(cache_file, &cache);
|
||||||
|
Ok(out)
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||||
@@ -191,6 +363,8 @@ pub struct PublicCatalogueResponse {
|
|||||||
pub etag: Option<String>,
|
pub etag: Option<String>,
|
||||||
pub total_count: usize,
|
pub total_count: usize,
|
||||||
pub recommended_count: usize,
|
pub recommended_count: usize,
|
||||||
|
#[serde(default)]
|
||||||
|
pub categories: Vec<CategoryInfo>,
|
||||||
}
|
}
|
||||||
|
|
||||||
// ---------------------------------------------------------------------------
|
// ---------------------------------------------------------------------------
|
||||||
@@ -368,44 +542,14 @@ pub fn normalize_catalogue(
|
|||||||
coa_status_source: coa_source,
|
coa_status_source: coa_source,
|
||||||
conflict_reason: reason,
|
conflict_reason: reason,
|
||||||
is_coa_recommended: is_rec,
|
is_coa_recommended: is_rec,
|
||||||
|
category: String::new(),
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
// 4. Also ensure any Recommended overlay rules that were not present in the public raw catalog
|
// Overlay rules for repositories the public catalogue does not list are not turned into entries: the
|
||||||
// are included so they are never lost
|
// catalogue shows only what azerothcore.org lists (CoA's own modules are in the Manager's curated list).
|
||||||
for rule in &overlay.rules {
|
|
||||||
let slug = normalize_repo_slug(&rule.repo_slug);
|
|
||||||
if seen_slugs.insert(slug.clone()) {
|
|
||||||
let parts: Vec<&str> = slug.split('/').collect();
|
|
||||||
let (owner, name) = if parts.len() >= 2 {
|
|
||||||
(parts[0].to_string(), parts[1].to_string())
|
|
||||||
} else {
|
|
||||||
("corfirean".to_string(), slug.clone())
|
|
||||||
};
|
|
||||||
|
|
||||||
normalized.push(PublicCatalogueItem {
|
// 4. Sort:
|
||||||
id: rule.repo_id.unwrap_or(0),
|
|
||||||
name: name.clone(),
|
|
||||||
full_name: slug.clone(),
|
|
||||||
owner,
|
|
||||||
html_url: format!("https://github.com/{}", slug),
|
|
||||||
description: rule.reason.clone().unwrap_or_default(),
|
|
||||||
stars: 0,
|
|
||||||
forks: 0,
|
|
||||||
default_branch: "master".to_string(),
|
|
||||||
pushed_at: None,
|
|
||||||
updated_at: None,
|
|
||||||
license: Some("AGPL-3.0".to_string()),
|
|
||||||
topics: vec!["azerothcore-module".to_string(), "coa-verified".to_string()],
|
|
||||||
coa_status: rule.status,
|
|
||||||
coa_status_source: "Overlay".to_string(),
|
|
||||||
conflict_reason: rule.reason.clone(),
|
|
||||||
is_coa_recommended: rule.is_recommended || rule.status == CoaCompatibilityStatus::Recommended,
|
|
||||||
});
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// 5. Sort:
|
|
||||||
// Group A (Recommended/Verified) first, then by Stars desc, then by pushed_at desc
|
// Group A (Recommended/Verified) first, then by Stars desc, then by pushed_at desc
|
||||||
normalized.sort_by(|a, b| {
|
normalized.sort_by(|a, b| {
|
||||||
// Priority 1: Recommended modules first
|
// Priority 1: Recommended modules first
|
||||||
@@ -461,15 +605,7 @@ pub fn fetch_or_load_catalogue(
|
|||||||
if let Ok(cached) = serde_json::from_str::<CachedDocument>(&content) {
|
if let Ok(cached) = serde_json::from_str::<CachedDocument>(&content) {
|
||||||
let age = now_ts - cached.timestamp;
|
let age = now_ts - cached.timestamp;
|
||||||
if age < DEFAULT_CACHE_TTL_SECS && !cached.items.is_empty() {
|
if age < DEFAULT_CACHE_TTL_SECS && !cached.items.is_empty() {
|
||||||
let rec_count = cached.items.iter().filter(|i| i.is_coa_recommended).count();
|
return Ok(respond(cached.items, &overlay, cached.cached_at, false, cached.etag));
|
||||||
return Ok(PublicCatalogueResponse {
|
|
||||||
total_count: cached.items.len(),
|
|
||||||
recommended_count: rec_count,
|
|
||||||
cached_at: cached.cached_at,
|
|
||||||
is_offline: false,
|
|
||||||
etag: cached.etag,
|
|
||||||
items: cached.items,
|
|
||||||
});
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -507,15 +643,7 @@ pub fn fetch_or_load_catalogue(
|
|||||||
cached.timestamp = now_ts;
|
cached.timestamp = now_ts;
|
||||||
cached.cached_at = Utc::now().to_rfc3339();
|
cached.cached_at = Utc::now().to_rfc3339();
|
||||||
let _ = fsx::atomic_write_json(&cache_file, &cached);
|
let _ = fsx::atomic_write_json(&cache_file, &cached);
|
||||||
let rec_count = cached.items.iter().filter(|i| i.is_coa_recommended).count();
|
return Ok(respond(cached.items, &overlay, cached.cached_at, false, cached.etag));
|
||||||
return Ok(PublicCatalogueResponse {
|
|
||||||
total_count: cached.items.len(),
|
|
||||||
recommended_count: rec_count,
|
|
||||||
cached_at: cached.cached_at,
|
|
||||||
is_offline: false,
|
|
||||||
etag: cached.etag,
|
|
||||||
items: cached.items,
|
|
||||||
});
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -540,7 +668,6 @@ pub fn fetch_or_load_catalogue(
|
|||||||
})?;
|
})?;
|
||||||
|
|
||||||
let items = normalize_catalogue(&raw, &overlay);
|
let items = normalize_catalogue(&raw, &overlay);
|
||||||
let rec_count = items.iter().filter(|i| i.is_coa_recommended).count();
|
|
||||||
let now_str = Utc::now().to_rfc3339();
|
let now_str = Utc::now().to_rfc3339();
|
||||||
|
|
||||||
let cached_doc = CachedDocument {
|
let cached_doc = CachedDocument {
|
||||||
@@ -557,14 +684,7 @@ pub fn fetch_or_load_catalogue(
|
|||||||
let _ = fs::write(&etag_file, tag);
|
let _ = fs::write(&etag_file, tag);
|
||||||
}
|
}
|
||||||
|
|
||||||
return Ok(PublicCatalogueResponse {
|
return Ok(respond(items, &overlay, now_str, false, new_etag));
|
||||||
total_count: items.len(),
|
|
||||||
recommended_count: rec_count,
|
|
||||||
cached_at: now_str,
|
|
||||||
is_offline: false,
|
|
||||||
etag: new_etag,
|
|
||||||
items,
|
|
||||||
});
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// If non-200 and non-304 HTTP status, fallback to existing cache if available
|
// If non-200 and non-304 HTTP status, fallback to existing cache if available
|
||||||
@@ -585,15 +705,7 @@ fn try_offline_fallback(
|
|||||||
if cache_file.is_file() {
|
if cache_file.is_file() {
|
||||||
if let Ok(content) = fs::read_to_string(cache_file) {
|
if let Ok(content) = fs::read_to_string(cache_file) {
|
||||||
if let Ok(cached) = serde_json::from_str::<CachedDocument>(&content) {
|
if let Ok(cached) = serde_json::from_str::<CachedDocument>(&content) {
|
||||||
let rec_count = cached.items.iter().filter(|i| i.is_coa_recommended).count();
|
return Ok(respond(cached.items, overlay, cached.cached_at, true, cached.etag.or(stored_etag)));
|
||||||
return Ok(PublicCatalogueResponse {
|
|
||||||
total_count: cached.items.len(),
|
|
||||||
recommended_count: rec_count,
|
|
||||||
cached_at: cached.cached_at,
|
|
||||||
is_offline: true,
|
|
||||||
etag: cached.etag.or(stored_etag),
|
|
||||||
items: cached.items,
|
|
||||||
});
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -604,16 +716,7 @@ fn try_offline_fallback(
|
|||||||
organizations: BTreeMap::new(),
|
organizations: BTreeMap::new(),
|
||||||
};
|
};
|
||||||
let items = normalize_catalogue(&empty_raw, overlay);
|
let items = normalize_catalogue(&empty_raw, overlay);
|
||||||
let rec_count = items.iter().filter(|i| i.is_coa_recommended).count();
|
Ok(respond(items, overlay, Utc::now().to_rfc3339(), true, None))
|
||||||
|
|
||||||
Ok(PublicCatalogueResponse {
|
|
||||||
total_count: items.len(),
|
|
||||||
recommended_count: rec_count,
|
|
||||||
cached_at: Utc::now().to_rfc3339(),
|
|
||||||
is_offline: true,
|
|
||||||
etag: None,
|
|
||||||
items,
|
|
||||||
})
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// ---------------------------------------------------------------------------
|
// ---------------------------------------------------------------------------
|
||||||
@@ -808,6 +911,7 @@ mod tests {
|
|||||||
coa_status_source: "CacheTest".into(),
|
coa_status_source: "CacheTest".into(),
|
||||||
conflict_reason: None,
|
conflict_reason: None,
|
||||||
is_coa_recommended: false,
|
is_coa_recommended: false,
|
||||||
|
category: String::new(),
|
||||||
}
|
}
|
||||||
];
|
];
|
||||||
|
|
||||||
@@ -833,6 +937,56 @@ mod tests {
|
|||||||
let overlay = load_coa_overlay(None);
|
let overlay = load_coa_overlay(None);
|
||||||
let fallback_resp = try_offline_fallback(&cache_file, None, &overlay).expect("fallback must succeed");
|
let fallback_resp = try_offline_fallback(&cache_file, None, &overlay).expect("fallback must succeed");
|
||||||
assert!(fallback_resp.is_offline);
|
assert!(fallback_resp.is_offline);
|
||||||
assert!(!fallback_resp.items.is_empty(), "Fallback must supply overlay items even on corrupt cache");
|
// nothing is made up from overlay rules when there is no catalogue to show
|
||||||
|
assert!(fallback_resp.items.is_empty());
|
||||||
|
}
|
||||||
|
|
||||||
|
fn item(full_name: &str, name: &str, description: &str, topics: &[&str]) -> PublicCatalogueItem {
|
||||||
|
PublicCatalogueItem {
|
||||||
|
id: 1,
|
||||||
|
name: name.into(),
|
||||||
|
full_name: full_name.into(),
|
||||||
|
owner: full_name.split('/').next().unwrap().into(),
|
||||||
|
html_url: format!("https://github.com/{full_name}"),
|
||||||
|
description: description.into(),
|
||||||
|
stars: 0,
|
||||||
|
forks: 0,
|
||||||
|
default_branch: "master".into(),
|
||||||
|
pushed_at: None,
|
||||||
|
updated_at: None,
|
||||||
|
license: None,
|
||||||
|
topics: topics.iter().map(|t| t.to_string()).collect(),
|
||||||
|
coa_status: CoaCompatibilityStatus::Verified,
|
||||||
|
coa_status_source: "Overlay".into(),
|
||||||
|
conflict_reason: Some("stale".into()),
|
||||||
|
is_coa_recommended: true,
|
||||||
|
category: String::new(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn statuses_come_from_the_current_overlay_not_the_cache_and_made_up_entries_are_dropped() {
|
||||||
|
let overlay = load_coa_overlay(None);
|
||||||
|
let cached = vec![
|
||||||
|
item("azerothcore/mod-duel-reset", "mod-duel-reset", "Duel reset module", &["azerothcore-module"]),
|
||||||
|
item("azerothcore/mod-cfbg", "mod-cfbg", "Cross-faction battlegrounds", &["azerothcore-module", "coa-verified"]),
|
||||||
|
];
|
||||||
|
let out = finalize(cached, &overlay);
|
||||||
|
assert_eq!(out.len(), 1, "the made-up mod-cfbg entry is dropped");
|
||||||
|
assert_eq!(out[0].coa_status, CoaCompatibilityStatus::Unverified);
|
||||||
|
assert!(out[0].conflict_reason.is_none() && !out[0].is_coa_recommended);
|
||||||
|
assert_eq!(out[0].category, "pvp");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn modules_get_a_category_from_the_reviewed_list_or_keywords() {
|
||||||
|
// reviewed list (the owner's file)
|
||||||
|
assert_eq!(categorize("DustinHendrickson/mod-ollama-chat", "mod-ollama-chat", "", &[]), "bots");
|
||||||
|
// keywords: whole words, not parts of other words
|
||||||
|
assert_eq!(categorize("x/mod-arena-points", "mod-arena-points", "Gives arena points", &[]), "pvp");
|
||||||
|
assert_eq!(categorize("x/mod-guild-chat", "mod-guild-chat", "", &[]), "social");
|
||||||
|
assert_eq!(categorize("x/mod-maintain", "mod-maintain", "Maintains things", &[]), "other");
|
||||||
|
assert_eq!(categorize("x/mod-nothing", "mod-nothing", "", &["azerothcore-module".to_string(), "wotlk".to_string()]), "other");
|
||||||
|
assert!(categories().iter().any(|c| c.code == "other"));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,473 @@
|
|||||||
|
{
|
||||||
|
"version": 1,
|
||||||
|
"source": "azerothcore_catalogue_categorized_2026-11-07.xlsx (owner), modules with high or medium confidence",
|
||||||
|
"categories": [
|
||||||
|
{
|
||||||
|
"code": "bots",
|
||||||
|
"ru": "Боты и искусственный интеллект",
|
||||||
|
"en": "Bots and AI",
|
||||||
|
"keywords": [
|
||||||
|
"playerbots",
|
||||||
|
"bots",
|
||||||
|
"npcbot",
|
||||||
|
"llm",
|
||||||
|
"ollama",
|
||||||
|
"ai",
|
||||||
|
"автономные спутники"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"code": "pve",
|
||||||
|
"ru": "PvE, подземелья и рейды",
|
||||||
|
"en": "PvE, dungeons and raids",
|
||||||
|
"keywords": [
|
||||||
|
"pve",
|
||||||
|
"dungeon",
|
||||||
|
"raid",
|
||||||
|
"boss",
|
||||||
|
"mythic+",
|
||||||
|
"scaling",
|
||||||
|
"rdf",
|
||||||
|
"инстансы"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"code": "pvp",
|
||||||
|
"ru": "PvP, арены и поля боя",
|
||||||
|
"en": "PvP, arenas and battlegrounds",
|
||||||
|
"keywords": [
|
||||||
|
"pvp",
|
||||||
|
"arena",
|
||||||
|
"battleground",
|
||||||
|
"bg",
|
||||||
|
"duel",
|
||||||
|
"ffa",
|
||||||
|
"фракции"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"code": "hardcore",
|
||||||
|
"ru": "Hardcore и режимы сложности",
|
||||||
|
"en": "Hardcore and difficulty",
|
||||||
|
"keywords": [
|
||||||
|
"hardcore",
|
||||||
|
"ironman",
|
||||||
|
"permadeath",
|
||||||
|
"high risk",
|
||||||
|
"difficulty"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"code": "progression",
|
||||||
|
"ru": "Прокачка и прогрессия",
|
||||||
|
"en": "Leveling and progression",
|
||||||
|
"keywords": [
|
||||||
|
"xp",
|
||||||
|
"level",
|
||||||
|
"rates",
|
||||||
|
"leveling",
|
||||||
|
"rewards",
|
||||||
|
"prestige",
|
||||||
|
"progression",
|
||||||
|
"experience",
|
||||||
|
"reputation",
|
||||||
|
"rested"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"code": "classes",
|
||||||
|
"ru": "Классы, расы и способности",
|
||||||
|
"en": "Classes, races and abilities",
|
||||||
|
"keywords": [
|
||||||
|
"race",
|
||||||
|
"class",
|
||||||
|
"talent",
|
||||||
|
"spells",
|
||||||
|
"specialization",
|
||||||
|
"pets"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"code": "cosmetics",
|
||||||
|
"ru": "Косметика и трансмог",
|
||||||
|
"en": "Cosmetics and transmog",
|
||||||
|
"keywords": [
|
||||||
|
"transmog",
|
||||||
|
"appearance",
|
||||||
|
"morph",
|
||||||
|
"visual",
|
||||||
|
"vanity",
|
||||||
|
"cosmetics"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"code": "items",
|
||||||
|
"ru": "Лут, предметы и экипировка",
|
||||||
|
"en": "Loot, items and gear",
|
||||||
|
"keywords": [
|
||||||
|
"loot",
|
||||||
|
"item",
|
||||||
|
"gear",
|
||||||
|
"enchant",
|
||||||
|
"reforging",
|
||||||
|
"bank",
|
||||||
|
"inventory",
|
||||||
|
"items",
|
||||||
|
"reagent"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"code": "economy",
|
||||||
|
"ru": "Торговля, экономика и профессии",
|
||||||
|
"en": "Trade, economy and professions",
|
||||||
|
"keywords": [
|
||||||
|
"auction",
|
||||||
|
"market",
|
||||||
|
"vendor",
|
||||||
|
"trade",
|
||||||
|
"gold",
|
||||||
|
"shop",
|
||||||
|
"profession",
|
||||||
|
"ahbot",
|
||||||
|
"auction house",
|
||||||
|
"gather",
|
||||||
|
"herbs",
|
||||||
|
"mining",
|
||||||
|
"fishing",
|
||||||
|
"crafting"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"code": "account",
|
||||||
|
"ru": "Аккаунты и персонажи",
|
||||||
|
"en": "Accounts and characters",
|
||||||
|
"keywords": [
|
||||||
|
"account",
|
||||||
|
"character",
|
||||||
|
"mounts",
|
||||||
|
"collection",
|
||||||
|
"migration",
|
||||||
|
"recruit",
|
||||||
|
"login",
|
||||||
|
"alts"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"code": "social",
|
||||||
|
"ru": "Гильдии, чат и социальные",
|
||||||
|
"en": "Guilds, chat and social",
|
||||||
|
"keywords": [
|
||||||
|
"guild",
|
||||||
|
"chat",
|
||||||
|
"messages",
|
||||||
|
"announcements",
|
||||||
|
"friends",
|
||||||
|
"mail"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"code": "npc",
|
||||||
|
"ru": "NPC и игровые сервисы",
|
||||||
|
"en": "NPCs and services",
|
||||||
|
"keywords": [
|
||||||
|
"npc",
|
||||||
|
"buffer",
|
||||||
|
"trainer",
|
||||||
|
"enchanter",
|
||||||
|
"services",
|
||||||
|
"assistant",
|
||||||
|
"vendor npc",
|
||||||
|
"gossip"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"code": "world",
|
||||||
|
"ru": "Мир, зоны и перемещение",
|
||||||
|
"en": "World, zones and travel",
|
||||||
|
"keywords": [
|
||||||
|
"world",
|
||||||
|
"zone",
|
||||||
|
"spawn",
|
||||||
|
"teleport",
|
||||||
|
"portal",
|
||||||
|
"travel",
|
||||||
|
"respawn"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"code": "events",
|
||||||
|
"ru": "События и мини-игры",
|
||||||
|
"en": "Events and mini-games",
|
||||||
|
"keywords": [
|
||||||
|
"events",
|
||||||
|
"holidays",
|
||||||
|
"quests",
|
||||||
|
"trivia",
|
||||||
|
"minigames",
|
||||||
|
"treasure"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"code": "server",
|
||||||
|
"ru": "Сервер, хостинг и автоматизация",
|
||||||
|
"en": "Server and automation",
|
||||||
|
"keywords": [
|
||||||
|
"server",
|
||||||
|
"deployment",
|
||||||
|
"backup",
|
||||||
|
"cache",
|
||||||
|
"relay",
|
||||||
|
"restart",
|
||||||
|
"monitoring"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"code": "admin",
|
||||||
|
"ru": "Администрирование и безопасность",
|
||||||
|
"en": "Administration and security",
|
||||||
|
"keywords": [
|
||||||
|
"gm",
|
||||||
|
"admin",
|
||||||
|
"moderation",
|
||||||
|
"logs",
|
||||||
|
"security",
|
||||||
|
"bans",
|
||||||
|
"abuse"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"code": "web",
|
||||||
|
"ru": "Сайты, API и интеграции",
|
||||||
|
"en": "Websites, API and integrations",
|
||||||
|
"keywords": [
|
||||||
|
"api",
|
||||||
|
"cms",
|
||||||
|
"website",
|
||||||
|
"discord",
|
||||||
|
"telegram",
|
||||||
|
"web",
|
||||||
|
"metrics"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"code": "dev",
|
||||||
|
"ru": "Разработка, SQL и инструменты",
|
||||||
|
"en": "Development, SQL and tools",
|
||||||
|
"keywords": [
|
||||||
|
"editor",
|
||||||
|
"db",
|
||||||
|
"sql",
|
||||||
|
"lua",
|
||||||
|
"eluna",
|
||||||
|
"ide",
|
||||||
|
"tooling",
|
||||||
|
"sdk"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"code": "client",
|
||||||
|
"ru": "Клиент, патчи и интерфейс",
|
||||||
|
"en": "Client, patches and UI",
|
||||||
|
"keywords": [
|
||||||
|
"client",
|
||||||
|
"patch",
|
||||||
|
"addon",
|
||||||
|
"ui",
|
||||||
|
"launcher",
|
||||||
|
"controller",
|
||||||
|
"mpq"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"code": "other",
|
||||||
|
"ru": "Прочее",
|
||||||
|
"en": "Other",
|
||||||
|
"keywords": [
|
||||||
|
|
||||||
|
]
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"repos": {
|
||||||
|
"liyunfan1223/mod-playerbots": "bots",
|
||||||
|
"dustinhendrickson/mod-ollama-chat": "bots",
|
||||||
|
"dustinhendrickson/mod-player-bot-level-brackets": "bots",
|
||||||
|
"dustinhendrickson/mod-ollama-bot-buddy": "bots",
|
||||||
|
"azerothcore/mod-autobalance": "pve",
|
||||||
|
"zhengpeiru21/mod-challenge-modes": "pve",
|
||||||
|
"anchydev/dungeonrespawn": "pve",
|
||||||
|
"azerothcore/mod-rdf-expansion": "pve",
|
||||||
|
"silviu20092/mod-mythic-plus": "pve",
|
||||||
|
"avarishd/mod-brawlers-guild": "pve",
|
||||||
|
"sogladev/mod-vanilla-naxxramas": "pve",
|
||||||
|
"pangolp/mod-cfpve": "pve",
|
||||||
|
"bewarellamas/mod-dungeonmaster": "pve",
|
||||||
|
"araxiaonline/mod-mythic-plus": "pve",
|
||||||
|
"sogladev/mod-reset-raid-cooldowns": "pve",
|
||||||
|
"hallgaeuer/mod-quickbalance": "pve",
|
||||||
|
"valsan-azerty-boi/mod-ony-naxx-logout-teleport": "pve",
|
||||||
|
"stealthyape/raidteleporter": "pve",
|
||||||
|
"zesman21/mod-nordf": "pve",
|
||||||
|
"helias/mod-bg-slaveryvalley": "pvp",
|
||||||
|
"azerothcore/mod-duel-reset": "pvp",
|
||||||
|
"gitdalisar/mod-faction-free": "pvp",
|
||||||
|
"azerothcore/mod-pvp-titles": "pvp",
|
||||||
|
"helias/mod-bg-twinpeaks": "pvp",
|
||||||
|
"helias/mod-bg-battle-for-gilneas": "pvp",
|
||||||
|
"talamortis/mod-pvpscript": "pvp",
|
||||||
|
"gozzim/mod-npc-spectator": "pvp",
|
||||||
|
"azerothcore/mod-bg-reward": "pvp",
|
||||||
|
"helias/mod-arena-tigerspeak": "pvp",
|
||||||
|
"helias/mod-arena-tolviron": "pvp",
|
||||||
|
"tbcstar/mod-high-risk-system": "pvp",
|
||||||
|
"azerothcore/mod-pvp-zones": "pvp",
|
||||||
|
"azerothcore/mod-bg-item-reward": "pvp",
|
||||||
|
"azerothcore/mod-desertion-warnings": "pvp",
|
||||||
|
"azerothcore/mod-low-level-rbg": "pvp",
|
||||||
|
"youpeoples/ultimate-full-loot-pvp": "pvp",
|
||||||
|
"azerothcore/mod-pvpstats-announcer": "pvp",
|
||||||
|
"anchydev/ffafix": "pvp",
|
||||||
|
"azerothcore/mod-low-level-arena": "pvp",
|
||||||
|
"trembon/mod-peacekeeper": "pvp",
|
||||||
|
"anchydev/bgqueuechecker": "pvp",
|
||||||
|
"anchydev/hardmode": "hardcore",
|
||||||
|
"kjack9/mod-dead-means-dead": "hardcore",
|
||||||
|
"conan1996-2/mod-hard-modes": "hardcore",
|
||||||
|
"jorge990125/mod-hardcore-makgora": "hardcore",
|
||||||
|
"stuntmonkey4u/mod-trial-of-finality": "hardcore",
|
||||||
|
"zindokar/mod-hardcore": "hardcore",
|
||||||
|
"zhengpeiru21/mod-individual-progression": "progression",
|
||||||
|
"azerothcore/mod-congrats-on-level": "progression",
|
||||||
|
"noisiver/mod-weekendbonus": "progression",
|
||||||
|
"youpeoples/prestige-and-draft-mode": "progression",
|
||||||
|
"anchydev/attriboost": "progression",
|
||||||
|
"azerothcore/mod-fireworks-on-level": "progression",
|
||||||
|
"anchydev/extendedxp": "progression",
|
||||||
|
"anchydev/prestigious": "progression",
|
||||||
|
"noisiver/mod-appreciation": "progression",
|
||||||
|
"betayi/mod_spec_reward": "progression",
|
||||||
|
"brian8544/setxpbar": "progression",
|
||||||
|
"nhobodyimportant/prestige": "progression",
|
||||||
|
"azerothcore/mod-alpha-rewards": "progression",
|
||||||
|
"michaeldelago/mod-quest-count-level": "progression",
|
||||||
|
"regrad/update-mob-level-to-player-and-random-item-stats": "progression",
|
||||||
|
"azerothcore/mod-chromie-xp": "progression",
|
||||||
|
"kadan-gx/mod-login-rewards": "progression",
|
||||||
|
"talamortis/mod-individual-xp": "progression",
|
||||||
|
"talamortis/reward-system": "progression",
|
||||||
|
"brian8544/mod-setxpbar": "progression",
|
||||||
|
"fischerlol/mod-level-15-boost": "progression",
|
||||||
|
"notepadguyofficial/mod-level-rewards": "progression",
|
||||||
|
"thearktect/mod-weekend-xp": "progression",
|
||||||
|
"heyitsbench/mod-arac": "classes",
|
||||||
|
"heyitsbench/mod-worgoblin": "classes",
|
||||||
|
"azerothcore/mod-npc-beastmaster": "classes",
|
||||||
|
"zhengpeiru21/mod-leech": "classes",
|
||||||
|
"azerothcore/mod-racial-trait-swap": "classes",
|
||||||
|
"noisiver/mod-learnspells": "classes",
|
||||||
|
"silviu20092/mod-warlock-pet-rename": "classes",
|
||||||
|
"vhiperdev/mod-spellregulator": "classes",
|
||||||
|
"xiii-hearts/mod-npc-subclass": "classes",
|
||||||
|
"gozzim/mod-starting-pet": "classes",
|
||||||
|
"bewarellamas/mod-profspecs": "classes",
|
||||||
|
"sogladev/mod-demonic-pact-classic": "classes",
|
||||||
|
"brian8544/mod-talentbutton": "classes",
|
||||||
|
"lenzork/mod-petequip": "classes",
|
||||||
|
"azerothcore/mod-transmog": "cosmetics",
|
||||||
|
"azerothcore/mod-weapon-visual": "cosmetics",
|
||||||
|
"azerothcore/mod-morphsummon": "cosmetics",
|
||||||
|
"azerothcore/mod-costumes": "cosmetics",
|
||||||
|
"azerothcore/mod-npc-morph": "cosmetics",
|
||||||
|
"azerothcore/mod-aoe-loot": "items",
|
||||||
|
"azerothcore/mod-npc-enchanter": "items",
|
||||||
|
"anchydev/statbooster": "items",
|
||||||
|
"zhengpeiru21/mod-reagent-bank": "items",
|
||||||
|
"silviu20092/mod-item-upgrade": "items",
|
||||||
|
"silviu20092/mod-reforging": "items",
|
||||||
|
"terrabyte-tbwps/mod-aoe-loot": "items",
|
||||||
|
"silviu20092/mod-improved-bank": "items",
|
||||||
|
"pangolp/mod-quest-loot-party": "items",
|
||||||
|
"anchydev/recycleditems": "items",
|
||||||
|
"anchydev/statboosterreroller": "items",
|
||||||
|
"hallgaeuer/mod-dynamic-loot-rates": "items",
|
||||||
|
"seaferer/aoe-loot---merge": "items",
|
||||||
|
"protonull/mod-starter-wands": "items",
|
||||||
|
"talamortis/mod-itemlevel": "items",
|
||||||
|
"noisiver/mod-junk-to-gold": "economy",
|
||||||
|
"youpeoples/black-market-auction-house": "economy",
|
||||||
|
"wowhellgarve-holydeew/mod-multi-vendor": "economy",
|
||||||
|
"azerothcore/mod-money-for-kills": "economy",
|
||||||
|
"azerothcore/mod-npc-gambler": "economy",
|
||||||
|
"elmsroth/mod-trade-items-filter": "economy",
|
||||||
|
"talamortis/mod_reward_shop": "economy",
|
||||||
|
"silviu20092/mod-sell-items": "economy",
|
||||||
|
"tereneckla/mod-profession-experience": "economy",
|
||||||
|
"jorge990125/mod-black-market": "economy",
|
||||||
|
"heyitsbench/mod-ptr-template": "account",
|
||||||
|
"pangolp/mod-recruit-friend": "account",
|
||||||
|
"azerothcore/mod-npc-all-mounts": "account",
|
||||||
|
"gozzim/mod-firstlogin-aio": "account",
|
||||||
|
"talamortis/mod-premium": "account",
|
||||||
|
"zerkenn/mod-character-services": "account",
|
||||||
|
"lucafolloni/mod-account-vanity-pets": "account",
|
||||||
|
"noisiver/mod-accountbound": "account",
|
||||||
|
"pangolp/mod-mounts-on-account": "account",
|
||||||
|
"microbica/mod-share-mounts": "account",
|
||||||
|
"gozzim/mod-globalchat": "social",
|
||||||
|
"azerothcore/mod-guild-zone-system": "social",
|
||||||
|
"azerothcore/mod-starter-guild": "social",
|
||||||
|
"anchydev/itembroadcastguildchat": "social",
|
||||||
|
"azerothcore/mod-chat-transmitter": "social",
|
||||||
|
"azerothcore/mod-global-chat": "social",
|
||||||
|
"noisiver/mod-guildfunds": "social",
|
||||||
|
"jorge990125/mod-streams": "social",
|
||||||
|
"noisiver/mod-assistant": "npc",
|
||||||
|
"azerothcore/mod-npc-services": "npc",
|
||||||
|
"azerothcore/mod-npc-buffer": "npc",
|
||||||
|
"pangolp/mod-npc-promotion": "npc",
|
||||||
|
"azerothcore/mod-npc-codebox": "npc",
|
||||||
|
"azerothcore/mod-buff-command": "npc",
|
||||||
|
"jorge990125/mod-bienvenida": "npc",
|
||||||
|
"dunjeon/mod-timeistime": "world",
|
||||||
|
"bytesgalore/mod-no-hearthstone-cooldown": "world",
|
||||||
|
"justin-kaufmann/mod-changeablespawnrates": "world",
|
||||||
|
"hallgaeuer/mod-quick-respawn": "world",
|
||||||
|
"justin-kaufmann/mod-noclip": "world",
|
||||||
|
"eldoba/mod-dynamic-resurrections-": "world",
|
||||||
|
"elmegaard/mod-auto-resurrect": "world",
|
||||||
|
"noisiver/mod-spawnpoints": "world",
|
||||||
|
"tralenor/mod-objscale": "world",
|
||||||
|
"silviu20092/mod-flightmaster-whistle": "world",
|
||||||
|
"sogladev/mod-ghost-speed": "world",
|
||||||
|
"talamortis/playerteleport": "world",
|
||||||
|
"vhiperdev/mod-no-farming": "world",
|
||||||
|
"noisiver/mod-activatezones": "world",
|
||||||
|
"zyggy123/treasure-chest-system": "events",
|
||||||
|
"azerothcore/mod-tic-tac-toe": "events",
|
||||||
|
"pangolp/mod-quest-status": "events",
|
||||||
|
"azerothcore/mod-war-effort": "events",
|
||||||
|
"youpeoples/quizmaster": "events",
|
||||||
|
"azerothcore/mod-cta-switch": "events",
|
||||||
|
"azerothcore/mod-dmf-switch": "events",
|
||||||
|
"azerothcore/mod-server-auto-shutdown": "server",
|
||||||
|
"anchydev/recache": "server",
|
||||||
|
"azerothcore/mod-queue-list-cache": "server",
|
||||||
|
"maluramichael/mod-influxdb": "server",
|
||||||
|
"sogladev/mod-increment-cache-version": "server",
|
||||||
|
"anchydev/aci": "server",
|
||||||
|
"azerothcore/mod-ip-tracker": "admin",
|
||||||
|
"tralenor/mod-gomove": "admin",
|
||||||
|
"talamortis/mod-whologged": "admin",
|
||||||
|
"talamortis/mod_character_tools": "admin",
|
||||||
|
"azerothcore/mod-notify-muted": "admin",
|
||||||
|
"mellianstudios/mod-encounter-logs": "admin",
|
||||||
|
"miithrandiir/mod_sponsorship": "web",
|
||||||
|
"exitare/mod-discord-webhook": "web",
|
||||||
|
"abutbul/mod-game-state-api": "web",
|
||||||
|
"thearktect/mod-discord-announce": "web",
|
||||||
|
"azerothcore/skeleton-module": "dev",
|
||||||
|
"azerothcore/eluna-ts": "dev",
|
||||||
|
"azerothcore/mod-premium-lib": "dev",
|
||||||
|
"anchydev/breakingnewsoverride": "client",
|
||||||
|
"gitdalisar/addon-faction-free-unit-popup": "client"
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -58,33 +58,27 @@
|
|||||||
},
|
},
|
||||||
{
|
{
|
||||||
"repo_slug": "azerothcore/mod-cfbg",
|
"repo_slug": "azerothcore/mod-cfbg",
|
||||||
"status": "Verified",
|
"status": "Incompatible",
|
||||||
"is_recommended": false,
|
"is_recommended": false,
|
||||||
"reason": "Cross-faction battlegrounds system. Built into CoA core fork."
|
"reason": "Already built into the CoA core (cross-faction battlegrounds); a separate DLL would load it a second time."
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
"repo_slug": "azerothcore/mod-duel-reset",
|
"repo_slug": "helias/mod-bg-battle-for-gilneas",
|
||||||
"status": "Verified",
|
"status": "Incompatible",
|
||||||
"is_recommended": false,
|
"is_recommended": false,
|
||||||
"reason": "Resets health, mana, cooldowns and auras after duels. Verified dynamic DLL."
|
"reason": "Needs the server's DBC files replaced (including Spell.dbc, which CoA ships its own of), a client patch and a modified wow.exe; written for AzerothCore 2019."
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
"repo_slug": "azerothcore/mod-pvp-titles",
|
"repo_slug": "helias/mod-bg-twinpeaks",
|
||||||
"status": "Verified",
|
"status": "Incompatible",
|
||||||
"is_recommended": false,
|
"is_recommended": false,
|
||||||
"reason": "Classic PvP rank titles awarded based on honorable kills."
|
"reason": "Needs the server's DBC files replaced (CoA ships its own), a client patch and a modified wow.exe."
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
"repo_slug": "azerothcore/mod-starter-guild",
|
"repo_slug": "helias/mod-bg-slaveryvalley",
|
||||||
"status": "Verified",
|
"status": "Incompatible",
|
||||||
"is_recommended": false,
|
"is_recommended": false,
|
||||||
"reason": "Automatically invites newly created characters into a designated starter guild."
|
"reason": "Needs the server's DBC files replaced (CoA ships its own) and a client patch."
|
||||||
},
|
|
||||||
{
|
|
||||||
"repo_slug": "azerothcore/mod-skip-dk-starting-area",
|
|
||||||
"status": "Verified",
|
|
||||||
"is_recommended": false,
|
|
||||||
"reason": "Allows Death Knights to skip the Scarlet Enclave starter zone."
|
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
"repo_slug": "azerothcore/mod-learn-spells",
|
"repo_slug": "azerothcore/mod-learn-spells",
|
||||||
|
|||||||
@@ -3,13 +3,10 @@
|
|||||||
//! small set (one per CoA class); older or imported servers can have it added on request.
|
//! small set (one per CoA class); older or imported servers can have it added on request.
|
||||||
|
|
||||||
use std::fs;
|
use std::fs;
|
||||||
use std::path::{Path, PathBuf};
|
use std::path::Path;
|
||||||
|
|
||||||
use serde::{Deserialize, Serialize};
|
|
||||||
|
|
||||||
use crate::db::Db;
|
use crate::db::Db;
|
||||||
use crate::error::Result;
|
use crate::error::Result;
|
||||||
use crate::fsx;
|
|
||||||
|
|
||||||
/// Owner of the template characters. Not account 1 (the bot module skips it) and not a bot-host account; no such
|
/// Owner of the template characters. Not account 1 (the bot module skips it) and not a bot-host account; no such
|
||||||
/// account exists in the login database, so nobody can ever log in to these characters.
|
/// account exists in the login database, so nobody can ever log in to these characters.
|
||||||
@@ -22,46 +19,37 @@ pub fn seed_sql(base_guid: &str) -> String {
|
|||||||
format!("SET @G = {base_guid}; SET @ACC = {TEMPLATE_ACCOUNT};\n{SQL}")
|
format!("SET @G = {base_guid}; SET @ACC = {TEMPLATE_ACCOUNT};\n{SQL}")
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Number of characters the bot module could use as templates.
|
/// Number of characters the bot module could use as templates (level 80, a CoA class, not account 1).
|
||||||
pub fn template_count(db: &Db) -> Result<u32> {
|
pub fn template_count(db: &Db) -> Result<u32> {
|
||||||
template_count_for_schema(db, "acore_characters")
|
let n = db.query("SELECT COUNT(*) FROM acore_characters.characters WHERE account<>1 AND level>=80 AND class BETWEEN 12 AND 32;")?;
|
||||||
}
|
|
||||||
|
|
||||||
pub fn template_count_for_schema(db: &Db, chars_db: &str) -> Result<u32> {
|
|
||||||
let n = db.query(&format!("SELECT COUNT(*) FROM {chars_db}.characters WHERE account<>1 AND level>=80;"))?;
|
|
||||||
Ok(n.trim().parse().unwrap_or(0))
|
Ok(n.trim().parse().unwrap_or(0))
|
||||||
}
|
}
|
||||||
|
|
||||||
fn run_seed(db: &Db, chars_db: &str, base_guid: &str) -> Result<()> {
|
fn run_seed(db: &Db, base_guid: &str) -> Result<()> {
|
||||||
let file = std::env::temp_dir().join(format!(
|
let file = std::env::temp_dir().join(format!(
|
||||||
"coa-companion-templates-{}.sql",
|
"coa-companion-templates-{}.sql",
|
||||||
std::process::id()
|
std::process::id()
|
||||||
));
|
));
|
||||||
fs::write(&file, seed_sql(base_guid))?;
|
fs::write(&file, seed_sql(base_guid))?;
|
||||||
let r = db.run_sql_file(chars_db, &file);
|
let r = db.run_sql_file("acore_characters", &file);
|
||||||
let _ = fs::remove_file(&file);
|
let _ = fs::remove_file(&file);
|
||||||
r
|
r
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Fresh databases (release tooling): the original guids.
|
/// Fresh databases (release tooling): the original guids.
|
||||||
pub fn seed_fresh(db: &Db) -> Result<()> {
|
pub fn seed_fresh(db: &Db) -> Result<()> {
|
||||||
run_seed(db, "acore_characters", "0")
|
run_seed(db, "0")
|
||||||
}
|
}
|
||||||
|
|
||||||
/// An existing server without templates: add them far above the highest guid in use, so a running world can never
|
/// An existing server without templates: add them far above the highest guid in use, so a running world can never
|
||||||
/// hand a new character one of their guids. Returns whether anything was added.
|
/// hand a new character one of their guids. Returns whether anything was added.
|
||||||
pub fn ensure_templates(db: &Db) -> Result<bool> {
|
pub fn ensure_templates(db: &Db) -> Result<bool> {
|
||||||
ensure_templates_for_schema(db, "acore_characters")
|
if template_count(db)? > 0 {
|
||||||
}
|
|
||||||
|
|
||||||
pub fn ensure_templates_for_schema(db: &Db, chars_db: &str) -> Result<bool> {
|
|
||||||
if template_count_for_schema(db, chars_db)? > 0 {
|
|
||||||
return Ok(false);
|
return Ok(false);
|
||||||
}
|
}
|
||||||
run_seed(
|
run_seed(
|
||||||
db,
|
db,
|
||||||
chars_db,
|
"(SELECT IFNULL(MAX(guid),0) FROM acore_characters.characters) + 100000",
|
||||||
&format!("(SELECT IFNULL(MAX(guid),0) FROM {chars_db}.characters) + 100000"),
|
|
||||||
)?;
|
)?;
|
||||||
Ok(true)
|
Ok(true)
|
||||||
}
|
}
|
||||||
@@ -137,168 +125,6 @@ pub fn offline_create(root: &Path, log: &Path, count: u32) -> Result<String> {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Real runtime wildcard archetype metadata directly from coa_build_creator.
|
|
||||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
|
||||||
pub struct WildcardArchetypeDto {
|
|
||||||
pub id: String,
|
|
||||||
pub name: String,
|
|
||||||
pub roles: u32,
|
|
||||||
pub primary_stat: u32,
|
|
||||||
pub author: String,
|
|
||||||
pub difficulty: u32,
|
|
||||||
pub category: u32,
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Query coa_build_creator in the target characters DB for curated and player-authored archetypes.
|
|
||||||
pub fn list_wildcard_archetypes(db: &Db, chars_db: &str) -> Result<Vec<WildcardArchetypeDto>> {
|
|
||||||
let sql = format!(
|
|
||||||
"SELECT id, name, roles, primary_stat, author, difficulty, category \
|
|
||||||
FROM {chars_db}.coa_build_creator \
|
|
||||||
WHERE needs_repairs = 0 \
|
|
||||||
ORDER BY upvotes DESC, name ASC \
|
|
||||||
LIMIT 100;"
|
|
||||||
);
|
|
||||||
|
|
||||||
let mut archetypes = Vec::new();
|
|
||||||
if let Ok(out) = db.query(&sql) {
|
|
||||||
for line in out.lines() {
|
|
||||||
let parts: Vec<&str> = line.split('\t').collect();
|
|
||||||
if parts.len() >= 7 {
|
|
||||||
archetypes.push(WildcardArchetypeDto {
|
|
||||||
id: parts[0].trim().to_string(),
|
|
||||||
name: parts[1].trim().to_string(),
|
|
||||||
roles: parts[2].trim().parse().unwrap_or(8),
|
|
||||||
primary_stat: parts[3].trim().parse().unwrap_or(0),
|
|
||||||
author: parts[4].trim().to_string(),
|
|
||||||
difficulty: parts[5].trim().parse().unwrap_or(0),
|
|
||||||
category: parts[6].trim().parse().unwrap_or(0),
|
|
||||||
});
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Curated fallback if DB query returned zero rows (e.g. initial setup)
|
|
||||||
if archetypes.is_empty() {
|
|
||||||
archetypes = vec![
|
|
||||||
WildcardArchetypeDto {
|
|
||||||
id: "b9bc2e11-cd62-4d37-b05a-fff2a2ada475".into(),
|
|
||||||
name: "Kinyaz Druid Tank Bear".into(),
|
|
||||||
roles: 2,
|
|
||||||
primary_stat: 0, // Strength
|
|
||||||
author: "Official".into(),
|
|
||||||
difficulty: 1,
|
|
||||||
category: 1,
|
|
||||||
},
|
|
||||||
WildcardArchetypeDto {
|
|
||||||
id: "c556625e-b5f1-40a9-b545-2bcaef883350".into(),
|
|
||||||
name: "Holy Paladin".into(),
|
|
||||||
roles: 4,
|
|
||||||
primary_stat: 3, // Intellect
|
|
||||||
author: "Official".into(),
|
|
||||||
difficulty: 1,
|
|
||||||
category: 1,
|
|
||||||
},
|
|
||||||
WildcardArchetypeDto {
|
|
||||||
id: "05add9af-94ee-4094-b091-f9afcb79c102".into(),
|
|
||||||
name: "Idum's Fire Sage".into(),
|
|
||||||
roles: 4,
|
|
||||||
primary_stat: 4, // Spirit
|
|
||||||
author: "Idum".into(),
|
|
||||||
difficulty: 2,
|
|
||||||
category: 1,
|
|
||||||
},
|
|
||||||
WildcardArchetypeDto {
|
|
||||||
id: "aaf370e5-fa02-4a02-abee-01cc4058aace".into(),
|
|
||||||
name: "Idum's Forest Warden".into(),
|
|
||||||
roles: 4,
|
|
||||||
primary_stat: 4, // Spirit
|
|
||||||
author: "Idum".into(),
|
|
||||||
difficulty: 2,
|
|
||||||
category: 1,
|
|
||||||
},
|
|
||||||
WildcardArchetypeDto {
|
|
||||||
id: "20f08cc1-b2c4-47ca-b5b1-d5cbcbd3d2f8".into(),
|
|
||||||
name: "Blood DK DPS".into(),
|
|
||||||
roles: 8,
|
|
||||||
primary_stat: 0, // Strength
|
|
||||||
author: "Official".into(),
|
|
||||||
difficulty: 1,
|
|
||||||
category: 1,
|
|
||||||
},
|
|
||||||
WildcardArchetypeDto {
|
|
||||||
id: "8f1df486-d97f-4424-9b2f-8a032d88bbd6".into(),
|
|
||||||
name: "Bleed Berserker".into(),
|
|
||||||
roles: 8,
|
|
||||||
primary_stat: 1, // Agility
|
|
||||||
author: "Official".into(),
|
|
||||||
difficulty: 2,
|
|
||||||
category: 1,
|
|
||||||
},
|
|
||||||
WildcardArchetypeDto {
|
|
||||||
id: "45fbe2e6-231a-4a25-827a-8d7b3da4501a".into(),
|
|
||||||
name: "Mur-Lock".into(),
|
|
||||||
roles: 8,
|
|
||||||
primary_stat: 3, // Intellect
|
|
||||||
author: "Official".into(),
|
|
||||||
difficulty: 2,
|
|
||||||
category: 1,
|
|
||||||
},
|
|
||||||
];
|
|
||||||
}
|
|
||||||
|
|
||||||
Ok(archetypes)
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Realm-aware pending companion deployment job.
|
|
||||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
|
||||||
pub struct CompanionsPendingJob {
|
|
||||||
pub job_id: String,
|
|
||||||
pub server_instance_id: String,
|
|
||||||
pub realm: String,
|
|
||||||
pub count: u32,
|
|
||||||
pub level: Option<u8>,
|
|
||||||
pub class_id: Option<u8>,
|
|
||||||
pub spec_id: Option<u32>,
|
|
||||||
pub build_id: Option<String>,
|
|
||||||
pub requested_operation: String,
|
|
||||||
pub created_at: u64,
|
|
||||||
pub state: String, // "pending", "in_progress", "completed", "failed"
|
|
||||||
pub completed_count: u32,
|
|
||||||
pub failed_count: u32,
|
|
||||||
pub last_error: Option<String>,
|
|
||||||
pub schema_version: u32,
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn pending_job_path(meta_dir: &Path, realm: &str) -> PathBuf {
|
|
||||||
meta_dir.join(format!("companions.pending.{realm}.json"))
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn save_pending_job(meta_dir: &Path, realm: &str, job: &CompanionsPendingJob) -> Result<()> {
|
|
||||||
fsx::atomic_write_json(&pending_job_path(meta_dir, realm), job)
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn load_pending_job(meta_dir: &Path, realm: &str) -> Result<Option<CompanionsPendingJob>> {
|
|
||||||
let p = pending_job_path(meta_dir, realm);
|
|
||||||
if !p.exists() {
|
|
||||||
return Ok(None);
|
|
||||||
}
|
|
||||||
match fsx::read_json::<CompanionsPendingJob>(&p) {
|
|
||||||
Ok(job) => Ok(Some(job)),
|
|
||||||
Err(e) => {
|
|
||||||
tracing::warn!("Corrupted pending job file {:?}: {e}", p);
|
|
||||||
Ok(None)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn clear_pending_job(meta_dir: &Path, realm: &str) -> Result<()> {
|
|
||||||
let p = pending_job_path(meta_dir, realm);
|
|
||||||
if p.exists() {
|
|
||||||
let _ = std::fs::remove_file(p);
|
|
||||||
}
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
|
|
||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
mod tests {
|
mod tests {
|
||||||
use super::*;
|
use super::*;
|
||||||
@@ -317,63 +143,4 @@ mod tests {
|
|||||||
assert!(s.contains("@ACC"));
|
assert!(s.contains("@ACC"));
|
||||||
assert!(!s.contains("INSERT INTO "), "rows that exist are kept");
|
assert!(!s.contains("INSERT INTO "), "rows that exist are kept");
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn pending_jobs_roundtrip_and_are_isolated_by_realm() {
|
|
||||||
let temp = std::env::temp_dir().join(format!("coa-test-jobs-{}", uuid::Uuid::new_v4().simple()));
|
|
||||||
std::fs::create_dir_all(&temp).unwrap();
|
|
||||||
|
|
||||||
let job_wc = CompanionsPendingJob {
|
|
||||||
job_id: "test-wc-1".into(),
|
|
||||||
server_instance_id: "inst-1".into(),
|
|
||||||
realm: "wildcard".into(),
|
|
||||||
count: 50,
|
|
||||||
level: Some(60),
|
|
||||||
class_id: Some(10),
|
|
||||||
spec_id: Some(1),
|
|
||||||
build_id: Some("b9bc2e11-cd62-4d37-b05a-fff2a2ada475".into()),
|
|
||||||
requested_operation: "spawn".into(),
|
|
||||||
created_at: 1000,
|
|
||||||
state: "pending".into(),
|
|
||||||
completed_count: 0,
|
|
||||||
failed_count: 0,
|
|
||||||
last_error: None,
|
|
||||||
schema_version: 1,
|
|
||||||
};
|
|
||||||
|
|
||||||
let job_wcr = CompanionsPendingJob {
|
|
||||||
job_id: "test-wcr-1".into(),
|
|
||||||
server_instance_id: "inst-1".into(),
|
|
||||||
realm: "reborn".into(),
|
|
||||||
count: 10,
|
|
||||||
level: Some(60),
|
|
||||||
class_id: Some(7),
|
|
||||||
spec_id: Some(4),
|
|
||||||
build_id: None,
|
|
||||||
requested_operation: "spawn".into(),
|
|
||||||
created_at: 1001,
|
|
||||||
state: "pending".into(),
|
|
||||||
completed_count: 0,
|
|
||||||
failed_count: 0,
|
|
||||||
last_error: None,
|
|
||||||
schema_version: 1,
|
|
||||||
};
|
|
||||||
|
|
||||||
save_pending_job(&temp, "wildcard", &job_wc).unwrap();
|
|
||||||
save_pending_job(&temp, "reborn", &job_wcr).unwrap();
|
|
||||||
|
|
||||||
let loaded_wc = load_pending_job(&temp, "wildcard").unwrap().expect("wc job missing");
|
|
||||||
let loaded_wcr = load_pending_job(&temp, "reborn").unwrap().expect("wcr job missing");
|
|
||||||
let loaded_coa = load_pending_job(&temp, "coa").unwrap();
|
|
||||||
|
|
||||||
assert_eq!(loaded_wc, job_wc);
|
|
||||||
assert_eq!(loaded_wcr, job_wcr);
|
|
||||||
assert!(loaded_coa.is_none());
|
|
||||||
|
|
||||||
clear_pending_job(&temp, "wildcard").unwrap();
|
|
||||||
assert!(load_pending_job(&temp, "wildcard").unwrap().is_none());
|
|
||||||
assert!(load_pending_job(&temp, "reborn").unwrap().is_some());
|
|
||||||
|
|
||||||
let _ = std::fs::remove_dir_all(temp);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
+306
-124
@@ -5,7 +5,7 @@
|
|||||||
//! into the player's WoW client directory.
|
//! into the player's WoW client directory.
|
||||||
|
|
||||||
use std::fs::{self, File};
|
use std::fs::{self, File};
|
||||||
use std::io::{self, Read, Write};
|
use std::io::{self, Read};
|
||||||
use std::path::{Path, PathBuf};
|
use std::path::{Path, PathBuf};
|
||||||
|
|
||||||
use serde::{Deserialize, Serialize};
|
use serde::{Deserialize, Serialize};
|
||||||
@@ -153,7 +153,10 @@ pub fn sync_bot_races_config(root: &Path, allow_custom_races: bool) -> Result<()
|
|||||||
let clean = value.trim().trim_matches(['"', '\'']);
|
let clean = value.trim().trim_matches(['"', '\'']);
|
||||||
let owned = String::from_utf8_lossy(&bytes)
|
let owned = String::from_utf8_lossy(&bytes)
|
||||||
.contains("CoA Custom: races new random bots never get")
|
.contains("CoA Custom: races new random bots never get")
|
||||||
&& matches!(clean, EXCLUDED_BOT_RACES_RECOMMENDED | EXCLUDED_BOT_RACES_EXPERIMENTAL);
|
&& matches!(
|
||||||
|
clean,
|
||||||
|
EXCLUDED_BOT_RACES_RECOMMENDED | EXCLUDED_BOT_RACES_EXPERIMENTAL
|
||||||
|
);
|
||||||
if !owned {
|
if !owned {
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
@@ -662,134 +665,147 @@ fn stage_root_asset(staging: &Path, relative: &str, reader: &mut impl Read) -> R
|
|||||||
Ok(relative.to_string())
|
Ok(relative.to_string())
|
||||||
}
|
}
|
||||||
|
|
||||||
fn verify_archive(path: &Path, filename: &str) -> Result<()> {
|
fn archive_job(filename: &str, url: &str, cache: &Path) -> Result<crate::download::Job> {
|
||||||
let expected = match filename {
|
let (size, sha256) = match filename {
|
||||||
"CoA-Custom-1.9.2-Client-1.zip" => {
|
"CoA-Custom-1.9.2-Client-1.zip" => (
|
||||||
"a9dd51ed2d90fb048d549602f40f5429d56e2df0df5606a38781b358fa369568"
|
1_513_021_586,
|
||||||
}
|
"a9dd51ed2d90fb048d549602f40f5429d56e2df0df5606a38781b358fa369568",
|
||||||
"CoA-Custom-1.9.2-Client-2.zip" => {
|
),
|
||||||
"ab084a55509ccbcc2977a06dd0c01fa879973a1892baaacaeb3ff52f3dfc750e"
|
"CoA-Custom-1.9.2-Client-2.zip" => (
|
||||||
}
|
1_198_283_005,
|
||||||
"CoA-Custom-1.9.2-Client-3.zip" => {
|
"ab084a55509ccbcc2977a06dd0c01fa879973a1892baaacaeb3ff52f3dfc750e",
|
||||||
"907e267f0ee7038807e626c3c1eca5e12db6c88b747137a23c5fb52eaa1a358e"
|
),
|
||||||
}
|
"CoA-Custom-1.9.2-Client-3.zip" => (
|
||||||
"CoA-Custom-1.9.2-Client-4.zip" => {
|
1_678_829_573,
|
||||||
"e0bd87172af989fa50a8e2b08ba4321c72b6265047482f051a1db3b80d55bcaa"
|
"907e267f0ee7038807e626c3c1eca5e12db6c88b747137a23c5fb52eaa1a358e",
|
||||||
}
|
),
|
||||||
"CoA-Custom-1.9.2-Client-5.zip" => {
|
"CoA-Custom-1.9.2-Client-4.zip" => (
|
||||||
"73364ad1b58c6342641a848a3b20a835472834f600416606be1470386774ca78"
|
502_385_128,
|
||||||
}
|
"e0bd87172af989fa50a8e2b08ba4321c72b6265047482f051a1db3b80d55bcaa",
|
||||||
|
),
|
||||||
|
"CoA-Custom-1.9.2-Client-5.zip" => (
|
||||||
|
168_079_711,
|
||||||
|
"73364ad1b58c6342641a848a3b20a835472834f600416606be1470386774ca78",
|
||||||
|
),
|
||||||
_ => return Err(Error::Invalid("Unknown custom races archive.".into())),
|
_ => return Err(Error::Invalid("Unknown custom races archive.".into())),
|
||||||
};
|
};
|
||||||
if fsx::sha256_file(path)? != expected {
|
Ok(crate::download::Job {
|
||||||
|
url: url.into(),
|
||||||
|
dest: cache.join(filename),
|
||||||
|
sha256: sha256.into(),
|
||||||
|
size,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
fn archive_matches(path: &Path, job: &crate::download::Job) -> bool {
|
||||||
|
path.metadata()
|
||||||
|
.is_ok_and(|m| m.is_file() && m.len() == job.size)
|
||||||
|
&& fsx::sha256_file(path).is_ok_and(|hash| hash.eq_ignore_ascii_case(&job.sha256))
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
fn verify_archive(path: &Path, filename: &str) -> Result<()> {
|
||||||
|
let job = archive_job(filename, "", Path::new(""))?;
|
||||||
|
if !archive_matches(path, &job) {
|
||||||
return Err(Error::Invalid(format!(
|
return Err(Error::Invalid(format!(
|
||||||
"Custom races archive {filename} failed verification. Remove it and try again."
|
"Custom races archive {filename} failed verification."
|
||||||
)));
|
)));
|
||||||
}
|
}
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Locate an archive locally in Downloads or cache, or download it from GitHub.
|
/// User-owned Downloads files are read-only candidates. Only the Manager's cache is repaired.
|
||||||
|
fn resolve_archive_with(
|
||||||
|
transport: &dyn crate::download::Transport,
|
||||||
|
job: &crate::download::Job,
|
||||||
|
downloads: Option<&Path>,
|
||||||
|
cancel: &Cancel,
|
||||||
|
progress: &dyn Fn(crate::download::Progress),
|
||||||
|
) -> Result<PathBuf> {
|
||||||
|
if cancel.is_set() {
|
||||||
|
return Err(Error::Invalid("Download cancelled.".into()));
|
||||||
|
}
|
||||||
|
if let Some(downloads) = downloads {
|
||||||
|
let candidate = downloads.join(job.dest.file_name().unwrap_or_default());
|
||||||
|
if archive_matches(&candidate, job) {
|
||||||
|
tracing::info!(path = %candidate.display(), "using verified archive in Downloads");
|
||||||
|
progress(crate::download::Progress {
|
||||||
|
downloaded: job.size,
|
||||||
|
total: job.size,
|
||||||
|
bytes_per_sec: 0,
|
||||||
|
});
|
||||||
|
return Ok(candidate);
|
||||||
|
}
|
||||||
|
if candidate.exists() {
|
||||||
|
tracing::warn!(path = %candidate.display(), "ignoring incomplete or unverified archive in Downloads");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
let cache = job
|
||||||
|
.dest
|
||||||
|
.parent()
|
||||||
|
.ok_or_else(|| Error::Invalid("Missing archive cache directory.".into()))?;
|
||||||
|
fs::create_dir_all(cache)?;
|
||||||
|
// Different installations share this cache; never append to or replace another active download.
|
||||||
|
use fs4::fs_std::FileExt;
|
||||||
|
let lock = fs::OpenOptions::new()
|
||||||
|
.read(true)
|
||||||
|
.write(true)
|
||||||
|
.create(true)
|
||||||
|
.truncate(false)
|
||||||
|
.open(suffix(&job.dest, "lock"))?;
|
||||||
|
if !lock.try_lock_exclusive()? {
|
||||||
|
return Err(Error::Invalid("Another custom races download is using this archive. Wait for it to finish, then retry.".into()));
|
||||||
|
}
|
||||||
|
if job.dest.is_file() {
|
||||||
|
if archive_matches(&job.dest, job) {
|
||||||
|
progress(crate::download::Progress {
|
||||||
|
downloaded: job.size,
|
||||||
|
total: job.size,
|
||||||
|
bytes_per_sec: 0,
|
||||||
|
});
|
||||||
|
return Ok(job.dest.clone());
|
||||||
|
}
|
||||||
|
tracing::warn!(path = %job.dest.display(), "removing unverified Manager archive cache; downloading again");
|
||||||
|
fs::remove_file(&job.dest)?;
|
||||||
|
}
|
||||||
|
// The shared downloader resumes .part files and verifies the complete archive before promotion.
|
||||||
|
// A stale/corrupt prefix may only be detectable after resume: retry once from scratch in that case.
|
||||||
|
match crate::download::fetch_with(transport, job, cancel, progress) {
|
||||||
|
Err(Error::HashMismatch { .. }) if !cancel.is_set() => {
|
||||||
|
tracing::warn!(path = %job.dest.display(), "archive verification failed; retrying a clean download");
|
||||||
|
crate::download::fetch_with(transport, job, cancel, progress)?;
|
||||||
|
}
|
||||||
|
result => result?,
|
||||||
|
}
|
||||||
|
Ok(job.dest.clone())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Locate a verified archive or resume downloading it into the Manager's cache.
|
||||||
fn resolve_or_download_archive(
|
fn resolve_or_download_archive(
|
||||||
filename: &str,
|
filename: &str,
|
||||||
url: &str,
|
url: &str,
|
||||||
client: &reqwest::blocking::Client,
|
transport: &dyn crate::download::Transport,
|
||||||
cancel: &Cancel,
|
cancel: &Cancel,
|
||||||
report: &dyn Fn(&str, f32),
|
report: &dyn Fn(&str, f32),
|
||||||
base_percent: f32,
|
base_percent: f32,
|
||||||
percent_slice: f32,
|
percent_slice: f32,
|
||||||
) -> Result<PathBuf> {
|
) -> Result<PathBuf> {
|
||||||
// 1. Check user Downloads folder
|
// Report before hashing existing files: otherwise checking a large archive looks like no operation.
|
||||||
if let Some(userprofile) = std::env::var_os("USERPROFILE") {
|
report(&format!("Checking {filename}..."), base_percent);
|
||||||
let downloads = PathBuf::from(userprofile).join("Downloads");
|
let cache = std::env::temp_dir().join("coa-client-races");
|
||||||
let candidate = downloads.join(filename);
|
let downloads = std::env::var_os("USERPROFILE").map(|p| PathBuf::from(p).join("Downloads"));
|
||||||
if candidate.is_file() {
|
let job = archive_job(filename, url, &cache)?;
|
||||||
if let Ok(meta) = candidate.metadata() {
|
resolve_archive_with(transport, &job, downloads.as_deref(), cancel, &|p| {
|
||||||
if meta.len() > 1000 {
|
let ratio = p.downloaded as f32 / p.total.max(1) as f32;
|
||||||
tracing::info!(path = %candidate.display(), "using existing archive in Downloads");
|
report(
|
||||||
verify_archive(&candidate, filename)?;
|
&format!(
|
||||||
return Ok(candidate);
|
"Downloading {filename} ({:.1} MB)...",
|
||||||
}
|
p.downloaded as f64 / 1_048_576.0
|
||||||
}
|
),
|
||||||
}
|
base_percent + ratio.clamp(0.0, 1.0) * percent_slice,
|
||||||
}
|
);
|
||||||
|
})
|
||||||
// 2. Check temp / cache directory
|
|
||||||
let cache_dir = std::env::temp_dir().join("coa-client-races");
|
|
||||||
fs::create_dir_all(&cache_dir)?;
|
|
||||||
let target = cache_dir.join(filename);
|
|
||||||
if target.is_file() {
|
|
||||||
if let Ok(meta) = target.metadata() {
|
|
||||||
if meta.len() > 1000 {
|
|
||||||
verify_archive(&target, filename)?;
|
|
||||||
return Ok(target);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// 3. Download from GitHub Releases
|
|
||||||
report(&format!("Downloading {filename}..."), base_percent);
|
|
||||||
let part_path = cache_dir.join(format!("{filename}.part"));
|
|
||||||
|
|
||||||
let resp = client
|
|
||||||
.get(url)
|
|
||||||
.send()
|
|
||||||
.map_err(|e| Error::NetworkUnreachable(format!("Could not reach download server: {e}")))?;
|
|
||||||
|
|
||||||
if !resp.status().is_success() {
|
|
||||||
return Err(Error::NetworkUnreachable(format!(
|
|
||||||
"Download failed with status {} for {url}",
|
|
||||||
resp.status()
|
|
||||||
)));
|
|
||||||
}
|
|
||||||
|
|
||||||
let total_bytes = resp.content_length().unwrap_or(0);
|
|
||||||
let mut downloaded = 0u64;
|
|
||||||
let mut src = resp;
|
|
||||||
let mut dst = File::create(&part_path)?;
|
|
||||||
|
|
||||||
let mut buf = [0u8; 64 * 1024];
|
|
||||||
let mut last_report = std::time::Instant::now();
|
|
||||||
|
|
||||||
loop {
|
|
||||||
if cancel.is_set() {
|
|
||||||
let _ = fs::remove_file(&part_path);
|
|
||||||
return Err(Error::Invalid("Operation cancelled.".into()));
|
|
||||||
}
|
|
||||||
|
|
||||||
let n = src
|
|
||||||
.read(&mut buf)
|
|
||||||
.map_err(|e| Error::NetworkUnreachable(format!("Download interrupted: {e}")))?;
|
|
||||||
if n == 0 {
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
|
|
||||||
dst.write_all(&buf[..n])?;
|
|
||||||
downloaded += n as u64;
|
|
||||||
|
|
||||||
if last_report.elapsed() > std::time::Duration::from_millis(200) {
|
|
||||||
let ratio = if total_bytes > 0 {
|
|
||||||
(downloaded as f32 / total_bytes as f32).clamp(0.0, 1.0)
|
|
||||||
} else {
|
|
||||||
0.5
|
|
||||||
};
|
|
||||||
report(
|
|
||||||
&format!(
|
|
||||||
"Downloading {filename} ({:.1} MB)...",
|
|
||||||
downloaded as f64 / 1_048_576.0
|
|
||||||
),
|
|
||||||
base_percent + ratio * percent_slice,
|
|
||||||
);
|
|
||||||
last_report = std::time::Instant::now();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
dst.flush()?;
|
|
||||||
drop(dst);
|
|
||||||
|
|
||||||
verify_archive(&part_path, filename)?;
|
|
||||||
fs::rename(&part_path, &target)?;
|
|
||||||
Ok(target)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Download (if needed) and extract custom races client assets into the target WoW client.
|
/// Download (if needed) and extract custom races client assets into the target WoW client.
|
||||||
@@ -818,11 +834,7 @@ pub fn install_client_patches(
|
|||||||
fs::create_dir_all(&data_dir)?;
|
fs::create_dir_all(&data_dir)?;
|
||||||
|
|
||||||
// 2. Resolve/download archives (0.05 .. 0.50)
|
// 2. Resolve/download archives (0.05 .. 0.50)
|
||||||
let http = reqwest::blocking::Client::builder()
|
let http = crate::download::HttpTransport::with_total_timeout(600)?;
|
||||||
.user_agent(concat!("CoA-Server-Manager/", env!("CARGO_PKG_VERSION")))
|
|
||||||
.timeout(std::time::Duration::from_secs(600))
|
|
||||||
.build()
|
|
||||||
.map_err(|e| Error::Invalid(format!("Cannot prepare downloader: {e}")))?;
|
|
||||||
|
|
||||||
let mut resolved_archives = Vec::new();
|
let mut resolved_archives = Vec::new();
|
||||||
let n_archives = ARCHIVES.len() as f32;
|
let n_archives = ARCHIVES.len() as f32;
|
||||||
@@ -1113,7 +1125,9 @@ mod tests {
|
|||||||
serde_json::from_str(include_str!("custom_races_hashes_1_9_1.json")).unwrap();
|
serde_json::from_str(include_str!("custom_races_hashes_1_9_1.json")).unwrap();
|
||||||
let files = patch_files(temp.path()).unwrap();
|
let files = patch_files(temp.path()).unwrap();
|
||||||
assert_eq!(files.len(), old.len());
|
assert_eq!(files.len(), old.len());
|
||||||
assert!(files.iter().all(|file| old.get(&file.path) == Some(&file.sha256)));
|
assert!(files
|
||||||
|
.iter()
|
||||||
|
.all(|file| old.get(&file.path) == Some(&file.sha256)));
|
||||||
assert!(!files.iter().any(|file| file.path.contains("CoAQuestSafe")));
|
assert!(!files.iter().any(|file| file.path.contains("CoAQuestSafe")));
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1571,11 +1585,179 @@ mod tests {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
struct ArchiveTransport {
|
||||||
|
body: Vec<u8>,
|
||||||
|
ranges: std::sync::Mutex<Vec<u64>>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl crate::download::Transport for ArchiveTransport {
|
||||||
|
fn get(&self, _: &str, from: u64) -> std::result::Result<crate::download::Reply, String> {
|
||||||
|
self.ranges.lock().unwrap().push(from);
|
||||||
|
Ok(crate::download::Reply {
|
||||||
|
status: if from == 0 { 200 } else { 206 },
|
||||||
|
content_range: (from > 0)
|
||||||
|
.then(|| format!("bytes {from}-{}/{}", self.body.len() - 1, self.body.len())),
|
||||||
|
body: Box::new(io::Cursor::new(self.body[from as usize..].to_vec())),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn archive_fixture(root: &Path) -> (crate::download::Job, ArchiveTransport) {
|
||||||
|
use sha2::{Digest, Sha256};
|
||||||
|
let body = b"verified archive bytes for recovery tests".to_vec();
|
||||||
|
let job = crate::download::Job {
|
||||||
|
url: "https://example.invalid/patch.zip".into(),
|
||||||
|
dest: root.join("cache/patch.zip"),
|
||||||
|
sha256: hex::encode(Sha256::digest(&body)),
|
||||||
|
size: body.len() as u64,
|
||||||
|
};
|
||||||
|
fs::create_dir_all(job.dest.parent().unwrap()).unwrap();
|
||||||
|
(
|
||||||
|
job,
|
||||||
|
ArchiveTransport {
|
||||||
|
body,
|
||||||
|
ranges: Default::default(),
|
||||||
|
},
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn corrupt_downloads_are_rejected() {
|
fn download_uses_verified_user_archive_without_network() {
|
||||||
let temp = tempfile::NamedTempFile::new().unwrap();
|
let temp = tempfile::tempdir().unwrap();
|
||||||
fs::write(temp.path(), b"corrupt archive").unwrap();
|
let (job, transport) = archive_fixture(temp.path());
|
||||||
assert!(verify_archive(temp.path(), ARCHIVES[0].0).is_err());
|
let downloads = temp.path().join("Downloads");
|
||||||
|
fs::create_dir(&downloads).unwrap();
|
||||||
|
let archive = downloads.join("patch.zip");
|
||||||
|
fs::write(&archive, &transport.body).unwrap();
|
||||||
|
let path = resolve_archive_with(
|
||||||
|
&transport,
|
||||||
|
&job,
|
||||||
|
Some(&downloads),
|
||||||
|
&Cancel::default(),
|
||||||
|
&|_| {},
|
||||||
|
)
|
||||||
|
.unwrap();
|
||||||
|
assert_eq!(path, archive);
|
||||||
|
assert!(transport.ranges.lock().unwrap().is_empty());
|
||||||
|
assert!(!job.dest.exists());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn download_skips_bad_user_archive_and_repairs_bad_cache() {
|
||||||
|
let temp = tempfile::tempdir().unwrap();
|
||||||
|
let (job, transport) = archive_fixture(temp.path());
|
||||||
|
let downloads = temp.path().join("Downloads");
|
||||||
|
fs::create_dir(&downloads).unwrap();
|
||||||
|
let bad = vec![b'x'; transport.body.len()];
|
||||||
|
fs::write(downloads.join("patch.zip"), &bad).unwrap();
|
||||||
|
fs::write(downloads.join("patch.zip.part"), b"user browser download").unwrap();
|
||||||
|
fs::write(&job.dest, &bad).unwrap();
|
||||||
|
let path = resolve_archive_with(
|
||||||
|
&transport,
|
||||||
|
&job,
|
||||||
|
Some(&downloads),
|
||||||
|
&Cancel::default(),
|
||||||
|
&|_| {},
|
||||||
|
)
|
||||||
|
.unwrap();
|
||||||
|
assert_eq!(path, job.dest);
|
||||||
|
assert_eq!(fs::read(&path).unwrap(), transport.body);
|
||||||
|
assert_eq!(fs::read(downloads.join("patch.zip")).unwrap(), bad);
|
||||||
|
assert_eq!(
|
||||||
|
fs::read(downloads.join("patch.zip.part")).unwrap(),
|
||||||
|
b"user browser download"
|
||||||
|
);
|
||||||
|
assert_eq!(*transport.ranges.lock().unwrap(), vec![0]);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn download_resumes_leftover_part_and_verifies_complete_archive() {
|
||||||
|
let temp = tempfile::tempdir().unwrap();
|
||||||
|
let (job, transport) = archive_fixture(temp.path());
|
||||||
|
let part = suffix(&job.dest, "part");
|
||||||
|
fs::write(&part, &transport.body[..9]).unwrap();
|
||||||
|
resolve_archive_with(&transport, &job, None, &Cancel::default(), &|_| {}).unwrap();
|
||||||
|
assert_eq!(*transport.ranges.lock().unwrap(), vec![9]);
|
||||||
|
assert_eq!(fs::read(&job.dest).unwrap(), transport.body);
|
||||||
|
assert!(!part.exists());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn download_reuses_good_cache_even_when_user_archive_is_incomplete() {
|
||||||
|
let temp = tempfile::tempdir().unwrap();
|
||||||
|
let (job, transport) = archive_fixture(temp.path());
|
||||||
|
let downloads = temp.path().join("Downloads");
|
||||||
|
fs::create_dir(&downloads).unwrap();
|
||||||
|
fs::write(downloads.join("patch.zip"), b"incomplete").unwrap();
|
||||||
|
fs::write(&job.dest, &transport.body).unwrap();
|
||||||
|
let path = resolve_archive_with(
|
||||||
|
&transport,
|
||||||
|
&job,
|
||||||
|
Some(&downloads),
|
||||||
|
&Cancel::default(),
|
||||||
|
&|_| {},
|
||||||
|
)
|
||||||
|
.unwrap();
|
||||||
|
assert_eq!(path, job.dest);
|
||||||
|
assert!(transport.ranges.lock().unwrap().is_empty());
|
||||||
|
assert_eq!(
|
||||||
|
fs::read(downloads.join("patch.zip")).unwrap(),
|
||||||
|
b"incomplete"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn download_restarts_once_when_resumed_prefix_is_corrupt() {
|
||||||
|
let temp = tempfile::tempdir().unwrap();
|
||||||
|
let (job, transport) = archive_fixture(temp.path());
|
||||||
|
fs::write(suffix(&job.dest, "part"), b"bad").unwrap();
|
||||||
|
resolve_archive_with(&transport, &job, None, &Cancel::default(), &|_| {}).unwrap();
|
||||||
|
assert_eq!(*transport.ranges.lock().unwrap(), vec![3, 0]);
|
||||||
|
assert_eq!(fs::read(&job.dest).unwrap(), transport.body);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn download_promotes_completed_part_without_redownloading() {
|
||||||
|
let temp = tempfile::tempdir().unwrap();
|
||||||
|
let (job, transport) = archive_fixture(temp.path());
|
||||||
|
fs::write(suffix(&job.dest, "part"), &transport.body).unwrap();
|
||||||
|
resolve_archive_with(&transport, &job, None, &Cancel::default(), &|_| {}).unwrap();
|
||||||
|
assert!(transport.ranges.lock().unwrap().is_empty());
|
||||||
|
assert_eq!(fs::read(&job.dest).unwrap(), transport.body);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn download_stops_after_one_clean_retry_if_server_bytes_are_invalid() {
|
||||||
|
let temp = tempfile::tempdir().unwrap();
|
||||||
|
let (job, mut transport) = archive_fixture(temp.path());
|
||||||
|
transport.body.fill(b'x');
|
||||||
|
let result = resolve_archive_with(&transport, &job, None, &Cancel::default(), &|_| {});
|
||||||
|
assert!(matches!(result, Err(Error::HashMismatch { .. })));
|
||||||
|
assert_eq!(*transport.ranges.lock().unwrap(), vec![0, 0]);
|
||||||
|
assert!(!job.dest.exists());
|
||||||
|
assert!(!suffix(&job.dest, "part").exists());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn download_does_not_modify_an_archive_owned_by_another_download() {
|
||||||
|
use fs4::fs_std::FileExt;
|
||||||
|
let temp = tempfile::tempdir().unwrap();
|
||||||
|
let (job, transport) = archive_fixture(temp.path());
|
||||||
|
let lock = fs::OpenOptions::new()
|
||||||
|
.read(true)
|
||||||
|
.write(true)
|
||||||
|
.create(true)
|
||||||
|
.truncate(false)
|
||||||
|
.open(suffix(&job.dest, "lock"))
|
||||||
|
.unwrap();
|
||||||
|
lock.try_lock_exclusive().unwrap();
|
||||||
|
fs::write(suffix(&job.dest, "part"), b"active download").unwrap();
|
||||||
|
assert!(resolve_archive_with(&transport, &job, None, &Cancel::default(), &|_| {}).is_err());
|
||||||
|
assert_eq!(
|
||||||
|
fs::read(suffix(&job.dest, "part")).unwrap(),
|
||||||
|
b"active download"
|
||||||
|
);
|
||||||
|
assert!(transport.ranges.lock().unwrap().is_empty());
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
|
|||||||
@@ -337,6 +337,17 @@ impl Db {
|
|||||||
.map(|o| o.status.success()).unwrap_or(false)
|
.map(|o| o.status.success()).unwrap_or(false)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Ask the server to shut down cleanly (`mysqladmin shutdown`).
|
||||||
|
pub fn shutdown_server(&self) -> Result<()> {
|
||||||
|
let mut c = self.command("mysqladmin.exe");
|
||||||
|
c.arg("shutdown").arg("--connect-timeout=5");
|
||||||
|
let out = bounded_client_output(&mut c, b"", Instant::now() + Duration::from_secs(60))?;
|
||||||
|
if !out.status.success() {
|
||||||
|
return Err(self.fail(&out.stderr));
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
pub(crate) fn with_read_deadline(mut self, deadline: Instant) -> Self {
|
pub(crate) fn with_read_deadline(mut self, deadline: Instant) -> Self {
|
||||||
self.read_deadline = Some(deadline);
|
self.read_deadline = Some(deadline);
|
||||||
self
|
self
|
||||||
|
|||||||
+54
-308
@@ -1,11 +1,10 @@
|
|||||||
//! Start/stop of a repack-shaped installation by delegating to the repack's own supervisor
|
//! Start/stop of a repack-shaped installation through the repack launcher in this crate
|
||||||
//! (`Runtime\python\python.exe Scripts\manage.py <verb>`), which already implements config rendering, the
|
//! ([`crate::launcher`]): config rendering, the services, the world supervisor, graceful shutdown and readiness.
|
||||||
//! bug-report relay, RA graceful shutdown and readiness. Observation stays native (see `process`).
|
//! It writes the same `.state` records as the repack's `Scripts/manage.py`, so the repack's own launcher and
|
||||||
|
//! this Manager can be used on the same folder. Observation stays native (see `process`).
|
||||||
|
|
||||||
use std::io::Read;
|
use std::path::Path;
|
||||||
use std::path::{Path, PathBuf};
|
use std::sync::Mutex;
|
||||||
use std::process::{Command, Stdio};
|
|
||||||
use std::time::{Duration, Instant};
|
|
||||||
|
|
||||||
use serde::Serialize;
|
use serde::Serialize;
|
||||||
|
|
||||||
@@ -22,22 +21,13 @@ pub enum Verb {
|
|||||||
}
|
}
|
||||||
|
|
||||||
impl Verb {
|
impl Verb {
|
||||||
fn arg(self) -> &'static str {
|
fn action(self) -> crate::launcher::ops::Action {
|
||||||
|
use crate::launcher::ops::Action;
|
||||||
match self {
|
match self {
|
||||||
Verb::StartAll => "start-all",
|
Verb::StartAll => Action::StartAll,
|
||||||
Verb::StartMysql => "start-mysql",
|
Verb::StartMysql => Action::StartMysql,
|
||||||
Verb::StartWorld => "start-world",
|
Verb::StartWorld => Action::StartWorld,
|
||||||
Verb::StopAll => "stop-all",
|
Verb::StopAll => Action::StopAll,
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn timeout(self, _root: &Path) -> Duration {
|
|
||||||
match self {
|
|
||||||
// Includes database startup, optional bot provisioning and the shared 25-minute
|
|
||||||
// world/console wait in launcher_bridge.py, even for older installed scripts.
|
|
||||||
Verb::StartAll | Verb::StartWorld => Duration::from_secs(3600),
|
|
||||||
Verb::StartMysql => Duration::from_secs(360),
|
|
||||||
Verb::StopAll => Duration::from_secs(240),
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -52,41 +42,14 @@ pub struct DriverOutcome {
|
|||||||
pub output: String,
|
pub output: String,
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Map the launcher's own messages onto stable error codes. Unknown text stays `Unknown` (details remain visible).
|
fn has_launcher_settings(root: &Path) -> Result<()> {
|
||||||
pub fn translate(output: &str) -> ErrorCode {
|
if !root.join("Settings/repack.json").is_file() {
|
||||||
let o = output.to_lowercase();
|
|
||||||
if o.contains("is already used") {
|
|
||||||
ErrorCode::PortInUse
|
|
||||||
} else if o.contains("another start/stop action is in progress")
|
|
||||||
|| o.contains("shutdown is still finishing")
|
|
||||||
{
|
|
||||||
ErrorCode::OperationInProgress
|
|
||||||
} else if o.contains("packaged database is missing")
|
|
||||||
|| o.contains("extract the complete repack")
|
|
||||||
{
|
|
||||||
ErrorCode::ServerFilesIncomplete
|
|
||||||
} else if o.contains("stopped during startup")
|
|
||||||
|| o.contains("is still starting")
|
|
||||||
|| o.contains("world startup failed")
|
|
||||||
{
|
|
||||||
ErrorCode::StartupFailed
|
|
||||||
} else if o.contains("invalid port") || o.contains("unresolved placeholder") {
|
|
||||||
ErrorCode::InvalidConfigValue
|
|
||||||
} else {
|
|
||||||
ErrorCode::Unknown
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn launcher(root: &Path) -> Result<(PathBuf, PathBuf)> {
|
|
||||||
let python = root.join("Runtime/python/python.exe");
|
|
||||||
let script = root.join("Scripts/manage.py");
|
|
||||||
if !python.is_file() || !script.is_file() {
|
|
||||||
return Err(Error::Invalid(
|
return Err(Error::Invalid(
|
||||||
"This server has no CoA Repack launcher; start/stop is not available for it yet."
|
"This server has no CoA Repack launcher; start/stop is not available for it yet."
|
||||||
.into(),
|
.into(),
|
||||||
));
|
));
|
||||||
}
|
}
|
||||||
Ok((python, script))
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Run a launcher verb to completion (blocking; call from a worker thread).
|
/// Run a launcher verb to completion (blocking; call from a worker thread).
|
||||||
@@ -205,108 +168,51 @@ fn run_inner_mode(
|
|||||||
if matches!(verb, Verb::StartAll | Verb::StartWorld) {
|
if matches!(verb, Verb::StartAll | Verb::StartWorld) {
|
||||||
crate::modules::ensure_bot_exclusivity(&root)?;
|
crate::modules::ensure_bot_exclusivity(&root)?;
|
||||||
}
|
}
|
||||||
let (python, script) = launcher(&root)?;
|
has_launcher_settings(&root)?;
|
||||||
prepare_headless_world(&root, verb)?;
|
prepare_headless_world(&root, verb)?;
|
||||||
let original = std::fs::read_to_string(&script)?;
|
|
||||||
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) {
|
|
||||||
if let Ok((_, mut meta)) = crate::registry::MetaDir::open(&dir) {
|
|
||||||
if meta.original_hashes.get("Scripts/manage.py")
|
|
||||||
== Some(&fsx::sha256_bytes(original.as_bytes()))
|
|
||||||
{
|
|
||||||
meta.original_hashes.insert(
|
|
||||||
"Scripts/manage.py".into(),
|
|
||||||
fsx::sha256_bytes(patched.as_bytes()),
|
|
||||||
);
|
|
||||||
fsx::atomic_write_json(&dir.join("install.json"), &meta)?;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
discard_damaged_launcher_state(&root);
|
|
||||||
if matches!(verb, Verb::StopAll | Verb::StartMysql | Verb::StartAll) {
|
if matches!(verb, Verb::StopAll | Verb::StartMysql | Verb::StartAll) {
|
||||||
recover_mysql_launcher_state(&root, verb != Verb::StopAll)?;
|
recover_mysql_launcher_state(&root, verb != Verb::StopAll)?;
|
||||||
}
|
}
|
||||||
if force {
|
if force {
|
||||||
recover_world_for_forced_stop(&root)?;
|
recover_world_for_forced_stop(&root)?;
|
||||||
}
|
}
|
||||||
let mut cmd = Command::new(&python);
|
let action = if force {
|
||||||
if validating_update {
|
crate::launcher::ops::Action::ForceStopAll
|
||||||
// Isolated startup must use the port from its temporary auth config.
|
|
||||||
cmd.env_remove("AC_REALM_SERVER_PORT");
|
|
||||||
}
|
|
||||||
cmd.arg("-B")
|
|
||||||
.arg("-c")
|
|
||||||
.arg(LAUNCH_SCRIPT)
|
|
||||||
.arg(&script)
|
|
||||||
.arg(if force { "force-stop-all" } else { verb.arg() })
|
|
||||||
.current_dir(&root)
|
|
||||||
.stdin(Stdio::null())
|
|
||||||
.stdout(Stdio::piped())
|
|
||||||
.stderr(Stdio::piped());
|
|
||||||
#[cfg(windows)]
|
|
||||||
{
|
|
||||||
use std::os::windows::process::CommandExt;
|
|
||||||
cmd.creation_flags(0x0800_0000); // CREATE_NO_WINDOW
|
|
||||||
}
|
|
||||||
tracing::info!(?verb, root = %root.display(), "driver: starting launcher verb");
|
|
||||||
let mut child = cmd.spawn()?;
|
|
||||||
let mut stdout = child.stdout.take().expect("piped");
|
|
||||||
let mut stderr = child.stderr.take().expect("piped");
|
|
||||||
let out_t = std::thread::spawn(move || {
|
|
||||||
let mut s = String::new();
|
|
||||||
let _ = stdout.read_to_string(&mut s);
|
|
||||||
s
|
|
||||||
});
|
|
||||||
let err_t = std::thread::spawn(move || {
|
|
||||||
let mut s = String::new();
|
|
||||||
let _ = stderr.read_to_string(&mut s);
|
|
||||||
s
|
|
||||||
});
|
|
||||||
let deadline = Instant::now() + verb.timeout(&root);
|
|
||||||
let status = loop {
|
|
||||||
if let Some(st) = child.try_wait()? {
|
|
||||||
break Some(st);
|
|
||||||
}
|
|
||||||
if Instant::now() > deadline {
|
|
||||||
// Never kill the servers themselves: only abandon the launcher process we spawned.
|
|
||||||
let _ = child.kill();
|
|
||||||
break None;
|
|
||||||
}
|
|
||||||
std::thread::sleep(Duration::from_millis(200));
|
|
||||||
};
|
|
||||||
let mut output = out_t.join().unwrap_or_default();
|
|
||||||
output.push_str(&err_t.join().unwrap_or_default());
|
|
||||||
let mut output = output.trim().to_string();
|
|
||||||
if status.is_none() {
|
|
||||||
output.push_str(&format!(
|
|
||||||
"\nLauncher {} exceeded its {} second deadline; check the server logs.",
|
|
||||||
verb.arg(),
|
|
||||||
verb.timeout(&root).as_secs()
|
|
||||||
));
|
|
||||||
}
|
|
||||||
let (ok, exit_code) = match status {
|
|
||||||
Some(st) => (st.success(), st.code()),
|
|
||||||
None => (false, None),
|
|
||||||
};
|
|
||||||
let code = if ok {
|
|
||||||
None
|
|
||||||
} else {
|
} else {
|
||||||
// Log evidence beats the launcher's generic "stopped during startup" message.
|
verb.action()
|
||||||
let base = if status.is_none() {
|
};
|
||||||
ErrorCode::StartupFailed
|
tracing::info!(?verb, root = %root.display(), "driver: starting launcher action");
|
||||||
} else {
|
let lines = Mutex::new(Vec::<String>::new());
|
||||||
translate(&output)
|
let progress = |line: &str| {
|
||||||
};
|
tracing::info!(?verb, "launcher: {line}");
|
||||||
match base {
|
lines.lock().unwrap_or_else(|e| e.into_inner()).push(line.to_string());
|
||||||
ErrorCode::StartupFailed | ErrorCode::Unknown => {
|
};
|
||||||
Some(crate::health::diagnose_installation(&root).unwrap_or(base))
|
let result = crate::launcher::Settings::load(&root, 0).and_then(|mut cfg| {
|
||||||
|
if validating_update {
|
||||||
|
// Isolated startup must use the port from its temporary auth config.
|
||||||
|
cfg.env_remove.push("AC_REALM_SERVER_PORT".into());
|
||||||
|
}
|
||||||
|
crate::launcher::ops::run(&root, &cfg, 0, action, None, &progress)
|
||||||
|
});
|
||||||
|
let mut output = lines.into_inner().unwrap_or_else(|e| e.into_inner()).join("\n");
|
||||||
|
let ok = result.is_ok();
|
||||||
|
let code = match &result {
|
||||||
|
Ok(()) => None,
|
||||||
|
Err(error) => {
|
||||||
|
if !output.is_empty() {
|
||||||
|
output.push('\n');
|
||||||
|
}
|
||||||
|
output.push_str(&format!("ERROR: {error}"));
|
||||||
|
// Log evidence beats a generic "stopped during startup".
|
||||||
|
match error.code() {
|
||||||
|
ErrorCode::StartupFailed | ErrorCode::Unknown => Some(
|
||||||
|
crate::health::diagnose_installation(&root).unwrap_or(error.code()),
|
||||||
|
),
|
||||||
|
other => Some(other),
|
||||||
}
|
}
|
||||||
other => Some(other),
|
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
let exit_code = Some(if ok { 0 } else { 1 });
|
||||||
if code == Some(ErrorCode::PortInUse) {
|
if code == Some(ErrorCode::PortInUse) {
|
||||||
let observed = crate::process::observe(&root, &crate::layout::read_ports(&root));
|
let observed = crate::process::observe(&root, &crate::layout::read_ports(&root));
|
||||||
for service in [&observed.mysql, &observed.auth, &observed.world]
|
for service in [&observed.mysql, &observed.auth, &observed.world]
|
||||||
@@ -374,35 +280,6 @@ fn prepare_headless_world(root: &Path, verb: Verb) -> Result<()> {
|
|||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
/// The launcher keeps one JSON record per service in `.state`. A crash or power loss while it writes one can leave
|
|
||||||
/// a file of the right length that holds only zero bytes (NTFS keeps the length but not the data), and the launcher
|
|
||||||
/// then dies on every start with an unreadable record. Such a file carries no information, so remove it: the
|
|
||||||
/// launcher treats a missing record as "not running". Only empty or all-zero `*.json` files are touched.
|
|
||||||
pub(crate) fn discard_damaged_launcher_state(root: &Path) -> Vec<PathBuf> {
|
|
||||||
let mut removed = Vec::new();
|
|
||||||
let Ok(entries) = std::fs::read_dir(root.join(".state")) else {
|
|
||||||
return removed;
|
|
||||||
};
|
|
||||||
for entry in entries.flatten() {
|
|
||||||
let path = entry.path();
|
|
||||||
if path
|
|
||||||
.extension()
|
|
||||||
.is_none_or(|e| !e.eq_ignore_ascii_case("json"))
|
|
||||||
|| !path.is_file()
|
|
||||||
{
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
let Ok(bytes) = std::fs::read(&path) else {
|
|
||||||
continue;
|
|
||||||
};
|
|
||||||
if bytes.iter().all(|b| *b == 0) && std::fs::remove_file(&path).is_ok() {
|
|
||||||
tracing::warn!(file = %path.display(), bytes = bytes.len(), "driver: removed a launcher state file damaged by an interrupted write");
|
|
||||||
removed.push(path);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
removed
|
|
||||||
}
|
|
||||||
|
|
||||||
/// A lost launcher record must not hide this installation's running MySQL from
|
/// A lost launcher record must not hide this installation's running MySQL from
|
||||||
/// graceful shutdown. Adopt only the exact executable owning its configured port.
|
/// graceful shutdown. Adopt only the exact executable owning its configured port.
|
||||||
fn recover_mysql_launcher_state(root: &Path, prefer_listener: bool) -> Result<()> {
|
fn recover_mysql_launcher_state(root: &Path, prefer_listener: bool) -> Result<()> {
|
||||||
@@ -453,60 +330,6 @@ fn recover_mysql_launcher_state(root: &Path, prefer_listener: bool) -> Result<()
|
|||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
const LAUNCH_SCRIPT: &str = include_str!("launcher_bridge.py");
|
|
||||||
|
|
||||||
pub(crate) fn patch_launcher_imports(text: &str) -> Result<String> {
|
|
||||||
let line = "sys.path.insert(0, str(Path(__file__).resolve().parent))";
|
|
||||||
if !text.contains("from squid_playerbots import") || text.contains(line) {
|
|
||||||
return Ok(text.into());
|
|
||||||
}
|
|
||||||
let root = "ROOT = Path(__file__).resolve().parents[1]";
|
|
||||||
if !text.contains(root) || !text.lines().any(|line| line.trim() == "import sys") {
|
|
||||||
return Err(Error::Invalid(
|
|
||||||
"The server launcher cannot load its integration scripts. Repair its program files."
|
|
||||||
.into(),
|
|
||||||
));
|
|
||||||
}
|
|
||||||
Ok(text.replacen(root, &format!("{root}\n{line}"), 1))
|
|
||||||
}
|
|
||||||
|
|
||||||
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;
|
|
||||||
}
|
|
||||||
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 {
|
pub(crate) fn startup_failure(root: &Path, started: &DriverOutcome) -> String {
|
||||||
let code = started
|
let code = started
|
||||||
.code
|
.code
|
||||||
@@ -608,7 +431,7 @@ mod tests {
|
|||||||
text.contains("launcher request failed before completion")
|
text.contains("launcher request failed before completion")
|
||||||
&& text.contains("in progress")
|
&& text.contains("in progress")
|
||||||
);
|
);
|
||||||
assert!(!text.contains("starting launcher verb"));
|
assert!(!text.contains("starting launcher action"));
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
@@ -665,78 +488,10 @@ mod tests {
|
|||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn slow_world_startup_has_time_with_either_bot_system_without_extending_shutdown() {
|
fn launcher_failures_carry_their_error_code() {
|
||||||
let folder = tempfile::tempdir().unwrap();
|
let e = Error::Service(ErrorCode::PortInUse, "Port 8085 is already used (PID 4).".into());
|
||||||
let modules = folder.path().join("Core/configs/modules");
|
assert_eq!(e.code(), ErrorCode::PortInUse);
|
||||||
std::fs::create_dir_all(&modules).unwrap();
|
assert_eq!(e.to_string(), "Port 8085 is already used (PID 4).");
|
||||||
std::fs::write(
|
|
||||||
modules.join("playerbots.conf.dist"),
|
|
||||||
"AiPlayerbot.Enabled = 1\n",
|
|
||||||
)
|
|
||||||
.unwrap();
|
|
||||||
assert_eq!(
|
|
||||||
Verb::StartAll.timeout(folder.path()),
|
|
||||||
Duration::from_secs(3600)
|
|
||||||
);
|
|
||||||
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(3600)
|
|
||||||
);
|
|
||||||
assert_eq!(
|
|
||||||
Verb::StartMysql.timeout(folder.path()),
|
|
||||||
Duration::from_secs(360)
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn zero_filled_launcher_state_is_discarded_and_valid_state_is_kept() {
|
|
||||||
let folder = tempfile::tempdir().unwrap();
|
|
||||||
let state = folder.path().join(".state");
|
|
||||||
std::fs::create_dir_all(&state).unwrap();
|
|
||||||
std::fs::write(state.join("mysql.json"), vec![0u8; 116]).unwrap();
|
|
||||||
std::fs::write(state.join("configuration.json"), Vec::<u8>::new()).unwrap();
|
|
||||||
std::fs::write(state.join("world.json"), "{\"pid\": 4}\n").unwrap();
|
|
||||||
std::fs::write(state.join("stop-relay"), Vec::<u8>::new()).unwrap();
|
|
||||||
std::fs::write(state.join("auth.json"), "{\"pid\": 0}").unwrap();
|
|
||||||
let mut removed: Vec<_> = discard_damaged_launcher_state(folder.path())
|
|
||||||
.iter()
|
|
||||||
.map(|p| p.file_name().unwrap().to_string_lossy().into_owned())
|
|
||||||
.collect();
|
|
||||||
removed.sort();
|
|
||||||
assert_eq!(removed, ["configuration.json", "mysql.json"]);
|
|
||||||
assert!(
|
|
||||||
state.join("world.json").exists()
|
|
||||||
&& state.join("auth.json").exists()
|
|
||||||
&& state.join("stop-relay").exists()
|
|
||||||
);
|
|
||||||
assert!(discard_damaged_launcher_state(folder.path()).is_empty());
|
|
||||||
assert!(discard_damaged_launcher_state(&folder.path().join("missing")).is_empty());
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn translates_known_launcher_messages() {
|
|
||||||
assert_eq!(
|
|
||||||
translate("RuntimeError: Port 8085 is already used. Stop the other server"),
|
|
||||||
ErrorCode::PortInUse
|
|
||||||
);
|
|
||||||
assert_eq!(
|
|
||||||
translate("Another start/stop action is in progress."),
|
|
||||||
ErrorCode::OperationInProgress
|
|
||||||
);
|
|
||||||
assert_eq!(
|
|
||||||
translate("The packaged database is missing. Extract the complete repack."),
|
|
||||||
ErrorCode::ServerFilesIncomplete
|
|
||||||
);
|
|
||||||
assert_eq!(
|
|
||||||
translate("world stopped during startup. Check its log."),
|
|
||||||
ErrorCode::StartupFailed
|
|
||||||
);
|
|
||||||
assert_eq!(translate("Exit code -1073741819"), ErrorCode::Unknown);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
@@ -779,13 +534,4 @@ mod tests {
|
|||||||
assert!(!reason.contains("private"));
|
assert!(!reason.contains("private"));
|
||||||
assert!(!reason.contains("Something went wrong"));
|
assert!(!reason.contains("Something went wrong"));
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn launcher_import_fix_is_idempotent_and_retains_other_code() {
|
|
||||||
let text = "import sys\nROOT = Path(__file__).resolve().parents[1]\nfrom squid_playerbots import validate_bots\ncustom = 42\n";
|
|
||||||
let fixed = patch_launcher_imports(text).unwrap();
|
|
||||||
assert!(fixed.contains("sys.path.insert(0, str(Path(__file__).resolve().parent))"));
|
|
||||||
assert!(fixed.ends_with("custom = 42\n"));
|
|
||||||
assert_eq!(patch_launcher_imports(&fixed).unwrap(), fixed);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
@@ -24,6 +24,9 @@ pub enum Error {
|
|||||||
UnknownInstallation(String),
|
UnknownInstallation(String),
|
||||||
#[error("{0}")]
|
#[error("{0}")]
|
||||||
Invalid(String),
|
Invalid(String),
|
||||||
|
/// A server start or stop failed for a reason the UI can explain (the repack launcher's own errors).
|
||||||
|
#[error("{1}")]
|
||||||
|
Service(ErrorCode, String),
|
||||||
#[error("package not published: {0}")]
|
#[error("package not published: {0}")]
|
||||||
PackageNotPublished(String),
|
PackageNotPublished(String),
|
||||||
#[error("download server unreachable: {0}")]
|
#[error("download server unreachable: {0}")]
|
||||||
@@ -199,6 +202,7 @@ impl Error {
|
|||||||
Error::PackageNotPublished(_) => ErrorCode::PackageNotPublished,
|
Error::PackageNotPublished(_) => ErrorCode::PackageNotPublished,
|
||||||
Error::NetworkUnreachable(_) => ErrorCode::NetworkUnreachable,
|
Error::NetworkUnreachable(_) => ErrorCode::NetworkUnreachable,
|
||||||
Error::BotModulesConflict => ErrorCode::BotModulesConflict,
|
Error::BotModulesConflict => ErrorCode::BotModulesConflict,
|
||||||
|
Error::Service(code, _) => *code,
|
||||||
Error::CompanionTemplatesMissing => ErrorCode::CompanionTemplatesMissing,
|
Error::CompanionTemplatesMissing => ErrorCode::CompanionTemplatesMissing,
|
||||||
Error::CompanionCommandUnsupported => ErrorCode::CompanionCommandUnsupported,
|
Error::CompanionCommandUnsupported => ErrorCode::CompanionCommandUnsupported,
|
||||||
_ => ErrorCode::Unknown,
|
_ => ErrorCode::Unknown,
|
||||||
|
|||||||
@@ -210,7 +210,7 @@ pub(crate) fn free_port() -> Result<u16> {
|
|||||||
|
|
||||||
/// Run `f` with the staging copy listening on unused ports, so an installation never collides with a server (or any
|
/// 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.
|
/// 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> {
|
pub fn with_scratch_ports<T>(root: &Path, f: impl FnOnce() -> Result<T>) -> Result<T> {
|
||||||
const KEYS: [&str; 4] = ["mysqlPort", "authPort", "worldPort", "raPort"];
|
const KEYS: [&str; 4] = ["mysqlPort", "authPort", "worldPort", "raPort"];
|
||||||
let path = root.join("Settings/repack.json");
|
let path = root.join("Settings/repack.json");
|
||||||
let original: serde_json::Value = fsx::read_json(&path)?;
|
let original: serde_json::Value = fsx::read_json(&path)?;
|
||||||
@@ -378,15 +378,18 @@ pub fn install_base(p: &Params, report: &dyn Fn(Step)) -> Result<Installed> {
|
|||||||
})?;
|
})?;
|
||||||
say("Preparing database", 82, None);
|
say("Preparing database", 82, None);
|
||||||
bootstrap_database(&staging_root)?;
|
bootstrap_database(&staging_root)?;
|
||||||
crate::backup::with_database(&staging_root, |db| {
|
// On unused ports too: another server running on the shipped ports must not stop the installation.
|
||||||
let problems = crate::schema_check::check(db, &staging_root)?;
|
with_scratch_ports(&staging_root, || {
|
||||||
if let Some(p) = problems.first() {
|
crate::backup::with_database(&staging_root, |db| {
|
||||||
return Err(Error::Invalid(format!(
|
let problems = crate::schema_check::check(db, &staging_root)?;
|
||||||
"The packaged database is incomplete: {}.{}.{}: {}.",
|
if let Some(p) = problems.first() {
|
||||||
p.database, p.table, p.column, p.detail
|
return Err(Error::Invalid(format!(
|
||||||
)));
|
"The packaged database is incomplete: {}.{}.{}: {}.",
|
||||||
}
|
p.database, p.table, p.column, p.detail
|
||||||
Ok(())
|
)));
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
})
|
||||||
})?;
|
})?;
|
||||||
// 4. Commit: the only moment the destination changes. The marker stays until everything is done, so an
|
// 4. Commit: the only moment the destination changes. The marker stays until everything is done, so an
|
||||||
// unfinished install can always be recognised as ours (and cleaned up), wherever it stopped.
|
// unfinished install can always be recognised as ours (and cleaned up), wherever it stopped.
|
||||||
|
|||||||
@@ -0,0 +1,24 @@
|
|||||||
|
//! The repack launcher in Rust: what `Scripts/manage.py` does, without Python.
|
||||||
|
//!
|
||||||
|
//! Formats on disk stay exactly those of `manage.py`, so the two can be used on the same server during the move
|
||||||
|
//! (an old `.bat` and a new Manager, or the other way round):
|
||||||
|
//!
|
||||||
|
//! * `.state/<service>.json` process records `{pid, exe, created}` (see [`crate::process::ProcessIdentity`]);
|
||||||
|
//! * `.state/control.lock` one start/stop action at a time: byte 0 locked, as `msvcrt.locking` does;
|
||||||
|
//! * `.state/control-owner.json`, `.state/configuration.json`, `.state/debug-logs.json`;
|
||||||
|
//! * the rendered configs (`Core/configs/*.conf`, `mysql/my.ini`, `mysql/admin-client.ini`) byte for byte.
|
||||||
|
//!
|
||||||
|
//! State files are written with a flush to disk before they replace the old ones (`manage.py` did not, and a
|
||||||
|
//! power cut could leave a zero-filled record that stopped every later start).
|
||||||
|
|
||||||
|
pub mod ops;
|
||||||
|
pub mod relay;
|
||||||
|
pub mod render;
|
||||||
|
pub mod services;
|
||||||
|
pub mod settings;
|
||||||
|
pub mod spawn;
|
||||||
|
pub mod squid;
|
||||||
|
pub mod state;
|
||||||
|
pub mod world;
|
||||||
|
|
||||||
|
pub use settings::Settings;
|
||||||
@@ -0,0 +1,88 @@
|
|||||||
|
//! One start/stop action of a repack, with the control lock held (`manage.py main()`): the entry point of both
|
||||||
|
//! `coa-launcher.exe` and the Manager.
|
||||||
|
|
||||||
|
use std::path::Path;
|
||||||
|
use std::time::Duration;
|
||||||
|
|
||||||
|
use crate::error::Result;
|
||||||
|
use crate::launcher::services::{self, Progress};
|
||||||
|
use crate::launcher::world::{self, Supervisor};
|
||||||
|
use crate::launcher::{render, settings::Settings, squid, state};
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||||
|
pub enum Action {
|
||||||
|
StartAll,
|
||||||
|
StartMysql,
|
||||||
|
StartAuth,
|
||||||
|
StartWorld,
|
||||||
|
StopAll,
|
||||||
|
/// Stop the world without its console first (unsaved progress is lost), then everything else.
|
||||||
|
ForceStopAll,
|
||||||
|
Prepare,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Action {
|
||||||
|
/// The command name, as the `.bat` files and `manage.py` call it.
|
||||||
|
pub fn name(self) -> &'static str {
|
||||||
|
match self {
|
||||||
|
Action::StartAll => "start-all",
|
||||||
|
Action::StartMysql => "start-mysql",
|
||||||
|
Action::StartAuth => "start-auth",
|
||||||
|
Action::StartWorld => "start-world",
|
||||||
|
Action::StopAll => "stop-all",
|
||||||
|
Action::ForceStopAll => "force-stop-all",
|
||||||
|
Action::Prepare => "prepare",
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn parse(name: &str) -> Option<Action> {
|
||||||
|
[
|
||||||
|
Action::StartAll,
|
||||||
|
Action::StartMysql,
|
||||||
|
Action::StartAuth,
|
||||||
|
Action::StartWorld,
|
||||||
|
Action::StopAll,
|
||||||
|
Action::ForceStopAll,
|
||||||
|
Action::Prepare,
|
||||||
|
]
|
||||||
|
.into_iter()
|
||||||
|
.find(|a| a.name() == name)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Run `action`. A started world is supervised by `supervisor`, or by what the repack ships when it is `None`.
|
||||||
|
pub fn run(root: &Path, cfg: &Settings, offset: i32, action: Action, supervisor: Option<&Supervisor>, progress: Progress) -> Result<()> {
|
||||||
|
let _lock = state::ControlLock::acquire(root, action.name(), Duration::from_secs(30), progress)?;
|
||||||
|
match action {
|
||||||
|
// Shutdown uses the existing client and console settings: the templates may be exactly what a recovery
|
||||||
|
// needs to replace, so nothing is rendered.
|
||||||
|
Action::StopAll => return services::stop_all(root, cfg, progress),
|
||||||
|
Action::ForceStopAll => return services::force_stop_all(root, cfg, progress),
|
||||||
|
_ => {}
|
||||||
|
}
|
||||||
|
if matches!(action, Action::StartAll | Action::StartWorld) {
|
||||||
|
squid::validate_bots(root)?;
|
||||||
|
}
|
||||||
|
render::prepare(root, cfg)?;
|
||||||
|
if action == Action::Prepare {
|
||||||
|
return Ok(());
|
||||||
|
}
|
||||||
|
if matches!(action, Action::StartAll | Action::StartMysql) {
|
||||||
|
services::start_mysql(root, cfg, progress)?;
|
||||||
|
}
|
||||||
|
if matches!(action, Action::StartAll | Action::StartAuth) {
|
||||||
|
services::start_auth(root, cfg, progress)?;
|
||||||
|
}
|
||||||
|
if matches!(action, Action::StartAll | Action::StartWorld) {
|
||||||
|
let shipped;
|
||||||
|
let supervisor = match supervisor {
|
||||||
|
Some(s) => s,
|
||||||
|
None => {
|
||||||
|
shipped = Supervisor::of(root)?;
|
||||||
|
&shipped
|
||||||
|
}
|
||||||
|
};
|
||||||
|
world::start_world(root, cfg, offset, supervisor, progress)?;
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
@@ -0,0 +1,493 @@
|
|||||||
|
//! The bug-report relay (`BugReport/relay.py` and `manage.py relay-worker`): delivers the reports the world
|
||||||
|
//! writes to `BugReport/reports/*.report` through the CoA report service.
|
||||||
|
//!
|
||||||
|
//! On disk everything stays as the Python relay keeps it, so either can take over a spool: the `<key>.status`
|
||||||
|
//! files the world reads back, the delivery journal `relay.sqlite3` (tables `deliveries` and `settings`), and
|
||||||
|
//! `relay.lock` (byte 0 locked while a worker runs). A delivery interrupted while it was posting becomes
|
||||||
|
//! `uncertain` and is never sent again (the service's duplicate filter may have been reset in the meantime).
|
||||||
|
|
||||||
|
use std::path::{Path, PathBuf};
|
||||||
|
use std::time::{Duration, SystemTime, UNIX_EPOCH};
|
||||||
|
|
||||||
|
use rusqlite::{params, Connection, OptionalExtension};
|
||||||
|
use sha2::{Digest, Sha256};
|
||||||
|
|
||||||
|
use crate::error::{Error, Result};
|
||||||
|
use crate::launcher::state;
|
||||||
|
|
||||||
|
const REPOSITORY: &str = "jealous-sound/azerothcore-wotlk-coa";
|
||||||
|
pub const SERVICE_URL: &str = "https://coa-bug-report.up.railway.app";
|
||||||
|
/// Distribution credential for this narrow intake API (the same as relay.py's); not a GitHub token.
|
||||||
|
pub const DEFAULT_API_KEY: &str = "coa_zRatxUHShOn-HEkoreKGME6sd3DdMG7eKTTKlj2JCK4";
|
||||||
|
const MAX_FILE: u64 = 16000;
|
||||||
|
const MAX_RESPONSE: usize = 64 * 1024;
|
||||||
|
|
||||||
|
/// `[1-9][0-9]{0,9}-[0-9a-f]{16,48}`: the name of a report file (without `.report`).
|
||||||
|
pub fn valid_key(key: &str) -> bool {
|
||||||
|
let Some((id, hex)) = key.split_once('-') else { return false };
|
||||||
|
(1..=10).contains(&id.len())
|
||||||
|
&& !id.starts_with('0')
|
||||||
|
&& id.bytes().all(|b| b.is_ascii_digit())
|
||||||
|
&& (16..=48).contains(&hex.len())
|
||||||
|
&& hex.bytes().all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Why a delivery did not create an issue. Only fixed local codes: never service bodies, credentials or report
|
||||||
|
/// content.
|
||||||
|
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||||
|
pub enum Failure {
|
||||||
|
/// 202 pending: the service is still creating it.
|
||||||
|
Pending(u64),
|
||||||
|
/// 429: try again later.
|
||||||
|
Limited(u64),
|
||||||
|
/// The report itself was refused.
|
||||||
|
Invalid,
|
||||||
|
/// The service refused this relay (redirect, auth, missing endpoint, GitHub access).
|
||||||
|
Blocked(u64),
|
||||||
|
/// The outcome is unknown (network, timeout, unexpected answer).
|
||||||
|
Uncertain,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Where reports go.
|
||||||
|
pub trait Service {
|
||||||
|
fn create(&self, title: &str, body: &str) -> std::result::Result<u64, Failure>;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The CoA report service over HTTPS.
|
||||||
|
pub struct ReportService {
|
||||||
|
api: String,
|
||||||
|
key: String,
|
||||||
|
client: reqwest::blocking::Client,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl ReportService {
|
||||||
|
pub fn new(base_url: &str, api_key: &str) -> Result<ReportService> {
|
||||||
|
if api_key.is_empty() || !api_key.is_ascii() || api_key.chars().any(char::is_whitespace) {
|
||||||
|
return Err(Error::Invalid("Configure a valid report-service intake key.".into()));
|
||||||
|
}
|
||||||
|
let client = reqwest::blocking::Client::builder()
|
||||||
|
.redirect(reqwest::redirect::Policy::none())
|
||||||
|
.timeout(Duration::from_secs(30))
|
||||||
|
// One report every few seconds at most: a fresh connection each time, never a stale pooled one.
|
||||||
|
.pool_max_idle_per_host(0)
|
||||||
|
.user_agent("CoA-InGame-BugReport/1")
|
||||||
|
.build()
|
||||||
|
.map_err(|e| Error::Invalid(format!("The report client could not start: {e}")))?;
|
||||||
|
Ok(ReportService { api: format!("{base_url}/v1/reports"), key: api_key.into(), client })
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// `Retry-After` in seconds, kept within 1 s .. 1 day; `default` when absent or not a number.
|
||||||
|
fn retry_delay(retry_after: Option<&str>, default: u64) -> u64 {
|
||||||
|
retry_after.and_then(|v| v.trim().parse::<i64>().ok()).map_or(default, |v| v.clamp(1, 86400) as u64)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A JSON object of at most 64 KiB, or nothing.
|
||||||
|
fn json_object(raw: Option<&[u8]>) -> Option<serde_json::Map<String, serde_json::Value>> {
|
||||||
|
let raw = raw?;
|
||||||
|
if raw.len() > MAX_RESPONSE {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
match serde_json::from_slice(raw).ok()? {
|
||||||
|
serde_json::Value::Object(map) => Some(map),
|
||||||
|
_ => None,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn issue_number(data: &serde_json::Map<String, serde_json::Value>) -> std::result::Result<u64, Failure> {
|
||||||
|
let number = data.get("issue_number").and_then(|n| if n.is_u64() { n.as_u64() } else { None });
|
||||||
|
match number {
|
||||||
|
Some(n)
|
||||||
|
if data.get("status").and_then(|s| s.as_str()) == Some("created")
|
||||||
|
&& (1..=4294967295).contains(&n)
|
||||||
|
&& data.get("issue_url").and_then(|u| u.as_str())
|
||||||
|
== Some(format!("https://github.com/{REPOSITORY}/issues/{n}").as_str()) =>
|
||||||
|
{
|
||||||
|
Ok(n)
|
||||||
|
}
|
||||||
|
_ => Err(Failure::Uncertain),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// What a service answer means (relay.py's `create`): the status, its `Retry-After` and its body (`None` when it
|
||||||
|
/// could not be read or was longer than 64 KiB).
|
||||||
|
pub fn classify(status: u16, retry_after: Option<&str>, body: Option<&[u8]>) -> std::result::Result<u64, Failure> {
|
||||||
|
let field = |data: &serde_json::Map<String, serde_json::Value>, k: &str| data.get(k).and_then(|v| v.as_str()).map(str::to_owned);
|
||||||
|
match status {
|
||||||
|
200..=202 => {
|
||||||
|
let data = json_object(body).ok_or(Failure::Uncertain)?;
|
||||||
|
match status {
|
||||||
|
202 if field(&data, "status").as_deref() == Some("pending") => Err(Failure::Pending(retry_delay(retry_after, 2))),
|
||||||
|
202 => Err(Failure::Uncertain),
|
||||||
|
_ => issue_number(&data),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
429 => Err(Failure::Limited(retry_delay(retry_after, 300))),
|
||||||
|
400 | 413 | 415 | 422 => Err(Failure::Invalid),
|
||||||
|
301 | 302 | 303 | 307 | 308 | 401 | 403 | 404 | 405 => Err(Failure::Blocked(300)),
|
||||||
|
503 => {
|
||||||
|
let data = json_object(body).unwrap_or_default();
|
||||||
|
if field(&data, "status").as_deref() == Some("failed") && field(&data, "error").as_deref() == Some("github_access_denied") {
|
||||||
|
Err(Failure::Blocked(retry_delay(retry_after, 300)))
|
||||||
|
} else {
|
||||||
|
Err(Failure::Uncertain)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
_ => Err(Failure::Uncertain),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Service for ReportService {
|
||||||
|
fn create(&self, title: &str, body: &str) -> std::result::Result<u64, Failure> {
|
||||||
|
use std::io::Read;
|
||||||
|
let sent = self
|
||||||
|
.client
|
||||||
|
.post(&self.api)
|
||||||
|
.header("Authorization", format!("Bearer {}", self.key))
|
||||||
|
.header("Accept", "application/json")
|
||||||
|
.header("Content-Type", "application/json")
|
||||||
|
.body(serde_json::json!({ "title": title, "body": body }).to_string())
|
||||||
|
.send();
|
||||||
|
let response = sent.map_err(|_| Failure::Uncertain)?;
|
||||||
|
let status = response.status().as_u16();
|
||||||
|
let retry_after = response.headers().get("Retry-After").and_then(|v| v.to_str().ok()).map(str::to_owned);
|
||||||
|
let mut raw = Vec::new();
|
||||||
|
let read = response.take(MAX_RESPONSE as u64 + 1).read_to_end(&mut raw).is_ok() && raw.len() <= MAX_RESPONSE;
|
||||||
|
classify(status, retry_after.as_deref(), read.then_some(raw.as_slice()))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A report: `COABUG1\n<title>\n<body>`, checked as the world writes it.
|
||||||
|
pub struct Report {
|
||||||
|
pub digest: String,
|
||||||
|
pub marker: String,
|
||||||
|
pub title: String,
|
||||||
|
pub body: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn read_report(path: &Path) -> Result<Report> {
|
||||||
|
let bad = || Error::Invalid("Invalid report file".into());
|
||||||
|
let key = path.file_stem().and_then(|s| s.to_str()).ok_or_else(bad)?;
|
||||||
|
let meta = std::fs::symlink_metadata(path)?;
|
||||||
|
if !valid_key(key) || meta.file_type().is_symlink() || meta.len() > MAX_FILE {
|
||||||
|
return Err(bad());
|
||||||
|
}
|
||||||
|
let raw = std::fs::read(path)?;
|
||||||
|
let text = String::from_utf8(raw.clone()).map_err(|_| bad())?.replace("\r\n", "\n");
|
||||||
|
let rest = text.strip_prefix("COABUG1\n").ok_or_else(|| Error::Invalid("Unsupported report format".into()))?;
|
||||||
|
let invalid = || Error::Invalid("Invalid report content".into());
|
||||||
|
let (title, body) = rest.split_once('\n').ok_or_else(invalid)?;
|
||||||
|
if !(3..=200).contains(&title.len())
|
||||||
|
|| body.trim().is_empty()
|
||||||
|
|| title.chars().any(|c| (c as u32) < 32)
|
||||||
|
|| body.chars().any(|c| (c as u32) < 32 && !matches!(c, '\r' | '\n' | '\t'))
|
||||||
|
{
|
||||||
|
return Err(invalid());
|
||||||
|
}
|
||||||
|
let digest = hex(&Sha256::digest(&raw));
|
||||||
|
let id = hex(&Sha256::digest(format!("{key}:{digest}").as_bytes()));
|
||||||
|
Ok(Report { digest, marker: format!("<!-- coa-report:{id} -->"), title: title.into(), body: body.into() })
|
||||||
|
}
|
||||||
|
|
||||||
|
fn hex(bytes: &[u8]) -> String {
|
||||||
|
bytes.iter().map(|b| format!("{b:02x}")).collect()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// `<key>.status`: what the world shows the player (`queued`, `created|<issue>`, `failed`, ...).
|
||||||
|
pub fn write_status(spool: &Path, key: &str, state: &str, number: Option<u64>) -> Result<()> {
|
||||||
|
let value = match (state, number) {
|
||||||
|
("created", Some(n)) => format!("created|{n}"),
|
||||||
|
("created", None) => "created|None".into(),
|
||||||
|
_ => state.to_string(),
|
||||||
|
};
|
||||||
|
let data = format!("{value}\n");
|
||||||
|
let destination = spool.join(format!("{key}.status"));
|
||||||
|
if std::fs::read(&destination).is_ok_and(|d| d == data.as_bytes()) {
|
||||||
|
return Ok(());
|
||||||
|
}
|
||||||
|
crate::fsx::atomic_write(&destination, data.as_bytes())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn now() -> f64 {
|
||||||
|
SystemTime::now().duration_since(UNIX_EPOCH).map(|d| d.as_secs_f64()).unwrap_or(0.0)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The delivery journal of one spool.
|
||||||
|
pub struct Relay<S: Service> {
|
||||||
|
spool: PathBuf,
|
||||||
|
service: S,
|
||||||
|
db: Connection,
|
||||||
|
clock: Box<dyn Fn() -> f64 + Send>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<S: Service> Relay<S> {
|
||||||
|
pub fn open(spool: &Path, service: S) -> Result<Relay<S>> {
|
||||||
|
Self::with_clock(spool, service, Box::new(now))
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn with_clock(spool: &Path, service: S, clock: Box<dyn Fn() -> f64 + Send>) -> Result<Relay<S>> {
|
||||||
|
let db = Connection::open(spool.join("relay.sqlite3")).map_err(sql)?;
|
||||||
|
db.execute_batch(
|
||||||
|
"PRAGMA synchronous=FULL;
|
||||||
|
CREATE TABLE IF NOT EXISTS deliveries (
|
||||||
|
key TEXT PRIMARY KEY, digest TEXT NOT NULL, marker TEXT NOT NULL, state TEXT NOT NULL,
|
||||||
|
number INTEGER, attempted REAL NOT NULL DEFAULT 0, next_try REAL NOT NULL DEFAULT 0
|
||||||
|
);
|
||||||
|
CREATE TABLE IF NOT EXISTS settings (key TEXT PRIMARY KEY, value REAL NOT NULL);
|
||||||
|
UPDATE deliveries SET state='uncertain' WHERE state='posting';",
|
||||||
|
)
|
||||||
|
.map_err(sql)?;
|
||||||
|
Ok(Relay { spool: spool.into(), service, db, clock })
|
||||||
|
}
|
||||||
|
|
||||||
|
fn set_state(&self, key: &str, state: &str, number: Option<u64>, delay: u64) -> Result<()> {
|
||||||
|
self.db
|
||||||
|
.execute(
|
||||||
|
"UPDATE deliveries SET state=?1, number=?2, next_try=?3 WHERE key=?4",
|
||||||
|
params![state, number.map(|n| n as i64), (self.clock)() + delay as f64, key],
|
||||||
|
)
|
||||||
|
.map_err(sql)?;
|
||||||
|
write_status(&self.spool, key, state, number)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn set_network_gate(&self, delay: u64) -> Result<()> {
|
||||||
|
self.db
|
||||||
|
.execute("INSERT OR REPLACE INTO settings VALUES('next_network',?1)", params![(self.clock)() + delay as f64])
|
||||||
|
.map_err(sql)?;
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Handle one report file; returns its delivery state.
|
||||||
|
pub fn process(&self, path: &Path) -> Result<String> {
|
||||||
|
let Some(key) = path.file_stem().and_then(|s| s.to_str()).filter(|k| valid_key(k)) else {
|
||||||
|
return Ok("ignored".into());
|
||||||
|
};
|
||||||
|
let report = match read_report(path) {
|
||||||
|
Ok(r) => r,
|
||||||
|
Err(_) => {
|
||||||
|
write_status(&self.spool, key, "failed", None)?;
|
||||||
|
return Ok("failed".into());
|
||||||
|
}
|
||||||
|
};
|
||||||
|
self.db
|
||||||
|
.execute(
|
||||||
|
"INSERT OR IGNORE INTO deliveries(key,digest,marker,state) VALUES(?1,?2,?3,'queued')",
|
||||||
|
params![key, report.digest, report.marker],
|
||||||
|
)
|
||||||
|
.map_err(sql)?;
|
||||||
|
let (digest, row_state, number, next_try): (String, String, Option<i64>, f64) = self
|
||||||
|
.db
|
||||||
|
.query_row("SELECT digest, state, number, next_try FROM deliveries WHERE key=?1", params![key], |r| {
|
||||||
|
Ok((r.get(0)?, r.get(1)?, r.get(2)?, r.get(3)?))
|
||||||
|
})
|
||||||
|
.map_err(sql)?;
|
||||||
|
let number = number.map(|n| n as u64);
|
||||||
|
if digest != report.digest {
|
||||||
|
// Never replace an existing delivery or publish edited content under the same ID.
|
||||||
|
write_status(&self.spool, key, "failed", None)?;
|
||||||
|
return Ok("changed".into());
|
||||||
|
}
|
||||||
|
if matches!(row_state.as_str(), "created" | "failed" | "uncertain") {
|
||||||
|
write_status(&self.spool, key, &row_state, number)?;
|
||||||
|
return Ok(row_state);
|
||||||
|
}
|
||||||
|
if next_try > (self.clock)() {
|
||||||
|
write_status(&self.spool, key, &row_state, None)?;
|
||||||
|
return Ok(row_state);
|
||||||
|
}
|
||||||
|
let gate: Option<f64> = self
|
||||||
|
.db
|
||||||
|
.query_row("SELECT value FROM settings WHERE key='next_network'", [], |r| r.get(0))
|
||||||
|
.optional()
|
||||||
|
.map_err(sql)?;
|
||||||
|
if gate.is_some_and(|g| g > (self.clock)()) {
|
||||||
|
write_status(&self.spool, key, &row_state, None)?;
|
||||||
|
return Ok(row_state);
|
||||||
|
}
|
||||||
|
self.set_network_gate(5)?;
|
||||||
|
// A crash after this point needs review: the service's duplicate cache can reset on deploy.
|
||||||
|
self.db
|
||||||
|
.execute("UPDATE deliveries SET state='posting', attempted=?1 WHERE key=?2", params![(self.clock)(), key])
|
||||||
|
.map_err(sql)?;
|
||||||
|
match self.service.create(&report.title, &report.body) {
|
||||||
|
Ok(n) => {
|
||||||
|
self.set_state(key, "created", Some(n), 0)?;
|
||||||
|
Ok("created".into())
|
||||||
|
}
|
||||||
|
Err(failure) => {
|
||||||
|
let (state, delay) = match failure {
|
||||||
|
Failure::Limited(d) | Failure::Pending(d) => ("queued", d),
|
||||||
|
Failure::Blocked(d) => ("blocked", d),
|
||||||
|
Failure::Invalid => ("failed", 300),
|
||||||
|
Failure::Uncertain => ("uncertain", 300),
|
||||||
|
};
|
||||||
|
self.set_state(key, state, None, delay)?;
|
||||||
|
if let Failure::Limited(d) | Failure::Blocked(d) = failure {
|
||||||
|
self.set_network_gate(d)?;
|
||||||
|
}
|
||||||
|
Ok(state.into())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// One pass over the spool, in name order.
|
||||||
|
pub fn pass(&self) -> Result<()> {
|
||||||
|
let mut reports: Vec<PathBuf> = std::fs::read_dir(&self.spool)?
|
||||||
|
.flatten()
|
||||||
|
.map(|e| e.path())
|
||||||
|
.filter(|p| p.extension().is_some_and(|x| x == "report"))
|
||||||
|
.collect();
|
||||||
|
reports.sort();
|
||||||
|
for path in reports {
|
||||||
|
self.process(&path)?;
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn sql(e: rusqlite::Error) -> Error {
|
||||||
|
Error::Invalid(format!("The bug-report journal failed ({e})."))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// `relay-worker`: deliver reports until the supervisor asks the relay to stop (`.state/stop-relay`).
|
||||||
|
pub fn worker(root: &Path) -> Result<()> {
|
||||||
|
let spool = root.join("BugReport/reports");
|
||||||
|
std::fs::create_dir_all(&spool)?;
|
||||||
|
let _lock = state::FileLock::try_acquire(&spool.join("relay.lock"))?
|
||||||
|
.ok_or_else(|| Error::Invalid("Another bug-report relay is already using this spool.".into()))?;
|
||||||
|
let key = std::env::var("COA_BUGREPORT_API_KEY").unwrap_or_else(|_| DEFAULT_API_KEY.into());
|
||||||
|
let relay = Relay::open(&spool, ReportService::new(SERVICE_URL, &key)?)?;
|
||||||
|
state::record(root, "relay-ready", std::process::id())?;
|
||||||
|
println!("Bug-report relay ready. Waiting for in-game reports.");
|
||||||
|
let stop = state::dir(root).join("stop-relay");
|
||||||
|
while !stop.exists() {
|
||||||
|
relay.pass()?;
|
||||||
|
for _ in 0..10 {
|
||||||
|
if stop.exists() {
|
||||||
|
return Ok(());
|
||||||
|
}
|
||||||
|
std::thread::sleep(Duration::from_millis(500));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
use std::sync::{Arc, Mutex};
|
||||||
|
|
||||||
|
type Answers = Arc<Mutex<Vec<std::result::Result<u64, Failure>>>>;
|
||||||
|
|
||||||
|
struct Fake(Answers, Arc<Mutex<u32>>);
|
||||||
|
impl Service for Fake {
|
||||||
|
fn create(&self, _: &str, _: &str) -> std::result::Result<u64, Failure> {
|
||||||
|
*self.1.lock().unwrap() += 1;
|
||||||
|
self.0.lock().unwrap().remove(0)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn report(spool: &Path, key: &str, text: &str) -> PathBuf {
|
||||||
|
let p = spool.join(format!("{key}.report"));
|
||||||
|
std::fs::write(&p, text).unwrap();
|
||||||
|
p
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn keys_follow_the_world_format() {
|
||||||
|
assert!(valid_key("1-0123456789abcdef"));
|
||||||
|
assert!(valid_key("4294967295-0123456789abcdef0123456789abcdef0123456789abcdef"));
|
||||||
|
for bad in ["0-0123456789abcdef", "1-0123456789abcde", "1-0123456789ABCDEF", "12345678901-0123456789abcdef", "x"] {
|
||||||
|
assert!(!valid_key(bad), "{bad}");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn service_answers_map_like_relay_py() {
|
||||||
|
let ok = format!(r#"{{"status":"created","issue_number":12,"issue_url":"https://github.com/{REPOSITORY}/issues/12"}}"#);
|
||||||
|
let cases: Vec<(u16, Option<&str>, Option<&[u8]>, std::result::Result<u64, Failure>)> = vec![
|
||||||
|
(201, None, Some(ok.as_bytes()), Ok(12)),
|
||||||
|
(200, None, Some(ok.as_bytes()), Ok(12)),
|
||||||
|
(201, None, Some(br#"{"status":"created","issue_number":12,"issue_url":"https://evil/12"}"#), Err(Failure::Uncertain)),
|
||||||
|
(201, None, Some(br#"{"status":"created","issue_number":0,"issue_url":"x"}"#), Err(Failure::Uncertain)),
|
||||||
|
(201, None, Some(b"[1]"), Err(Failure::Uncertain)),
|
||||||
|
(201, None, None, Err(Failure::Uncertain)),
|
||||||
|
(202, Some("7"), Some(br#"{"status":"pending"}"#), Err(Failure::Pending(7))),
|
||||||
|
(202, None, Some(br#"{"status":"pending"}"#), Err(Failure::Pending(2))),
|
||||||
|
(202, None, Some(br#"{"status":"other"}"#), Err(Failure::Uncertain)),
|
||||||
|
(429, Some("999999"), None, Err(Failure::Limited(86400))),
|
||||||
|
(429, Some("0"), None, Err(Failure::Limited(1))),
|
||||||
|
(429, Some("soon"), None, Err(Failure::Limited(300))),
|
||||||
|
(422, None, None, Err(Failure::Invalid)),
|
||||||
|
(302, None, None, Err(Failure::Blocked(300))),
|
||||||
|
(401, None, None, Err(Failure::Blocked(300))),
|
||||||
|
(503, Some("30"), Some(br#"{"status":"failed","error":"github_access_denied"}"#), Err(Failure::Blocked(30))),
|
||||||
|
(503, None, Some(b"{}"), Err(Failure::Uncertain)),
|
||||||
|
(500, None, None, Err(Failure::Uncertain)),
|
||||||
|
];
|
||||||
|
for (i, (status, retry, body, expected)) in cases.into_iter().enumerate() {
|
||||||
|
assert_eq!(classify(status, retry, body), expected, "case {i}");
|
||||||
|
}
|
||||||
|
assert!(json_object(Some(&vec![b' '; MAX_RESPONSE + 1])).is_none(), "oversized answers are refused");
|
||||||
|
assert!(ReportService::new(SERVICE_URL, "has space").is_err());
|
||||||
|
assert!(ReportService::new(SERVICE_URL, "coa_key").is_ok());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_report_is_checked_and_identified_like_relay_py() {
|
||||||
|
let d = tempfile::tempdir().unwrap();
|
||||||
|
let p = report(d.path(), "7-0123456789abcdef", "COABUG1\r\nBroken quest\r\nThe NPC is missing.\r\n");
|
||||||
|
let r = read_report(&p).unwrap();
|
||||||
|
assert_eq!(r.title, "Broken quest");
|
||||||
|
assert_eq!(r.body, "The NPC is missing.\n");
|
||||||
|
assert_eq!(r.digest, hex(&Sha256::digest(std::fs::read(&p).unwrap())));
|
||||||
|
assert!(r.marker.starts_with("<!-- coa-report:") && r.marker.len() == 16 + 64 + 4);
|
||||||
|
for bad in ["COABUG2\nTitle\nBody", "COABUG1\nab\nBody", "COABUG1\nTitle\n \n", "COABUG1\nTi\u{7}tle\nBody", "COABUG1\nTitle"] {
|
||||||
|
std::fs::write(&p, bad).unwrap();
|
||||||
|
assert!(read_report(&p).is_err(), "{bad:?}");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn deliveries_follow_the_journal() {
|
||||||
|
let d = tempfile::tempdir().unwrap();
|
||||||
|
let spool = d.path();
|
||||||
|
let t = Arc::new(Mutex::new(1000.0f64));
|
||||||
|
let calls = Arc::new(Mutex::new(0));
|
||||||
|
let answers: Answers = Arc::new(Mutex::new(vec![Err(Failure::Limited(60)), Ok(42)]));
|
||||||
|
let clock = t.clone();
|
||||||
|
let relay = Relay::with_clock(spool, Fake(answers, calls.clone()), Box::new(move || *clock.lock().unwrap())).unwrap();
|
||||||
|
let p = report(spool, "7-0123456789abcdef", "COABUG1\nBroken quest\nThe NPC is missing.\n");
|
||||||
|
let status = || std::fs::read_to_string(spool.join("7-0123456789abcdef.status")).unwrap();
|
||||||
|
assert_eq!(relay.process(&p).unwrap(), "queued", "429 keeps it queued");
|
||||||
|
assert_eq!(status(), "queued\n");
|
||||||
|
assert_eq!(relay.process(&p).unwrap(), "queued", "not before its retry time");
|
||||||
|
assert_eq!(*calls.lock().unwrap(), 1);
|
||||||
|
*t.lock().unwrap() += 61.0;
|
||||||
|
assert_eq!(relay.process(&p).unwrap(), "created");
|
||||||
|
assert_eq!(status(), "created|42\n");
|
||||||
|
assert_eq!(relay.process(&p).unwrap(), "created", "never sent twice");
|
||||||
|
assert_eq!(*calls.lock().unwrap(), 2);
|
||||||
|
std::fs::write(&p, "COABUG1\nBroken quest\nEdited.\n").unwrap();
|
||||||
|
assert_eq!(relay.process(&p).unwrap(), "changed");
|
||||||
|
relay
|
||||||
|
.db
|
||||||
|
.execute("INSERT INTO deliveries(key,digest,marker,state) VALUES('8-0123456789abcdef','x','m','posting')", [])
|
||||||
|
.unwrap();
|
||||||
|
drop(relay);
|
||||||
|
let reopened = Relay::open(spool, Fake(Arc::new(Mutex::new(vec![])), calls.clone())).unwrap();
|
||||||
|
let state: String =
|
||||||
|
reopened.db.query_row("SELECT state FROM deliveries WHERE key='8-0123456789abcdef'", [], |r| r.get(0)).unwrap();
|
||||||
|
assert_eq!(state, "uncertain", "an interrupted post is never retried");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_second_worker_cannot_take_the_spool() {
|
||||||
|
let d = tempfile::tempdir().unwrap();
|
||||||
|
let first = state::FileLock::try_acquire(&d.path().join("relay.lock")).unwrap();
|
||||||
|
assert!(first.is_some());
|
||||||
|
assert!(state::FileLock::try_acquire(&d.path().join("relay.lock")).unwrap().is_none());
|
||||||
|
drop(first);
|
||||||
|
assert!(state::FileLock::try_acquire(&d.path().join("relay.lock")).unwrap().is_some());
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,271 @@
|
|||||||
|
//! `prepare`: the configuration files a repack runs with, rendered from `Settings/*.template` and
|
||||||
|
//! `Settings/repack.json` (`manage.py prepare()`), byte for byte the same.
|
||||||
|
|
||||||
|
use std::path::{Path, PathBuf};
|
||||||
|
|
||||||
|
use crate::error::{Error, Result};
|
||||||
|
use crate::launcher::{settings::Settings, state};
|
||||||
|
|
||||||
|
/// Services whose running process blocks moving the folder or changing ports.
|
||||||
|
const SERVICES: [&str; 5] = ["mysql", "auth", "world", "supervisor", "relay"];
|
||||||
|
|
||||||
|
/// The root as the servers see it: forward slashes, and the short (8.3) form when the real one has non-Latin
|
||||||
|
/// letters, which MySQL and the servers do not read reliably from their config files.
|
||||||
|
pub fn native_root(root: &Path) -> Result<String> {
|
||||||
|
let mut value = root.to_string_lossy().into_owned();
|
||||||
|
if !value.is_ascii() {
|
||||||
|
if let Some(short) = sys::short_path(root) {
|
||||||
|
value = short;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if !value.is_ascii() {
|
||||||
|
return Err(Error::Invalid(
|
||||||
|
"Extract the repack to a path with Latin letters, such as C:\\Games\\CoA-Repack.".into(),
|
||||||
|
));
|
||||||
|
}
|
||||||
|
Ok(value.replace('\\', "/"))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Text as Python's text mode reads it: strict UTF-8, Windows and old Mac line ends turned into "\n".
|
||||||
|
fn read_text(path: &Path) -> Result<String> {
|
||||||
|
let bytes = std::fs::read(path)?;
|
||||||
|
let text = String::from_utf8(bytes).map_err(|_| Error::Invalid(format!("{} is not UTF-8 text.", path.display())))?;
|
||||||
|
Ok(text.replace("\r\n", "\n").replace('\r', "\n"))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Text written as Python's text mode writes it on Windows: "\n" becomes "\r\n".
|
||||||
|
fn windows_text(text: &str) -> Vec<u8> {
|
||||||
|
if cfg!(windows) {
|
||||||
|
text.replace('\n', "\r\n").into_bytes()
|
||||||
|
} else {
|
||||||
|
text.as_bytes().to_vec()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn placeholders(line: &str) -> Vec<String> {
|
||||||
|
let mut out = Vec::new();
|
||||||
|
let bytes = line.as_bytes();
|
||||||
|
let mut i = 0;
|
||||||
|
while i < bytes.len() {
|
||||||
|
if bytes[i] == b'@' {
|
||||||
|
let mut j = i + 1;
|
||||||
|
while j < bytes.len() && (bytes[j].is_ascii_alphabetic() || bytes[j] == b'_') {
|
||||||
|
j += 1;
|
||||||
|
}
|
||||||
|
if j < bytes.len() && j > i + 1 && bytes[j] == b'@' {
|
||||||
|
out.push(line[i..=j].to_string());
|
||||||
|
i = j + 1;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
i += 1;
|
||||||
|
}
|
||||||
|
out
|
||||||
|
}
|
||||||
|
|
||||||
|
fn credentials(root: &Path) -> Result<(String, String)> {
|
||||||
|
let v: serde_json::Value = crate::fsx::read_json(&root.join("Settings/database.json"))?;
|
||||||
|
let good = |k: &str| {
|
||||||
|
v.get(k)
|
||||||
|
.and_then(|x| x.as_str())
|
||||||
|
.filter(|s| s.len() == 48 && s.bytes().all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b)))
|
||||||
|
.map(str::to_string)
|
||||||
|
};
|
||||||
|
match (good("rootPassword"), good("appPassword")) {
|
||||||
|
(Some(r), Some(a)) => Ok((r, a)),
|
||||||
|
_ => Err(Error::Invalid("Invalid packaged database configuration.".into())),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Render every file the repack's services read. Refuses while a service runs and the folder or the ports
|
||||||
|
/// changed since the last render.
|
||||||
|
pub fn prepare(root: &Path, config: &Settings) -> Result<Vec<PathBuf>> {
|
||||||
|
let base = native_root(root)?;
|
||||||
|
let signature = serde_json::json!({
|
||||||
|
"root": root.to_string_lossy(),
|
||||||
|
"ports": serde_json::Value::Object(config.port_map()),
|
||||||
|
});
|
||||||
|
let previous = state::dir(root).join("configuration.json");
|
||||||
|
if previous.exists() {
|
||||||
|
let recorded: Option<serde_json::Value> = crate::fsx::read_json(&previous).ok();
|
||||||
|
if recorded.as_ref() != Some(&signature) && SERVICES.iter().any(|s| state::running(root, s).is_some()) {
|
||||||
|
return Err(Error::Invalid("Stop this repack before moving its folder or changing its ports.".into()));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let (root_password, app_password) = credentials(root)?;
|
||||||
|
for folder in ["Core/configs/modules", "Core/Logs", "BugReport/reports", "BugReport/Logs", "mysql/logs", ".state"] {
|
||||||
|
std::fs::create_dir_all(root.join(folder))?;
|
||||||
|
}
|
||||||
|
let mysql_port = config.mysql_port;
|
||||||
|
let mut values: Vec<(&str, String)> = vec![
|
||||||
|
("DATA", format!("{base}/Data")),
|
||||||
|
("LOGS", format!("{base}/Core/Logs")),
|
||||||
|
("ASCENSION_DBC", format!("{base}/Data/dbc/Ascension")),
|
||||||
|
("MYSQL_EXE", format!("{base}/mysql/bin/mysql.exe")),
|
||||||
|
("AUTH_PORT", config.auth_port.to_string()),
|
||||||
|
("WORLD_PORT", config.world_port.to_string()),
|
||||||
|
("RA_PORT", config.ra_port.to_string()),
|
||||||
|
];
|
||||||
|
for (key, db) in [
|
||||||
|
("LoginDatabaseInfo", "acore_auth"),
|
||||||
|
("WorldDatabaseInfo", config.realm.world_db),
|
||||||
|
("CharacterDatabaseInfo", config.realm.characters_db),
|
||||||
|
] {
|
||||||
|
values.push((key, format!("127.0.0.1;{mysql_port};acore;{app_password};{db}")));
|
||||||
|
}
|
||||||
|
let mut written = Vec::new();
|
||||||
|
for (name, target) in [
|
||||||
|
("authserver.conf", "Core/configs/authserver.conf"),
|
||||||
|
("worldserver.conf", "Core/configs/worldserver.conf"),
|
||||||
|
("mod_ascension_compat.conf", "Core/configs/modules/mod_ascension_compat.conf"),
|
||||||
|
] {
|
||||||
|
let mut text = read_text(&root.join("Settings").join(format!("{name}.template")))?;
|
||||||
|
for (key, value) in &values {
|
||||||
|
text = text.replace(&format!("@{key}@"), value);
|
||||||
|
}
|
||||||
|
let mut unresolved: Vec<String> = text
|
||||||
|
.split('\n')
|
||||||
|
.filter(|l| !l.trim().is_empty() && !l.trim_start().starts_with('#'))
|
||||||
|
.flat_map(placeholders)
|
||||||
|
.collect();
|
||||||
|
unresolved.sort();
|
||||||
|
unresolved.dedup();
|
||||||
|
if !unresolved.is_empty() {
|
||||||
|
return Err(Error::Service(
|
||||||
|
crate::error::ErrorCode::InvalidConfigValue,
|
||||||
|
format!("An unresolved placeholder remains in Settings/{name}.template: {}", unresolved.join(", ")),
|
||||||
|
));
|
||||||
|
}
|
||||||
|
// these three keep "\n" (Python wrote them with newline="\n")
|
||||||
|
std::fs::write(root.join(target), text.as_bytes())?;
|
||||||
|
written.push(root.join(target));
|
||||||
|
}
|
||||||
|
let files: [(&str, String); 3] = [
|
||||||
|
(
|
||||||
|
"Core/configs/modules/coa_bugreport.conf",
|
||||||
|
format!(
|
||||||
|
"# Managed by the repack launcher. Enabled whenever worldserver starts.\nCoABugReport.Enable = 1\nCoABugReport.SpoolDirectory = \"{base}/BugReport/reports\"\nCoABugReport.CooldownSeconds = 120\n"
|
||||||
|
),
|
||||||
|
),
|
||||||
|
(
|
||||||
|
"mysql/my.ini",
|
||||||
|
format!(
|
||||||
|
"[mysqld]\nbasedir=\"{base}/mysql\"\ndatadir=\"{base}/mysql/data\"\nport={mysql_port}\nbind-address=127.0.0.1\nmysqlx=0\ncharacter-set-server=utf8mb4\ncollation-server=utf8mb4_unicode_ci\nmax_allowed_packet=128M\ninnodb_buffer_pool_size=256M\nskip-log-bin\nlog-error=\"{base}/mysql/logs/mysql-error.log\"\npid-file=\"{base}/mysql/mysql.pid\"\n"
|
||||||
|
),
|
||||||
|
),
|
||||||
|
(
|
||||||
|
"mysql/admin-client.ini",
|
||||||
|
format!(
|
||||||
|
"[client]\nuser=root\npassword={root_password}\nhost=127.0.0.1\nport={mysql_port}\nprotocol=tcp\ndefault-character-set=utf8mb4\n"
|
||||||
|
),
|
||||||
|
),
|
||||||
|
];
|
||||||
|
for (rel, text) in files {
|
||||||
|
std::fs::write(root.join(rel), windows_text(&text))?;
|
||||||
|
written.push(root.join(rel));
|
||||||
|
}
|
||||||
|
state::write_json(&previous, &signature)?;
|
||||||
|
Ok(written)
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(windows)]
|
||||||
|
mod sys {
|
||||||
|
use std::os::windows::ffi::OsStrExt;
|
||||||
|
use std::path::Path;
|
||||||
|
use windows_sys::Win32::Storage::FileSystem::GetShortPathNameW;
|
||||||
|
|
||||||
|
pub fn short_path(path: &Path) -> Option<String> {
|
||||||
|
let wide: Vec<u16> = path.as_os_str().encode_wide().chain(Some(0)).collect();
|
||||||
|
let mut buf = vec![0u16; 32768];
|
||||||
|
let n = unsafe { GetShortPathNameW(wide.as_ptr(), buf.as_mut_ptr(), buf.len() as u32) };
|
||||||
|
(n > 0 && (n as usize) < buf.len()).then(|| String::from_utf16_lossy(&buf[..n as usize]))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(not(windows))]
|
||||||
|
mod sys {
|
||||||
|
pub fn short_path(_: &std::path::Path) -> Option<String> {
|
||||||
|
None
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
|
||||||
|
pub(crate) fn fixture(root: &Path) {
|
||||||
|
let w = |rel: &str, text: &[u8]| {
|
||||||
|
let p = root.join(rel);
|
||||||
|
std::fs::create_dir_all(p.parent().unwrap()).unwrap();
|
||||||
|
std::fs::write(p, text).unwrap();
|
||||||
|
};
|
||||||
|
w("Settings/repack.json", br#"{"authPort": 3724, "mysqlPort": 3307, "raPassword": "e0c39beaa5c14128", "raPort": 3443, "raUsername": "COAMANAGER", "worldPort": 8085}"#);
|
||||||
|
w("Settings/database.json", format!(r#"{{"rootPassword": "{}", "appPassword": "{}"}}"#, "a".repeat(48), "0123456789abcdef".repeat(3)).as_bytes());
|
||||||
|
w("Settings/authserver.conf.template", b"[authserver]\r\nLoginDatabaseInfo = \"@LoginDatabaseInfo@\"\r\nRealmServerPort = @AUTH_PORT@\r\nLogsDir = \"@LOGS@\"\r\n# @NOT_A_VALUE@ in a comment is fine\r\n");
|
||||||
|
w("Settings/worldserver.conf.template", "[worldserver]\nDataDir = \"@DATA@\"\nWorldServerPort = @WORLD_PORT@\nRa.Port = @RA_PORT@\nWorldDatabaseInfo = \"@WorldDatabaseInfo@\"\nCharacterDatabaseInfo = \"@CharacterDatabaseInfo@\"\nMySQLExecutable = \"@MYSQL_EXE@\"\nMotd = \"Ünïcode stays\"\n".as_bytes());
|
||||||
|
w("Settings/mod_ascension_compat.conf.template", b"Ascension.DbcDir = \"@ASCENSION_DBC@\"\rOld.Mac = 1\r");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn placeholders_left_outside_comments_are_refused() {
|
||||||
|
let d = tempfile::tempdir().unwrap();
|
||||||
|
fixture(d.path());
|
||||||
|
std::fs::write(d.path().join("Settings/worldserver.conf.template"), "A = @UNKNOWN@\n").unwrap();
|
||||||
|
let cfg = Settings::load(d.path(), 0).unwrap();
|
||||||
|
let err = prepare(d.path(), &cfg).unwrap_err().to_string();
|
||||||
|
assert!(err.contains("worldserver.conf.template: @UNKNOWN@"), "{err}");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_bad_password_file_is_refused() {
|
||||||
|
let d = tempfile::tempdir().unwrap();
|
||||||
|
fixture(d.path());
|
||||||
|
std::fs::write(d.path().join("Settings/database.json"), r#"{"rootPassword":"short","appPassword":"x"}"#).unwrap();
|
||||||
|
let cfg = Settings::load(d.path(), 0).unwrap();
|
||||||
|
assert!(prepare(d.path(), &cfg).unwrap_err().to_string().contains("Invalid packaged database configuration"));
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Byte-for-byte the same files as the Python launcher. COA_MANAGE_PY = a manage.py to compare with (taken from
|
||||||
|
/// coa-server-build); skipped without it.
|
||||||
|
#[test]
|
||||||
|
fn renders_exactly_what_manage_py_renders() {
|
||||||
|
let Ok(manage) = std::env::var("COA_MANAGE_PY") else { return };
|
||||||
|
let python = std::env::var("COA_PYTHON").unwrap_or_else(|_| "python".into());
|
||||||
|
let rust = tempfile::tempdir().unwrap();
|
||||||
|
let py = tempfile::tempdir().unwrap();
|
||||||
|
for d in [rust.path(), py.path()] {
|
||||||
|
fixture(d);
|
||||||
|
}
|
||||||
|
std::fs::create_dir_all(py.path().join("Scripts")).unwrap();
|
||||||
|
std::fs::copy(&manage, py.path().join("Scripts/manage.py")).unwrap();
|
||||||
|
// manage.py imports squid_playerbots lazily; prepare does not need it.
|
||||||
|
let out = std::process::Command::new(&python)
|
||||||
|
.args(["-I", "-B"])
|
||||||
|
.arg(py.path().join("Scripts/manage.py"))
|
||||||
|
.arg("prepare")
|
||||||
|
.output()
|
||||||
|
.unwrap();
|
||||||
|
assert!(out.status.success(), "{}{}", String::from_utf8_lossy(&out.stdout), String::from_utf8_lossy(&out.stderr));
|
||||||
|
let cfg = Settings::load(rust.path(), 0).unwrap();
|
||||||
|
let written = prepare(rust.path(), &cfg).unwrap();
|
||||||
|
let root_text = |p: &Path, base: &Path| {
|
||||||
|
let n = native_root(base).unwrap();
|
||||||
|
String::from_utf8(std::fs::read(p).unwrap()).unwrap().replace(&n, "<ROOT>")
|
||||||
|
};
|
||||||
|
for file in &written {
|
||||||
|
let rel = file.strip_prefix(rust.path()).unwrap();
|
||||||
|
assert_eq!(
|
||||||
|
root_text(file, rust.path()),
|
||||||
|
root_text(&py.path().join(rel), py.path()),
|
||||||
|
"{} differs",
|
||||||
|
rel.display()
|
||||||
|
);
|
||||||
|
}
|
||||||
|
let sig = |base: &Path| -> serde_json::Value {
|
||||||
|
let mut v: serde_json::Value = crate::fsx::read_json(&base.join(".state/configuration.json")).unwrap();
|
||||||
|
v["root"] = serde_json::Value::Null;
|
||||||
|
v
|
||||||
|
};
|
||||||
|
assert_eq!(sig(rust.path()), sig(py.path()));
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,571 @@
|
|||||||
|
//! Starting, checking and stopping the services of one repack: MySQL, authserver, worldserver
|
||||||
|
//! (`manage.py start_mysql`, `start_auth`, `stop_all` and their helpers), with the same rules.
|
||||||
|
|
||||||
|
use std::net::{SocketAddr, TcpStream};
|
||||||
|
use std::path::{Path, PathBuf};
|
||||||
|
use std::process::{Command, Stdio};
|
||||||
|
use std::time::{Duration, Instant};
|
||||||
|
|
||||||
|
use crate::error::{Error, ErrorCode, Result};
|
||||||
|
use crate::launcher::{settings::Settings, state};
|
||||||
|
use crate::process::ProcessIdentity;
|
||||||
|
|
||||||
|
pub type Progress<'a> = &'a dyn Fn(&str);
|
||||||
|
|
||||||
|
const CREATE_NO_WINDOW: u32 = 0x0800_0000;
|
||||||
|
const CREATE_NEW_PROCESS_GROUP: u32 = 0x0000_0200;
|
||||||
|
|
||||||
|
fn hidden(cmd: &mut Command) -> &mut Command {
|
||||||
|
#[cfg(windows)]
|
||||||
|
{
|
||||||
|
use std::os::windows::process::CommandExt;
|
||||||
|
cmd.creation_flags(CREATE_NO_WINDOW | CREATE_NEW_PROCESS_GROUP);
|
||||||
|
}
|
||||||
|
cmd
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Start `exe` with its output appended to `log`, and record it as `name`. `env_remove` are variables of this
|
||||||
|
/// process the service must not see.
|
||||||
|
pub fn spawn(root: &Path, name: &str, exe: &Path, args: &[&str], cwd: &Path, log: &Path, env_remove: &[String]) -> Result<ProcessIdentity> {
|
||||||
|
let child = crate::launcher::spawn::start(exe, args, cwd, log, env_remove)?;
|
||||||
|
state::record(root, name, child.pid)
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------------------------------------------------------
|
||||||
|
// Ports
|
||||||
|
// ---------------------------------------------------------------------------------------------------------------
|
||||||
|
|
||||||
|
/// Wait (up to 30 s) until `port` can be bound by a new server. A port with a listening owner is refused at
|
||||||
|
/// once; a port Windows still holds for a stopped process (a PID-zero row) is waited for. The test bind is
|
||||||
|
/// exclusive (`SO_EXCLUSIVEADDRUSE`), never a shared one.
|
||||||
|
pub fn ensure_free(port: u16, progress: Progress) -> Result<()> {
|
||||||
|
let deadline = Instant::now() + Duration::from_secs(30);
|
||||||
|
let mut announced = false;
|
||||||
|
loop {
|
||||||
|
let mut owners: Vec<u32> = sys::tcp_rows_v4()
|
||||||
|
.into_iter()
|
||||||
|
.filter(|r| r.state == sys::LISTEN && r.local_port == port)
|
||||||
|
.map(|r| r.pid)
|
||||||
|
.collect();
|
||||||
|
owners.sort_unstable();
|
||||||
|
owners.dedup();
|
||||||
|
if owners.iter().any(|p| *p != 0) {
|
||||||
|
let list: Vec<String> = owners.iter().map(u32::to_string).collect();
|
||||||
|
return Err(Error::Service(
|
||||||
|
ErrorCode::PortInUse,
|
||||||
|
format!("Port {port} is already used (PID {}). Stop the other server or change Settings/repack.json.", list.join(", ")),
|
||||||
|
));
|
||||||
|
}
|
||||||
|
match sys::exclusive_bind(port) {
|
||||||
|
Ok(()) => return Ok(()),
|
||||||
|
Err(code) if code == 10013 || code == 10048 => {
|
||||||
|
if Instant::now() >= deadline {
|
||||||
|
return Err(Error::Invalid(format!(
|
||||||
|
"Port {port} remains unavailable after 30 seconds (Windows bind error {code}). No process was stopped. Retry after the previous database shutdown has finished, or check the Windows port reservation."
|
||||||
|
)));
|
||||||
|
}
|
||||||
|
if !announced {
|
||||||
|
progress(&format!("Waiting for Windows to release port {port}..."));
|
||||||
|
announced = true;
|
||||||
|
}
|
||||||
|
std::thread::sleep(Duration::from_millis(250));
|
||||||
|
}
|
||||||
|
Err(code) => return Err(Error::Invalid(format!("Port {port} cannot be checked (Windows error {code})."))),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Is the recorded process of `name` serving `port`? Its listener row is the evidence; when a system does not
|
||||||
|
/// show the owner of a listener, the server side of a fresh loopback connection is (never for MySQL, whose
|
||||||
|
/// listener has always been visible and which should not get stray connections).
|
||||||
|
pub fn ready(root: &Path, name: &str, port: u16) -> bool {
|
||||||
|
let Some(record) = state::running(root, name) else { return false };
|
||||||
|
let listening = sys::tcp_rows_v4().iter().any(|r| r.state == sys::LISTEN && r.local_port == port && r.pid == record.pid);
|
||||||
|
if listening {
|
||||||
|
return crate::process::is_alive(&record);
|
||||||
|
}
|
||||||
|
if name == "mysql" {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
accepted_by(port, record.pid) && crate::process::is_alive(&record)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Connect to 127.0.0.1:`port` and check that exactly one established server-side row, owned by `pid`, answers
|
||||||
|
/// that connection.
|
||||||
|
fn accepted_by(port: u16, pid: u32) -> bool {
|
||||||
|
let addr: SocketAddr = ([127, 0, 0, 1], port).into();
|
||||||
|
let Ok(client) = TcpStream::connect_timeout(&addr, Duration::from_millis(500)) else { return false };
|
||||||
|
let Ok(mine) = client.local_addr().map(|a| a.port()) else { return false };
|
||||||
|
let me = std::process::id();
|
||||||
|
let rows: Vec<sys::TcpRow> = sys::tcp_rows_v4()
|
||||||
|
.into_iter()
|
||||||
|
.chain(sys::tcp_rows_v6())
|
||||||
|
.filter(|r| r.remote_port == mine && r.remote_loopback && !(r.local_port == mine && r.pid == me))
|
||||||
|
.collect();
|
||||||
|
rows.len() == 1 && rows[0].state == sys::ESTABLISHED && rows[0].pid == pid
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn wait_ready(root: &Path, name: &str, port: u16, seconds: u64) -> Result<()> {
|
||||||
|
let until = Instant::now() + Duration::from_secs(seconds);
|
||||||
|
while Instant::now() < until {
|
||||||
|
if ready(root, name, port) {
|
||||||
|
return Ok(());
|
||||||
|
}
|
||||||
|
if state::running(root, name).is_none() {
|
||||||
|
return Err(Error::Service(ErrorCode::StartupFailed, format!("{name} stopped during startup. Check its log.")));
|
||||||
|
}
|
||||||
|
std::thread::sleep(Duration::from_millis(500));
|
||||||
|
}
|
||||||
|
Err(Error::Service(
|
||||||
|
ErrorCode::StartupFailed,
|
||||||
|
format!("{name} is still starting: its expected TCP listener on port {port} was not found; check its log."),
|
||||||
|
))
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------------------------------------------------------
|
||||||
|
// MySQL client
|
||||||
|
// ---------------------------------------------------------------------------------------------------------------
|
||||||
|
|
||||||
|
/// Run SQL (or a `mysqladmin` command) with the repack's own client and administrator login.
|
||||||
|
pub fn mysql(root: &Path, sql: Option<&str>, admin: Option<&str>) -> Result<String> {
|
||||||
|
let exe = root.join(if admin.is_some() { "mysql/bin/mysqladmin.exe" } else { "mysql/bin/mysql.exe" });
|
||||||
|
let defaults = format!("--defaults-file={}", root.join("mysql/admin-client.ini").display());
|
||||||
|
let mut cmd = Command::new(exe);
|
||||||
|
hidden(&mut cmd).arg(defaults);
|
||||||
|
match admin {
|
||||||
|
Some(a) => cmd.arg(a),
|
||||||
|
None => cmd.args(["--batch", "--skip-column-names"]),
|
||||||
|
};
|
||||||
|
let payload = sql.map(|s| s.as_bytes().to_vec());
|
||||||
|
let timeout = if payload.as_ref().is_some_and(|p| p.len() > 1024 * 1024) { 900 } else { 90 };
|
||||||
|
cmd.stdin(if payload.is_some() { Stdio::piped() } else { Stdio::null() }).stdout(Stdio::piped()).stderr(Stdio::piped());
|
||||||
|
let mut child = cmd.spawn()?;
|
||||||
|
if let (Some(data), Some(mut stdin)) = (payload, child.stdin.take()) {
|
||||||
|
std::thread::spawn(move || {
|
||||||
|
use std::io::Write;
|
||||||
|
let _ = stdin.write_all(&data);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
// Both outputs are read while the client runs: a full pipe would stop it (and look like a timeout).
|
||||||
|
let read = |pipe: Option<Box<dyn std::io::Read + Send>>| {
|
||||||
|
std::thread::spawn(move || {
|
||||||
|
let mut buf = Vec::new();
|
||||||
|
if let Some(mut p) = pipe {
|
||||||
|
let _ = p.read_to_end(&mut buf);
|
||||||
|
}
|
||||||
|
buf
|
||||||
|
})
|
||||||
|
};
|
||||||
|
let out_reader = read(child.stdout.take().map(|p| Box::new(p) as Box<dyn std::io::Read + Send>));
|
||||||
|
let err_reader = read(child.stderr.take().map(|p| Box::new(p) as Box<dyn std::io::Read + Send>));
|
||||||
|
let started = Instant::now();
|
||||||
|
let failed = |stderr: &[u8]| {
|
||||||
|
let text = String::from_utf8_lossy(stderr);
|
||||||
|
let detail = text.lines().rev().find(|l| !l.trim().is_empty()).unwrap_or("").trim().to_string();
|
||||||
|
let mut message = "The repack database command failed; check mysql/logs/mysql-error.log.".to_string();
|
||||||
|
if !detail.is_empty() {
|
||||||
|
message.push_str(&format!(" ({detail})"));
|
||||||
|
}
|
||||||
|
Error::Invalid(message)
|
||||||
|
};
|
||||||
|
let status = loop {
|
||||||
|
if let Some(status) = child.try_wait()? {
|
||||||
|
break status;
|
||||||
|
}
|
||||||
|
if started.elapsed() > Duration::from_secs(timeout) {
|
||||||
|
let _ = child.kill();
|
||||||
|
let _ = child.wait();
|
||||||
|
let _ = out_reader.join();
|
||||||
|
return Err(failed(b"timed out"));
|
||||||
|
}
|
||||||
|
std::thread::sleep(Duration::from_millis(50));
|
||||||
|
};
|
||||||
|
let stdout = out_reader.join().unwrap_or_default();
|
||||||
|
let stderr = err_reader.join().unwrap_or_default();
|
||||||
|
if !status.success() {
|
||||||
|
return Err(failed(&stderr));
|
||||||
|
}
|
||||||
|
Ok(String::from_utf8_lossy(&stdout).trim().to_string())
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------------------------------------------------------
|
||||||
|
// Start and stop
|
||||||
|
// ---------------------------------------------------------------------------------------------------------------
|
||||||
|
|
||||||
|
pub fn start_mysql(root: &Path, cfg: &Settings, progress: Progress) -> Result<()> {
|
||||||
|
if cfg.shared_database {
|
||||||
|
// An extra world uses the main folder's database; it must already run.
|
||||||
|
return mysql(root, None, Some("ping")).map(|_| ()).map_err(|e| {
|
||||||
|
Error::Service(ErrorCode::DatabaseNotRunning, format!("The main server's database is not running. {e}"))
|
||||||
|
});
|
||||||
|
}
|
||||||
|
if state::running(root, "mysql").is_some() {
|
||||||
|
wait_ready(root, "mysql", cfg.mysql_port, 300)?;
|
||||||
|
mysql(root, None, Some("ping"))?;
|
||||||
|
progress("MySQL is already running.");
|
||||||
|
return Ok(());
|
||||||
|
}
|
||||||
|
ensure_free(cfg.mysql_port, progress)?;
|
||||||
|
if !root.join("mysql/data/mysql").is_dir() {
|
||||||
|
return Err(Error::Service(ErrorCode::ServerFilesIncomplete, "The packaged database is missing. Extract the complete repack.".into()));
|
||||||
|
}
|
||||||
|
progress("Starting MySQL...");
|
||||||
|
let ini = format!("--defaults-file={}", root.join("mysql/my.ini").display());
|
||||||
|
spawn(root, "mysql", &root.join("mysql/bin/mysqld.exe"), &[&ini, "--no-monitor"], &root.join("mysql"), &root.join("mysql/logs/startup.log"), &cfg.env_remove)?;
|
||||||
|
wait_ready(root, "mysql", cfg.mysql_port, 300)?;
|
||||||
|
mysql(root, None, Some("ping"))?;
|
||||||
|
mysql(
|
||||||
|
root,
|
||||||
|
Some(&format!(
|
||||||
|
"UPDATE acore_auth.realmlist SET name='{}',address='127.0.0.1',localAddress='127.0.0.1',port={} WHERE id={};",
|
||||||
|
cfg.realm.name, cfg.world_port, cfg.realm.id
|
||||||
|
)),
|
||||||
|
None,
|
||||||
|
)?;
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn start_auth(root: &Path, cfg: &Settings, progress: Progress) -> Result<()> {
|
||||||
|
start_mysql(root, cfg, progress)?;
|
||||||
|
if state::running(root, "auth").is_some() {
|
||||||
|
wait_ready(root, "auth", cfg.auth_port, 60)?;
|
||||||
|
progress("Authserver is already running.");
|
||||||
|
return Ok(());
|
||||||
|
}
|
||||||
|
ensure_free(cfg.auth_port, progress)?;
|
||||||
|
// An interrupted world startup can leave flag 3, which authserver excludes.
|
||||||
|
mysql(root, Some(&format!("UPDATE acore_auth.realmlist SET flag=0 WHERE id={};", cfg.realm.id)), None)?;
|
||||||
|
progress("Starting authserver...");
|
||||||
|
spawn(root, "auth", &root.join("Core/authserver.exe"), &["-c", "configs/authserver.conf"], &root.join("Core"), &root.join("Core/Logs/auth-console.log"), &cfg.env_remove)?;
|
||||||
|
wait_ready(root, "auth", cfg.auth_port, 60)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Stop the recorded process, only if it is still that process.
|
||||||
|
pub fn terminate(record: &ProcessIdentity) -> Result<()> {
|
||||||
|
if !crate::process::is_alive(record) {
|
||||||
|
return Ok(());
|
||||||
|
}
|
||||||
|
sys::terminate(record)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn wait_stopped(record: &ProcessIdentity, seconds: u64) -> bool {
|
||||||
|
let until = Instant::now() + Duration::from_secs(seconds);
|
||||||
|
while crate::process::is_alive(record) && Instant::now() < until {
|
||||||
|
std::thread::sleep(Duration::from_millis(250));
|
||||||
|
}
|
||||||
|
!crate::process::is_alive(record)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The recorded world, when it is this folder's own `Core/worldserver.exe` (never stop a process only because a
|
||||||
|
/// record names it).
|
||||||
|
fn owned_world(root: &Path) -> Result<Option<ProcessIdentity>> {
|
||||||
|
let Some(world) = state::running(root, "world") else { return Ok(None) };
|
||||||
|
let expected = root.join("Core/worldserver.exe");
|
||||||
|
let same = std::fs::canonicalize(&world.exe).ok().zip(std::fs::canonicalize(&expected).ok()).is_some_and(|(a, b)| a == b);
|
||||||
|
if !same {
|
||||||
|
return Err(Error::Invalid("World process ownership could not be verified; the database was left running.".into()));
|
||||||
|
}
|
||||||
|
Ok(Some(world))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Ask the world's console for a graceful shutdown. False when the console is not this world's or does not answer.
|
||||||
|
fn ask_shutdown(root: &Path, cfg: &Settings) -> bool {
|
||||||
|
ready(root, "world", cfg.ra_port)
|
||||||
|
&& crate::ra::Ra::connect_to(cfg.ra_port, &cfg.ra_username, &cfg.ra_password)
|
||||||
|
.and_then(|ra| ra.send_without_answer("server shutdown 1s 0"))
|
||||||
|
.is_ok()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Stop this folder's world without its console (unsaved progress since the last save is lost).
|
||||||
|
fn stop_world_process(world: &ProcessIdentity) -> Result<()> {
|
||||||
|
terminate(world).map_err(|_| Error::Invalid("Worldserver could not be stopped safely; its database was left running.".into()))?;
|
||||||
|
if !wait_stopped(world, 90) {
|
||||||
|
return Err(Error::Invalid("Worldserver is still stopping; its database was left running.".into()));
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Stop the world at once, then everything else as [`stop_all`] does. Only when the user asked for it.
|
||||||
|
pub fn force_stop_all(root: &Path, cfg: &Settings, progress: Progress) -> Result<()> {
|
||||||
|
if let Some(world) = owned_world(root)? {
|
||||||
|
stop_world_process(&world)?;
|
||||||
|
progress("Force-stopped this server's verified world process; unsaved progress may be lost.");
|
||||||
|
}
|
||||||
|
stop_all(root, cfg, progress)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Stop everything of this repack, world first (gracefully through its console), its database last. An extra
|
||||||
|
/// world leaves the shared database alone.
|
||||||
|
pub fn stop_all(root: &Path, cfg: &Settings, progress: Progress) -> Result<()> {
|
||||||
|
if let Some(world) = owned_world(root)? {
|
||||||
|
if ask_shutdown(root, cfg) {
|
||||||
|
progress("Graceful world shutdown requested.");
|
||||||
|
} else {
|
||||||
|
progress("World console unavailable; stopping this repack's recorded world process.");
|
||||||
|
stop_world_process(&world)?;
|
||||||
|
}
|
||||||
|
// A console request can be lost (seen when a client disconnected at once). While the world still runs
|
||||||
|
// and its console still answers, it has not begun to stop: ask again. Asking twice is harmless.
|
||||||
|
let mut stopped = wait_stopped(&world, 15);
|
||||||
|
for _ in 0..2 {
|
||||||
|
if stopped {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
if ask_shutdown(root, cfg) {
|
||||||
|
progress("The world has not begun to stop; shutdown requested again.");
|
||||||
|
}
|
||||||
|
stopped = wait_stopped(&world, 15);
|
||||||
|
}
|
||||||
|
if !stopped && !wait_stopped(&world, 45) {
|
||||||
|
return Err(Error::Invalid("Worldserver is still stopping; its database has been left running.".into()));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if let Some(supervisor) = state::running(root, "supervisor") {
|
||||||
|
if !wait_stopped(&supervisor, 45) {
|
||||||
|
return Err(Error::Invalid("The report relay is still finishing a request. Try Stop All again shortly.".into()));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if let Some(relay) = state::running(root, "relay") {
|
||||||
|
std::fs::write(state::dir(root).join("stop-relay"), b"")?;
|
||||||
|
if !wait_stopped(&relay, 40) {
|
||||||
|
return Err(Error::Invalid("The report relay did not finish; it was left running for recovery.".into()));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if let Some(auth) = state::running(root, "auth") {
|
||||||
|
terminate(&auth)?;
|
||||||
|
if !wait_stopped(&auth, 10) {
|
||||||
|
return Err(Error::Invalid("Authserver did not stop.".into()));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if let Some(database) = state::running(root, "mysql").filter(|_| !cfg.shared_database) {
|
||||||
|
let shutdown = mysql(root, None, Some("shutdown"));
|
||||||
|
if !wait_stopped(&database, 60) {
|
||||||
|
shutdown?;
|
||||||
|
return Err(Error::Invalid("MySQL is still stopping; wait before copying the repack.".into()));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
progress("All services from this repack are stopped. It is safe to move or copy this folder.");
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Which services run (`manage.py status-json`).
|
||||||
|
pub fn status(root: &Path) -> serde_json::Value {
|
||||||
|
let mut out = serde_json::Map::new();
|
||||||
|
for name in ["mysql", "auth", "world", "relay"] {
|
||||||
|
out.insert(name.into(), state::running(root, name).is_some().into());
|
||||||
|
}
|
||||||
|
let debug: bool = crate::fsx::read_json::<serde_json::Value>(&state::dir(root).join("debug-logs.json"))
|
||||||
|
.ok()
|
||||||
|
.and_then(|v| v.get("enabled").and_then(|e| e.as_bool()))
|
||||||
|
.unwrap_or(false);
|
||||||
|
out.insert("debugLogs".into(), debug.into());
|
||||||
|
serde_json::Value::Object(out)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn log_path(root: &Path, name: &str) -> PathBuf {
|
||||||
|
match name {
|
||||||
|
"mysql" => root.join("mysql/logs/startup.log"),
|
||||||
|
"auth" => root.join("Core/Logs/auth-console.log"),
|
||||||
|
"world" => root.join("Core/Logs/world-console.log"),
|
||||||
|
"supervisor" => root.join("Core/Logs/supervisor.log"),
|
||||||
|
_ => root.join("BugReport/Logs/relay.log"),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------------------------------------------------------
|
||||||
|
// Windows
|
||||||
|
// ---------------------------------------------------------------------------------------------------------------
|
||||||
|
|
||||||
|
#[cfg(windows)]
|
||||||
|
mod sys {
|
||||||
|
use crate::error::{Error, Result};
|
||||||
|
use crate::process::ProcessIdentity;
|
||||||
|
use windows_sys::Win32::Foundation::CloseHandle;
|
||||||
|
use windows_sys::Win32::NetworkManagement::IpHelper::GetExtendedTcpTable;
|
||||||
|
use windows_sys::Win32::Networking::WinSock::{setsockopt, SOL_SOCKET, SO_EXCLUSIVEADDRUSE};
|
||||||
|
use windows_sys::Win32::System::Threading::{OpenProcess, TerminateProcess, PROCESS_QUERY_LIMITED_INFORMATION, PROCESS_TERMINATE};
|
||||||
|
|
||||||
|
pub const LISTEN: u32 = 2;
|
||||||
|
pub const ESTABLISHED: u32 = 5;
|
||||||
|
|
||||||
|
pub struct TcpRow {
|
||||||
|
pub state: u32,
|
||||||
|
pub local_port: u16,
|
||||||
|
pub remote_port: u16,
|
||||||
|
pub remote_loopback: bool,
|
||||||
|
pub pid: u32,
|
||||||
|
}
|
||||||
|
|
||||||
|
fn table(af: u32) -> Vec<u8> {
|
||||||
|
const TCP_TABLE_OWNER_PID_ALL: i32 = 5;
|
||||||
|
let mut size = 0u32;
|
||||||
|
let mut buf: Vec<u8> = Vec::new();
|
||||||
|
for _ in 0..4 {
|
||||||
|
let code = unsafe {
|
||||||
|
GetExtendedTcpTable(
|
||||||
|
if buf.is_empty() { std::ptr::null_mut() } else { buf.as_mut_ptr().cast() },
|
||||||
|
&mut size,
|
||||||
|
0,
|
||||||
|
af,
|
||||||
|
TCP_TABLE_OWNER_PID_ALL,
|
||||||
|
0,
|
||||||
|
)
|
||||||
|
};
|
||||||
|
match code {
|
||||||
|
0 if !buf.is_empty() => return buf,
|
||||||
|
0 | 122 => buf = vec![0u8; size as usize + 4096],
|
||||||
|
_ => return Vec::new(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Vec::new()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn u32_at(b: &[u8], o: usize) -> u32 {
|
||||||
|
u32::from_le_bytes(b[o..o + 4].try_into().unwrap())
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn tcp_rows_v4() -> Vec<TcpRow> {
|
||||||
|
let b = table(2);
|
||||||
|
let mut out = Vec::new();
|
||||||
|
if b.len() < 4 {
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
for i in 0..u32_at(&b, 0) as usize {
|
||||||
|
let o = 4 + 24 * i;
|
||||||
|
if o + 24 > b.len() {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
let remote = u32_at(&b, o + 12).to_le_bytes();
|
||||||
|
out.push(TcpRow {
|
||||||
|
state: u32_at(&b, o),
|
||||||
|
local_port: u16::from_be((u32_at(&b, o + 8) & 0xFFFF) as u16),
|
||||||
|
remote_port: u16::from_be((u32_at(&b, o + 16) & 0xFFFF) as u16),
|
||||||
|
remote_loopback: remote == [127, 0, 0, 1],
|
||||||
|
pid: u32_at(&b, o + 20),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
out
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn tcp_rows_v6() -> Vec<TcpRow> {
|
||||||
|
let b = table(23);
|
||||||
|
let mut out = Vec::new();
|
||||||
|
if b.len() < 4 {
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
// MIB_TCP6ROW_OWNER_PID: local addr 16, scope 4, local port 4, remote addr 16, scope 4, remote port 4, state 4, pid 4
|
||||||
|
for i in 0..u32_at(&b, 0) as usize {
|
||||||
|
let o = 4 + 56 * i;
|
||||||
|
if o + 56 > b.len() {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
let remote = &b[o + 24..o + 40];
|
||||||
|
let mapped_loopback = remote[..10].iter().all(|x| *x == 0) && remote[10] == 0xff && remote[11] == 0xff && remote[12..] == [127, 0, 0, 1];
|
||||||
|
out.push(TcpRow {
|
||||||
|
state: u32_at(&b, o + 48),
|
||||||
|
local_port: u16::from_be((u32_at(&b, o + 20) & 0xFFFF) as u16),
|
||||||
|
remote_port: u16::from_be((u32_at(&b, o + 44) & 0xFFFF) as u16),
|
||||||
|
remote_loopback: mapped_loopback,
|
||||||
|
pid: u32_at(&b, o + 52),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
out
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Bind 0.0.0.0:port exclusively and release it. Err carries the Windows socket error.
|
||||||
|
pub fn exclusive_bind(port: u16) -> std::result::Result<(), i32> {
|
||||||
|
use socket2::{Domain, Socket, Type};
|
||||||
|
use std::os::windows::io::AsRawSocket;
|
||||||
|
let socket = Socket::new(Domain::IPV4, Type::STREAM, None).map_err(|e| e.raw_os_error().unwrap_or(-1))?;
|
||||||
|
let one: i32 = 1;
|
||||||
|
let set = unsafe {
|
||||||
|
setsockopt(socket.as_raw_socket() as _, SOL_SOCKET, SO_EXCLUSIVEADDRUSE, (&one as *const i32).cast(), 4)
|
||||||
|
};
|
||||||
|
if set != 0 {
|
||||||
|
return Err(std::io::Error::last_os_error().raw_os_error().unwrap_or(-1));
|
||||||
|
}
|
||||||
|
let addr: std::net::SocketAddr = ([0, 0, 0, 0], port).into();
|
||||||
|
socket.bind(&addr.into()).map_err(|e| e.raw_os_error().unwrap_or(-1))
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn terminate(record: &ProcessIdentity) -> Result<()> {
|
||||||
|
unsafe {
|
||||||
|
let h = OpenProcess(PROCESS_TERMINATE | PROCESS_QUERY_LIMITED_INFORMATION, 0, record.pid);
|
||||||
|
if h.is_null() {
|
||||||
|
return Err(Error::Invalid("Unable to stop the repack process.".into()));
|
||||||
|
}
|
||||||
|
let same = crate::process::is_alive(record);
|
||||||
|
let ok = same && TerminateProcess(h, 0) != 0;
|
||||||
|
CloseHandle(h);
|
||||||
|
if !ok {
|
||||||
|
return Err(Error::Invalid("The process changed while stopping it.".into()));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(not(windows))]
|
||||||
|
mod sys {
|
||||||
|
use crate::error::{Error, Result};
|
||||||
|
use crate::process::ProcessIdentity;
|
||||||
|
pub const LISTEN: u32 = 2;
|
||||||
|
pub const ESTABLISHED: u32 = 5;
|
||||||
|
pub struct TcpRow {
|
||||||
|
pub state: u32,
|
||||||
|
pub local_port: u16,
|
||||||
|
pub remote_port: u16,
|
||||||
|
pub remote_loopback: bool,
|
||||||
|
pub pid: u32,
|
||||||
|
}
|
||||||
|
pub fn tcp_rows_v4() -> Vec<TcpRow> {
|
||||||
|
Vec::new()
|
||||||
|
}
|
||||||
|
pub fn tcp_rows_v6() -> Vec<TcpRow> {
|
||||||
|
Vec::new()
|
||||||
|
}
|
||||||
|
pub fn exclusive_bind(_: u16) -> std::result::Result<(), i32> {
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
pub fn terminate(_: &ProcessIdentity) -> Result<()> {
|
||||||
|
Err(Error::Invalid("not supported".into()))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_port_with_a_listener_is_refused_and_a_free_one_passes() {
|
||||||
|
let held = std::net::TcpListener::bind("0.0.0.0:0").unwrap();
|
||||||
|
let port = held.local_addr().unwrap().port();
|
||||||
|
let err = ensure_free(port, &|_| {}).unwrap_err().to_string();
|
||||||
|
assert!(err.contains(&format!("Port {port} is already used (PID {}", std::process::id())), "{err}");
|
||||||
|
drop(held);
|
||||||
|
ensure_free(port, &|_| {}).unwrap();
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_service_is_ready_only_on_its_own_port() {
|
||||||
|
let d = tempfile::tempdir().unwrap();
|
||||||
|
let held = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
|
||||||
|
let port = held.local_addr().unwrap().port();
|
||||||
|
assert!(!ready(d.path(), "auth", port), "no record yet");
|
||||||
|
state::record(d.path(), "auth", std::process::id()).unwrap();
|
||||||
|
assert!(ready(d.path(), "auth", port));
|
||||||
|
let other = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
|
||||||
|
drop(other);
|
||||||
|
assert!(!ready(d.path(), "auth", port + 1) || port + 1 == 0);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn status_reads_the_records() {
|
||||||
|
let d = tempfile::tempdir().unwrap();
|
||||||
|
state::record(d.path(), "mysql", std::process::id()).unwrap();
|
||||||
|
let s = status(d.path());
|
||||||
|
assert_eq!(s["mysql"], true);
|
||||||
|
assert_eq!(s["world"], false);
|
||||||
|
assert_eq!(s["debugLogs"], false);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,168 @@
|
|||||||
|
//! `Settings/repack.json`: ports and the console login of one repack (`manage.py settings()`).
|
||||||
|
|
||||||
|
use std::path::Path;
|
||||||
|
|
||||||
|
use crate::error::{Error, Result};
|
||||||
|
|
||||||
|
pub const PORT_KEYS: [&str; 4] = ["mysqlPort", "authPort", "worldPort", "raPort"];
|
||||||
|
|
||||||
|
/// The realm a folder runs: its row in `acore_auth.realmlist` and its two game databases.
|
||||||
|
///
|
||||||
|
/// Without `Settings/realm-profile.json` this is what the repack launcher always did (realm 1 "AzerothCore" on
|
||||||
|
/// `acore_world`/`acore_characters`). With it, the active profile decides, as the Manager's realm patch of
|
||||||
|
/// `manage.py` did.
|
||||||
|
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||||
|
pub struct Realm {
|
||||||
|
pub id: u32,
|
||||||
|
pub name: &'static str,
|
||||||
|
pub world_db: &'static str,
|
||||||
|
pub characters_db: &'static str,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Realm {
|
||||||
|
pub fn load(root: &Path) -> Result<Realm> {
|
||||||
|
let path = root.join("Settings/realm-profile.json");
|
||||||
|
if !path.exists() {
|
||||||
|
return Ok(Realm { id: 1, name: "AzerothCore", world_db: "acore_world", characters_db: "acore_characters" });
|
||||||
|
}
|
||||||
|
let v: serde_json::Value = crate::fsx::read_json(&path)?;
|
||||||
|
Ok(match v.get("active").and_then(|a| a.as_str()).unwrap_or("coa") {
|
||||||
|
"wildcard" => Realm { id: 2, name: "Wildcard", world_db: "acore_world_wildcard", characters_db: "acore_characters_wildcard" },
|
||||||
|
"reborn" => Realm { id: 3, name: "Warcraft Reborn", world_db: "acore_world_reborn", characters_db: "acore_characters_reborn" },
|
||||||
|
_ => Realm { id: 1, name: "Conquest of Azeroth", world_db: "acore_world", characters_db: "acore_characters" },
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// An extra world of a server (`<server>/.realms/<name>`): it shares the main folder's database and never
|
||||||
|
/// starts or stops it.
|
||||||
|
pub fn is_extra_world(root: &Path) -> bool {
|
||||||
|
root.parent().and_then(|p| p.file_name()).is_some_and(|n| n == ".realms")
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||||
|
pub struct Settings {
|
||||||
|
pub mysql_port: u16,
|
||||||
|
pub auth_port: u16,
|
||||||
|
pub world_port: u16,
|
||||||
|
pub ra_port: u16,
|
||||||
|
pub ra_username: String,
|
||||||
|
pub ra_password: String,
|
||||||
|
pub realm: Realm,
|
||||||
|
/// The database belongs to the main folder of this server (an extra world): it is only checked, never
|
||||||
|
/// started.
|
||||||
|
pub shared_database: bool,
|
||||||
|
/// Environment variables the started services must not see (for example a port override of the caller).
|
||||||
|
pub env_remove: Vec<String>,
|
||||||
|
/// The whole document, for keys this code does not know (kept when it is written back).
|
||||||
|
pub raw: serde_json::Map<String, serde_json::Value>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Settings {
|
||||||
|
/// Read `Settings/repack.json`, with every port moved by `offset` (a second world of the same server runs on
|
||||||
|
/// shifted ports). The same checks as `manage.py`: integer ports in 1025..65535 after the offset, all
|
||||||
|
/// different.
|
||||||
|
pub fn load(root: &Path, offset: i32) -> Result<Settings> {
|
||||||
|
let bytes = std::fs::read(root.join("Settings/repack.json"))?;
|
||||||
|
let text = String::from_utf8_lossy(&bytes);
|
||||||
|
let text = text.strip_prefix('\u{feff}').unwrap_or(&text);
|
||||||
|
let raw: serde_json::Map<String, serde_json::Value> =
|
||||||
|
serde_json::from_str(text).map_err(|e| Error::Invalid(format!("Settings/repack.json: {e}")))?;
|
||||||
|
let mut ports = [0u16; 4];
|
||||||
|
for (i, key) in PORT_KEYS.iter().enumerate() {
|
||||||
|
// Python's `type(value) is not int` refuses booleans and floats alike.
|
||||||
|
let value = raw.get(*key).and_then(|v| v.as_i64()).filter(|_| raw[*key].is_i64() || raw[*key].is_u64());
|
||||||
|
let shifted = value.map(|v| v + i64::from(offset));
|
||||||
|
match shifted {
|
||||||
|
Some(p) if p > 1024 && p < 65536 => ports[i] = p as u16,
|
||||||
|
_ => return Err(Error::Service(crate::error::ErrorCode::InvalidConfigValue, "Invalid port in Settings/repack.json".into())),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let mut unique = ports.to_vec();
|
||||||
|
unique.sort_unstable();
|
||||||
|
unique.dedup();
|
||||||
|
if unique.len() != 4 {
|
||||||
|
return Err(Error::Invalid("Each service needs a different port.".into()));
|
||||||
|
}
|
||||||
|
let text_of = |k: &str| raw.get(k).and_then(|v| v.as_str()).unwrap_or_default().to_string();
|
||||||
|
Ok(Settings {
|
||||||
|
mysql_port: ports[0],
|
||||||
|
auth_port: ports[1],
|
||||||
|
world_port: ports[2],
|
||||||
|
ra_port: ports[3],
|
||||||
|
ra_username: text_of("raUsername"),
|
||||||
|
ra_password: text_of("raPassword"),
|
||||||
|
realm: Realm::load(root)?,
|
||||||
|
shared_database: is_extra_world(root),
|
||||||
|
env_remove: Vec::new(),
|
||||||
|
raw,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
/// `{"mysqlPort": .., "authPort": .., "worldPort": .., "raPort": ..}` as `manage.py` records it in
|
||||||
|
/// `.state/configuration.json` (the keys of repack.json ending in "Port", in the file's order).
|
||||||
|
pub fn port_map(&self) -> serde_json::Map<String, serde_json::Value> {
|
||||||
|
let shifted = [self.mysql_port, self.auth_port, self.world_port, self.ra_port];
|
||||||
|
let mut out = serde_json::Map::new();
|
||||||
|
for key in self.raw.keys().filter(|k| k.ends_with("Port")) {
|
||||||
|
let value = PORT_KEYS
|
||||||
|
.iter()
|
||||||
|
.position(|p| p == key)
|
||||||
|
.map(|i| serde_json::Value::from(shifted[i]))
|
||||||
|
.unwrap_or_else(|| self.raw[key].clone());
|
||||||
|
out.insert(key.clone(), value);
|
||||||
|
}
|
||||||
|
out
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
|
||||||
|
fn write(dir: &Path, text: &str) {
|
||||||
|
std::fs::create_dir_all(dir.join("Settings")).unwrap();
|
||||||
|
std::fs::write(dir.join("Settings/repack.json"), text).unwrap();
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn ports_are_checked_like_the_python_launcher() {
|
||||||
|
let d = tempfile::tempdir().unwrap();
|
||||||
|
write(d.path(), r#"{"mysqlPort":3307,"authPort":3724,"worldPort":8085,"raPort":3443,"raUsername":"U","raPassword":"P"}"#);
|
||||||
|
let s = Settings::load(d.path(), 0).unwrap();
|
||||||
|
assert_eq!((s.mysql_port, s.auth_port, s.world_port, s.ra_port), (3307, 3724, 8085, 3443));
|
||||||
|
assert_eq!(s.ra_username, "U");
|
||||||
|
let shifted = Settings::load(d.path(), 10).unwrap();
|
||||||
|
assert_eq!(shifted.world_port, 8095);
|
||||||
|
assert_eq!(shifted.port_map()["worldPort"], serde_json::json!(8095));
|
||||||
|
|
||||||
|
for bad in [
|
||||||
|
r#"{"mysqlPort":1024,"authPort":3724,"worldPort":8085,"raPort":3443}"#,
|
||||||
|
r#"{"mysqlPort":"3307","authPort":3724,"worldPort":8085,"raPort":3443}"#,
|
||||||
|
r#"{"mysqlPort":3307.0,"authPort":3724,"worldPort":8085,"raPort":3443}"#,
|
||||||
|
r#"{"mysqlPort":true,"authPort":3724,"worldPort":8085,"raPort":3443}"#,
|
||||||
|
r#"{"mysqlPort":3307,"authPort":3307,"worldPort":8085,"raPort":3443}"#,
|
||||||
|
r#"{"authPort":3724,"worldPort":8085,"raPort":3443}"#,
|
||||||
|
] {
|
||||||
|
write(d.path(), bad);
|
||||||
|
assert!(Settings::load(d.path(), 0).is_err(), "{bad}");
|
||||||
|
}
|
||||||
|
write(d.path(), "\u{feff}{\"mysqlPort\":3307,\"authPort\":3724,\"worldPort\":8085,\"raPort\":65535}");
|
||||||
|
assert!(Settings::load(d.path(), 1).is_err(), "65536 after the offset");
|
||||||
|
assert!(Settings::load(d.path(), 0).is_ok(), "a byte order mark is accepted");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn the_realm_follows_the_active_profile() {
|
||||||
|
let d = tempfile::tempdir().unwrap();
|
||||||
|
assert_eq!(Realm::load(d.path()).unwrap().name, "AzerothCore");
|
||||||
|
std::fs::create_dir_all(d.path().join("Settings")).unwrap();
|
||||||
|
for (active, id, db) in [("coa", 1, "acore_world"), ("wildcard", 2, "acore_world_wildcard"), ("reborn", 3, "acore_world_reborn")] {
|
||||||
|
std::fs::write(d.path().join("Settings/realm-profile.json"), format!("{{\"active\":\"{active}\"}}")).unwrap();
|
||||||
|
let r = Realm::load(d.path()).unwrap();
|
||||||
|
assert_eq!((r.id, r.world_db), (id, db));
|
||||||
|
}
|
||||||
|
assert!(is_extra_world(&d.path().join(".realms/secondary")));
|
||||||
|
assert!(!is_extra_world(d.path()));
|
||||||
|
}
|
||||||
|
}
|
||||||
Binary file not shown.
@@ -0,0 +1,398 @@
|
|||||||
|
//! SQUID Playerbots on a repack (`Scripts/squid_playerbots.py`): the bot modules must not both run, how long a
|
||||||
|
//! SQUID world may take to start, and its database, provisioned before the world starts.
|
||||||
|
//!
|
||||||
|
//! The SQL journals are the ones the Python script keeps, unchanged: `coa_squid_migrations(path, sha256)` and
|
||||||
|
//! `coa_squid_pending(path, sha256)` in every target schema, and the SQUID installer's `coa_bots_installed`.
|
||||||
|
|
||||||
|
use std::collections::{BTreeMap, BTreeSet};
|
||||||
|
use std::path::{Path, PathBuf};
|
||||||
|
|
||||||
|
use sha1::Digest as _;
|
||||||
|
|
||||||
|
use crate::error::{Error, Result};
|
||||||
|
|
||||||
|
/// `key = value` lines of a module config (comments and quotes dropped), as `options()` reads them.
|
||||||
|
pub fn options(path: &Path) -> BTreeMap<String, String> {
|
||||||
|
let mut out = BTreeMap::new();
|
||||||
|
let Ok(bytes) = std::fs::read(path) else { return out };
|
||||||
|
let text = String::from_utf8_lossy(&bytes);
|
||||||
|
let text = text.strip_prefix('\u{feff}').unwrap_or(&text);
|
||||||
|
for line in text.lines() {
|
||||||
|
let line = line.trim_start();
|
||||||
|
let Some((key, rest)) = line.split_once('=') else { continue };
|
||||||
|
let key = key.trim_end();
|
||||||
|
if key.is_empty() || key.starts_with('#') || key.contains(char::is_whitespace) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
let value = rest.split('#').next().unwrap_or("").trim();
|
||||||
|
out.insert(key.to_string(), value.trim_matches('"').to_string());
|
||||||
|
}
|
||||||
|
out
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A secondary world shares the primary's package files.
|
||||||
|
pub fn package_root(root: &Path) -> PathBuf {
|
||||||
|
let secondary = root.file_name().is_some_and(|n| n == "secondary")
|
||||||
|
&& root.parent().and_then(|p| p.file_name()).is_some_and(|n| n == ".realms");
|
||||||
|
if secondary {
|
||||||
|
root.parent().and_then(Path::parent).map(Path::to_path_buf).unwrap_or_else(|| root.to_path_buf())
|
||||||
|
} else {
|
||||||
|
root.to_path_buf()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn module_options(root: &Path, name: &str) -> (PathBuf, BTreeMap<String, String>) {
|
||||||
|
let folder = root.join("Core/configs/modules");
|
||||||
|
let active = folder.join(name);
|
||||||
|
let mut path = if active.exists() { active } else { folder.join(format!("{name}.dist")) };
|
||||||
|
if !path.exists() && name == "playerbots.conf" {
|
||||||
|
path = package_root(root).join("Core/configs/modules/playerbots.conf.dist");
|
||||||
|
}
|
||||||
|
let values = options(&path);
|
||||||
|
(path, values)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Invalid booleans count as the modules' compiled default: enabled.
|
||||||
|
pub fn enabled(values: &BTreeMap<String, String>, key: &str) -> bool {
|
||||||
|
!matches!(values.get(key).map(|v| v.to_ascii_lowercase()).as_deref(), Some("0" | "false" | "no" | "off"))
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn validate_bots(root: &Path) -> Result<()> {
|
||||||
|
let (a, av) = module_options(root, "mod_coa_playerbots.conf");
|
||||||
|
let (b, bv) = module_options(root, "playerbots.conf");
|
||||||
|
if a.exists() && b.exists() && enabled(&av, "CoaBots.Enable") && enabled(&bv, "AiPlayerbot.Enabled") {
|
||||||
|
return Err(Error::Invalid(
|
||||||
|
"CoA Companions and SQUID Playerbots cannot both be enabled. Disable one bot module in Modules or its config.".into(),
|
||||||
|
));
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Seconds a world may take to open its port: SQUID loads its bots first.
|
||||||
|
pub fn startup_timeout(root: &Path) -> u64 {
|
||||||
|
let (path, values) = module_options(root, "playerbots.conf");
|
||||||
|
if path.exists() && enabled(&values, "AiPlayerbot.Enabled") {
|
||||||
|
1500
|
||||||
|
} else {
|
||||||
|
180
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Replace (or append) `key = value` lines; the file is written with "\n" line ends.
|
||||||
|
pub fn set_options(path: &Path, values: &[(&str, String)]) -> Result<()> {
|
||||||
|
let bytes = std::fs::read(path)?;
|
||||||
|
let text = String::from_utf8_lossy(&bytes);
|
||||||
|
let mut text = text.strip_prefix('\u{feff}').unwrap_or(&text).replace("\r\n", "\n");
|
||||||
|
for (key, value) in values {
|
||||||
|
let line = format!("{key} = {value}");
|
||||||
|
let mut found = false;
|
||||||
|
let lines: Vec<String> = text
|
||||||
|
.split('\n')
|
||||||
|
.map(|l| {
|
||||||
|
let t = l.trim_start();
|
||||||
|
let matches = t.strip_prefix(key).is_some_and(|rest| rest.trim_start().starts_with('='));
|
||||||
|
if matches {
|
||||||
|
found = true;
|
||||||
|
line.clone()
|
||||||
|
} else {
|
||||||
|
l.to_string()
|
||||||
|
}
|
||||||
|
})
|
||||||
|
.collect();
|
||||||
|
text = lines.join("\n");
|
||||||
|
if !found {
|
||||||
|
text.push('\n');
|
||||||
|
text.push_str(&line);
|
||||||
|
text.push('\n');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
crate::fsx::atomic_write(path, text.as_bytes())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn valid_relative(rel: &str) -> bool {
|
||||||
|
!rel.is_empty() && rel.bytes().all(|b| b.is_ascii_alphanumeric() || matches!(b, b'_' | b'.' | b'/' | b'-'))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Table names a base file creates (`CREATE TABLE [IF NOT EXISTS] name`).
|
||||||
|
fn created_tables(sql: &str) -> BTreeSet<String> {
|
||||||
|
let mut out = BTreeSet::new();
|
||||||
|
let upper = sql.to_ascii_uppercase();
|
||||||
|
let mut from = 0;
|
||||||
|
while let Some(i) = upper[from..].find("CREATE") {
|
||||||
|
let start = from + i + "CREATE".len();
|
||||||
|
from = start;
|
||||||
|
let rest = &sql[start..];
|
||||||
|
let mut words = rest.split_whitespace();
|
||||||
|
if !words.next().is_some_and(|w| w.eq_ignore_ascii_case("TABLE")) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
let mut name = words.next().unwrap_or("");
|
||||||
|
if name.eq_ignore_ascii_case("IF") {
|
||||||
|
let _ = words.next(); // NOT
|
||||||
|
let _ = words.next(); // EXISTS
|
||||||
|
name = words.next().unwrap_or("");
|
||||||
|
}
|
||||||
|
let name: String = name.trim_start_matches('`').chars().take_while(|c| c.is_ascii_alphanumeric() || *c == '_').collect();
|
||||||
|
if !name.is_empty() {
|
||||||
|
out.insert(name);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
out
|
||||||
|
}
|
||||||
|
|
||||||
|
fn sha256_hex(bytes: &[u8]) -> String {
|
||||||
|
crate::fsx::sha256_bytes(bytes)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn sha1_hex(bytes: &[u8]) -> String {
|
||||||
|
let mut h = sha1::Sha1::new();
|
||||||
|
h.update(bytes);
|
||||||
|
h.finalize().iter().map(|b| format!("{b:02x}")).collect()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn rows(text: &str) -> Vec<(String, String)> {
|
||||||
|
text.lines().filter_map(|r| r.split_once('\t')).map(|(a, b)| (a.to_string(), b.to_string())).collect()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Provision an enabled SQUID without replaying imported base tables (`prepare_playerbots`). `mysql(sql)` runs
|
||||||
|
/// SQL with the repack's administrator login and returns its output.
|
||||||
|
pub fn prepare_playerbots(root: &Path, mysql_port: u16, mysql: &dyn Fn(&str) -> Result<String>, progress: &dyn Fn(&str)) -> Result<()> {
|
||||||
|
let (mut path, values) = module_options(root, "playerbots.conf");
|
||||||
|
if !path.exists() || !enabled(&values, "AiPlayerbot.Enabled") {
|
||||||
|
return Ok(());
|
||||||
|
}
|
||||||
|
validate_bots(root)?;
|
||||||
|
let sql_root = package_root(root).join("Extras/SquidPlayerbots/sql");
|
||||||
|
if !sql_root.join("playerbots/base").is_dir() {
|
||||||
|
return Err(Error::Invalid("SQUID Playerbots database files are missing. Repair the server installation.".into()));
|
||||||
|
}
|
||||||
|
let world = options(&root.join("Core/configs/worldserver.conf"));
|
||||||
|
let mut schemas: Vec<(&str, String)> = Vec::new();
|
||||||
|
for (kind, key) in [("characters", "CharacterDatabaseInfo"), ("world", "WorldDatabaseInfo")] {
|
||||||
|
let schema = world.get(key).and_then(|v| v.rsplit(';').next()).unwrap_or("").to_string();
|
||||||
|
let ok = matches!(schema.as_str(), "acore_world" | "acore_characters" | "acore_world_wildcard" | "acore_characters_wildcard");
|
||||||
|
if !ok {
|
||||||
|
return Err(Error::Invalid("Unsupported world/characters database for SQUID Playerbots.".into()));
|
||||||
|
}
|
||||||
|
schemas.push((kind, schema));
|
||||||
|
}
|
||||||
|
schemas.push(("playerbots", "acore_playerbots".into()));
|
||||||
|
|
||||||
|
let list = |schema: &str| -> Result<BTreeSet<String>> {
|
||||||
|
Ok(mysql(&format!("SELECT TABLE_NAME FROM information_schema.TABLES WHERE TABLE_SCHEMA='{schema}';"))?
|
||||||
|
.lines()
|
||||||
|
.map(str::to_string)
|
||||||
|
.collect())
|
||||||
|
};
|
||||||
|
let existing_playerbots = list("acore_playerbots")?;
|
||||||
|
let bookkeeping = ["updates", "updates_include", "version_db_playerbots", "coa_squid_migrations", "coa_bots_installed", "coa_squid_pending"];
|
||||||
|
let data_tables: Vec<&String> = existing_playerbots.iter().filter(|t| !bookkeeping.contains(&t.as_str())).collect();
|
||||||
|
let mut installer_history = BTreeSet::new();
|
||||||
|
if existing_playerbots.contains("coa_bots_installed") {
|
||||||
|
for name in mysql("SELECT file FROM `acore_playerbots`.coa_bots_installed;")?.lines() {
|
||||||
|
let mut n = name.replace('\\', "/");
|
||||||
|
while n.contains("//") {
|
||||||
|
n = n.replace("//", "/");
|
||||||
|
}
|
||||||
|
let n = n.trim_matches('/').to_string();
|
||||||
|
if n.to_ascii_lowercase().ends_with(".sql") {
|
||||||
|
installer_history.insert(n);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let mut tables: BTreeMap<&str, BTreeSet<String>> = BTreeMap::new();
|
||||||
|
let mut histories: BTreeMap<&str, BTreeMap<String, String>> = BTreeMap::new();
|
||||||
|
let mut ledgers: BTreeMap<&str, BTreeMap<String, String>> = BTreeMap::new();
|
||||||
|
for (kind, schema) in &schemas {
|
||||||
|
let t = if *kind == "playerbots" { existing_playerbots.clone() } else { list(schema)? };
|
||||||
|
if t.contains("coa_squid_pending") {
|
||||||
|
let pending = mysql(&format!("SELECT path FROM `{schema}`.coa_squid_pending;"))?;
|
||||||
|
let pending = pending.trim();
|
||||||
|
if !pending.is_empty() {
|
||||||
|
return Err(Error::Invalid(format!(
|
||||||
|
"A SQUID base import was interrupted. Restore the database backup or repair the incomplete import before continuing; no SQL was applied: {pending}"
|
||||||
|
)));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let mut history = BTreeMap::new();
|
||||||
|
if t.contains("updates") {
|
||||||
|
for (name, digest) in rows(&mysql(&format!("SELECT name,hash FROM `{schema}`.updates;"))?) {
|
||||||
|
history.insert(name, digest.to_ascii_lowercase());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let mut ledger = BTreeMap::new();
|
||||||
|
if t.contains("coa_squid_migrations") {
|
||||||
|
for (name, digest) in rows(&mysql(&format!("SELECT path,sha256 FROM `{schema}`.coa_squid_migrations;"))?) {
|
||||||
|
ledger.insert(name, digest);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
tables.insert(kind, t);
|
||||||
|
histories.insert(kind, history);
|
||||||
|
ledgers.insert(kind, ledger);
|
||||||
|
}
|
||||||
|
if !data_tables.is_empty() && installer_history.is_empty() && histories["playerbots"].is_empty() && ledgers["playerbots"].is_empty() {
|
||||||
|
for table in data_tables {
|
||||||
|
let quoted = table.replace('`', "``");
|
||||||
|
if mysql(&format!("SELECT EXISTS(SELECT 1 FROM `acore_playerbots`.`{quoted}` LIMIT 1);"))?.trim() == "1" {
|
||||||
|
return Err(Error::Invalid(
|
||||||
|
"Existing SQUID data has no recorded installation history. Repair the imported database history before continuing; no SQL was applied.".into(),
|
||||||
|
));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
mysql("CREATE DATABASE IF NOT EXISTS acore_playerbots CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;")?;
|
||||||
|
for host in ["localhost", "127.0.0.1"] {
|
||||||
|
mysql(&format!("GRANT ALL PRIVILEGES ON acore_playerbots.* TO 'acore'@'{host}';"))?;
|
||||||
|
}
|
||||||
|
let (_, password) = crate::db::credentials(root)?;
|
||||||
|
if password.len() != 48 || !password.bytes().all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b)) {
|
||||||
|
return Err(Error::Invalid("Invalid packaged database configuration.".into()));
|
||||||
|
}
|
||||||
|
if path.file_name().is_some_and(|n| n.to_string_lossy().ends_with(".dist")) {
|
||||||
|
let active = root.join("Core/configs/modules/playerbots.conf");
|
||||||
|
std::fs::create_dir_all(active.parent().unwrap())?;
|
||||||
|
std::fs::write(&active, std::fs::read(&path)?)?;
|
||||||
|
path = active;
|
||||||
|
}
|
||||||
|
set_options(
|
||||||
|
&path,
|
||||||
|
&[
|
||||||
|
("PlayerbotsDatabaseInfo", format!("\"127.0.0.1;{mysql_port};acore;{password};acore_playerbots\"")),
|
||||||
|
("Playerbots.Updates.EnableDatabases", "0".into()),
|
||||||
|
],
|
||||||
|
)?;
|
||||||
|
for (kind, schema) in &schemas {
|
||||||
|
mysql(&format!("CREATE TABLE IF NOT EXISTS `{schema}`.coa_squid_migrations (path VARCHAR(240) PRIMARY KEY, sha256 CHAR(64) NOT NULL);"))?;
|
||||||
|
mysql(&format!("CREATE TABLE IF NOT EXISTS `{schema}`.coa_squid_pending (path VARCHAR(240) PRIMARY KEY, sha256 CHAR(64) NOT NULL);"))?;
|
||||||
|
let history = &histories[kind];
|
||||||
|
let recorded = ledgers[kind].clone();
|
||||||
|
for stage in ["base", "updates", "custom"] {
|
||||||
|
let mut sources: Vec<PathBuf> = std::fs::read_dir(sql_root.join(kind).join(stage))
|
||||||
|
.map(|rd| rd.flatten().map(|e| e.path()).filter(|p| p.extension().is_some_and(|e| e == "sql")).collect())
|
||||||
|
.unwrap_or_default();
|
||||||
|
sources.sort();
|
||||||
|
for source in sources {
|
||||||
|
let relative = source.strip_prefix(&sql_root).unwrap_or(&source).to_string_lossy().replace('\\', "/");
|
||||||
|
if !valid_relative(&relative) {
|
||||||
|
return Err(Error::Invalid("Invalid SQUID SQL filename.".into()));
|
||||||
|
}
|
||||||
|
let bytes = std::fs::read(&source)?;
|
||||||
|
let digest = sha256_hex(&bytes);
|
||||||
|
if let Some(previous) = recorded.get(&relative) {
|
||||||
|
if *previous != digest {
|
||||||
|
return Err(Error::Invalid(format!("A previously applied SQUID database migration changed: {relative}")));
|
||||||
|
}
|
||||||
|
if stage != "base" {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let ledger_sql = if recorded.contains_key(&relative) {
|
||||||
|
String::new()
|
||||||
|
} else {
|
||||||
|
format!("INSERT INTO `{schema}`.coa_squid_migrations VALUES ('{relative}','{digest}');")
|
||||||
|
};
|
||||||
|
let text = String::from_utf8_lossy(&bytes);
|
||||||
|
let text = text.strip_prefix('\u{feff}').unwrap_or(&text).to_string();
|
||||||
|
if stage == "base" {
|
||||||
|
let definitions = created_tables(&text);
|
||||||
|
let present: BTreeSet<String> = definitions.intersection(&tables[kind]).cloned().collect();
|
||||||
|
if !present.is_empty() && present != definitions {
|
||||||
|
return Err(Error::Invalid(format!("SQUID base file has only some of its tables. Repair the incomplete database before continuing: {relative}")));
|
||||||
|
}
|
||||||
|
if definitions.is_empty() {
|
||||||
|
return Err(Error::Invalid(format!("SQUID base file has no recognizable table definitions; repair is required: {relative}")));
|
||||||
|
}
|
||||||
|
if present == definitions {
|
||||||
|
if !ledger_sql.is_empty() {
|
||||||
|
mysql(&ledger_sql)?;
|
||||||
|
}
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
mysql(&format!("INSERT INTO `{schema}`.coa_squid_pending VALUES ('{relative}','{digest}'); COMMIT;"))?;
|
||||||
|
let complete = format!("DELETE FROM `{schema}`.coa_squid_pending WHERE path='{relative}' AND sha256='{digest}'; COMMIT;");
|
||||||
|
progress(&format!("Importing SQUID {relative} into {schema} ({} bytes); large imports may take several minutes...", bytes.len()));
|
||||||
|
mysql(&format!("USE `{schema}`;\n{text}\n{ledger_sql}\n{complete}")).map_err(|_| {
|
||||||
|
Error::Invalid(format!(
|
||||||
|
"SQUID import failed: {relative} in {schema}. The world server was not started. The incomplete import is recorded; restore a database backup or repair that import before retrying."
|
||||||
|
))
|
||||||
|
})?;
|
||||||
|
progress(&format!("Imported SQUID {relative}."));
|
||||||
|
if let Some(t) = tables.get_mut(kind) {
|
||||||
|
t.extend(definitions);
|
||||||
|
}
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if installer_history.iter().any(|n| *n == relative || n.ends_with(&format!("/{relative}"))) {
|
||||||
|
mysql(&ledger_sql)?;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
let file_name = source.file_name().unwrap_or_default().to_string_lossy().into_owned();
|
||||||
|
if let Some(upstream) = history.get(&file_name) {
|
||||||
|
let lf = String::from_utf8_lossy(&bytes).replace("\r\n", "\n");
|
||||||
|
let accepted = [sha1_hex(&bytes), sha1_hex(lf.as_bytes())];
|
||||||
|
if !upstream.is_empty() && !accepted.contains(upstream) {
|
||||||
|
return Err(Error::Invalid(format!("SQUID update history does not match the shipped SQL: {relative}")));
|
||||||
|
}
|
||||||
|
mysql(&ledger_sql)?;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
mysql(&format!("USE `{schema}`;\n{text}\n{ledger_sql}"))?;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn config_lines_are_read_like_the_python_script() {
|
||||||
|
let d = tempfile::tempdir().unwrap();
|
||||||
|
let p = d.path().join("playerbots.conf");
|
||||||
|
std::fs::write(&p, "\u{feff}# comment = 1\nAiPlayerbot.Enabled = 0 # off\n Key.Two=\"quoted\"\nnot a line\nEmpty =\n").unwrap();
|
||||||
|
let o = options(&p);
|
||||||
|
assert_eq!(o.get("AiPlayerbot.Enabled").map(String::as_str), Some("0"));
|
||||||
|
assert_eq!(o.get("Key.Two").map(String::as_str), Some("quoted"));
|
||||||
|
assert_eq!(o.get("Empty").map(String::as_str), Some(""));
|
||||||
|
assert!(!o.contains_key("#"));
|
||||||
|
assert!(!enabled(&o, "AiPlayerbot.Enabled"));
|
||||||
|
assert!(enabled(&o, "Missing"));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn both_bot_modules_on_is_refused_and_squid_gets_a_long_startup() {
|
||||||
|
let d = tempfile::tempdir().unwrap();
|
||||||
|
let m = d.path().join("Core/configs/modules");
|
||||||
|
std::fs::create_dir_all(&m).unwrap();
|
||||||
|
std::fs::write(m.join("mod_coa_playerbots.conf"), "CoaBots.Enable = 1\n").unwrap();
|
||||||
|
std::fs::write(m.join("playerbots.conf.dist"), "AiPlayerbot.Enabled = 1\n").unwrap();
|
||||||
|
assert!(validate_bots(d.path()).is_err());
|
||||||
|
assert_eq!(startup_timeout(d.path()), 1500);
|
||||||
|
std::fs::write(m.join("playerbots.conf"), "AiPlayerbot.Enabled = 0\n").unwrap();
|
||||||
|
validate_bots(d.path()).unwrap();
|
||||||
|
assert_eq!(startup_timeout(d.path()), 180);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn options_are_replaced_or_appended() {
|
||||||
|
let d = tempfile::tempdir().unwrap();
|
||||||
|
let p = d.path().join("playerbots.conf");
|
||||||
|
std::fs::write(&p, "A = 1\r\n Playerbots.Updates.EnableDatabases = 1\r\n").unwrap();
|
||||||
|
set_options(&p, &[("Playerbots.Updates.EnableDatabases", "0".into()), ("PlayerbotsDatabaseInfo", "\"x\"".into())]).unwrap();
|
||||||
|
assert_eq!(std::fs::read_to_string(&p).unwrap(), "A = 1\nPlayerbots.Updates.EnableDatabases = 0\n\nPlayerbotsDatabaseInfo = \"x\"\n");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn base_tables_are_found() {
|
||||||
|
let t = created_tables("CREATE TABLE IF NOT EXISTS `ai_playerbot_names` (\n id int);\ncreate table playerbots_random_bots(x int);\n-- CREATE INDEX i ON t(x);");
|
||||||
|
assert_eq!(t, ["ai_playerbot_names".to_string(), "playerbots_random_bots".to_string()].into_iter().collect());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_secondary_world_uses_the_primary_package() {
|
||||||
|
assert_eq!(package_root(Path::new("C:/S/.realms/secondary")), Path::new("C:/S"));
|
||||||
|
assert_eq!(package_root(Path::new("C:/S")), Path::new("C:/S"));
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,198 @@
|
|||||||
|
//! `.state/`: which processes belong to this repack, and the one-action-at-a-time lock.
|
||||||
|
|
||||||
|
use std::fs::{File, OpenOptions};
|
||||||
|
use std::io::{Seek, SeekFrom, Write};
|
||||||
|
use std::path::{Path, PathBuf};
|
||||||
|
use std::time::{Duration, Instant};
|
||||||
|
|
||||||
|
use crate::error::{Error, Result};
|
||||||
|
use crate::fsx;
|
||||||
|
use crate::process::{self, ProcessIdentity};
|
||||||
|
|
||||||
|
pub fn dir(root: &Path) -> PathBuf {
|
||||||
|
root.join(".state")
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Written like `manage.py atomic_json`: two-space JSON and a newline, now flushed to disk before it replaces
|
||||||
|
/// the old file.
|
||||||
|
pub fn write_json(path: &Path, value: &impl serde::Serialize) -> Result<()> {
|
||||||
|
let mut text = serde_json::to_string_pretty(value)?;
|
||||||
|
text.push('\n');
|
||||||
|
fsx::atomic_write(path, text.as_bytes())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The recorded process of `name` when it is still that process (same executable and start time). A missing,
|
||||||
|
/// empty or damaged record is no process: `manage.py` failed on those, and every later start with it.
|
||||||
|
pub fn running(root: &Path, name: &str) -> Option<ProcessIdentity> {
|
||||||
|
let record = process::read_state_record(root, name)?;
|
||||||
|
process::is_alive(&record).then_some(record)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Record the process `pid` as `name`. Fails when it has already exited.
|
||||||
|
pub fn record(root: &Path, name: &str, pid: u32) -> Result<ProcessIdentity> {
|
||||||
|
let identity = process::identity(pid)
|
||||||
|
.ok_or_else(|| Error::Invalid(format!("{name} exited during startup; check its log.")))?;
|
||||||
|
write_json(&dir(root).join(format!("{name}.json")), &identity)?;
|
||||||
|
Ok(identity)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Held while one start/stop action runs. Byte 0 of `.state/control.lock` is locked, exactly the region
|
||||||
|
/// `msvcrt.locking(fd, LK_NBLCK, 1)` locks in `manage.py`, so a Python launcher and this one exclude each other.
|
||||||
|
pub struct ControlLock {
|
||||||
|
file: File,
|
||||||
|
owner: PathBuf,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl ControlLock {
|
||||||
|
/// Wait up to `wait` for the lock. `action` is recorded for whoever waits next ("start-all", ...).
|
||||||
|
pub fn acquire(root: &Path, action: &str, wait: Duration, progress: &dyn Fn(&str)) -> Result<ControlLock> {
|
||||||
|
let state = dir(root);
|
||||||
|
std::fs::create_dir_all(&state)?;
|
||||||
|
let mut file = OpenOptions::new().read(true).append(true).create(true).open(state.join("control.lock"))?;
|
||||||
|
if file.seek(SeekFrom::End(0))? == 0 {
|
||||||
|
file.write_all(b"0")?;
|
||||||
|
file.flush()?;
|
||||||
|
}
|
||||||
|
let owner = state.join("control-owner.json");
|
||||||
|
let deadline = Instant::now() + wait;
|
||||||
|
let mut announced = false;
|
||||||
|
loop {
|
||||||
|
if sys::try_lock(&file)? {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
let detail = match fsx::read_json::<serde_json::Value>(&owner) {
|
||||||
|
Ok(v) if v.get("pid").is_some() && v.get("action").is_some() => {
|
||||||
|
format!(" PID {}, action {}.", v["pid"], v["action"].as_str().unwrap_or(""))
|
||||||
|
}
|
||||||
|
_ => " Owner information is unavailable.".into(),
|
||||||
|
};
|
||||||
|
if Instant::now() >= deadline {
|
||||||
|
return Err(Error::Service(crate::error::ErrorCode::OperationInProgress, format!("Another start/stop action is in progress.{detail}")));
|
||||||
|
}
|
||||||
|
if !announced {
|
||||||
|
progress(&format!("Waiting for the current server action.{detail}"));
|
||||||
|
announced = true;
|
||||||
|
}
|
||||||
|
std::thread::sleep(Duration::from_millis(250));
|
||||||
|
}
|
||||||
|
let started = std::time::SystemTime::now()
|
||||||
|
.duration_since(std::time::UNIX_EPOCH)
|
||||||
|
.map(|d| d.as_secs_f64())
|
||||||
|
.unwrap_or(0.0);
|
||||||
|
let lock = ControlLock { file, owner };
|
||||||
|
write_json(
|
||||||
|
&lock.owner,
|
||||||
|
&serde_json::json!({ "pid": std::process::id(), "action": action, "started": started }),
|
||||||
|
)?;
|
||||||
|
Ok(lock)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Byte 0 of a file locked while held (`msvcrt.locking`), for example the bug-report relay's `relay.lock`.
|
||||||
|
pub struct FileLock {
|
||||||
|
file: File,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl FileLock {
|
||||||
|
/// Take the lock, or `None` when another process (or handle) holds it.
|
||||||
|
pub fn try_acquire(path: &Path) -> Result<Option<FileLock>> {
|
||||||
|
let mut file = OpenOptions::new().read(true).append(true).create(true).open(path)?;
|
||||||
|
if file.seek(SeekFrom::End(0))? == 0 {
|
||||||
|
file.write_all(b"0")?;
|
||||||
|
file.flush()?;
|
||||||
|
}
|
||||||
|
Ok(sys::try_lock(&file)?.then_some(FileLock { file }))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Drop for FileLock {
|
||||||
|
fn drop(&mut self) {
|
||||||
|
sys::unlock(&self.file);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Drop for ControlLock {
|
||||||
|
fn drop(&mut self) {
|
||||||
|
let _ = std::fs::remove_file(&self.owner);
|
||||||
|
sys::unlock(&self.file);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(windows)]
|
||||||
|
mod sys {
|
||||||
|
use std::fs::File;
|
||||||
|
use std::os::windows::io::AsRawHandle;
|
||||||
|
use windows_sys::Win32::Storage::FileSystem::{LockFile, UnlockFile};
|
||||||
|
|
||||||
|
/// `LockFile` on byte 0, length 1: the call `msvcrt.locking` makes. Non-blocking.
|
||||||
|
pub fn try_lock(file: &File) -> std::io::Result<bool> {
|
||||||
|
let ok = unsafe { LockFile(file.as_raw_handle() as _, 0, 0, 1, 0) };
|
||||||
|
if ok != 0 {
|
||||||
|
return Ok(true);
|
||||||
|
}
|
||||||
|
let err = std::io::Error::last_os_error();
|
||||||
|
// ERROR_LOCK_VIOLATION (33): someone else holds it.
|
||||||
|
if err.raw_os_error() == Some(33) {
|
||||||
|
Ok(false)
|
||||||
|
} else {
|
||||||
|
Err(err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn unlock(file: &File) {
|
||||||
|
unsafe {
|
||||||
|
UnlockFile(file.as_raw_handle() as _, 0, 0, 1, 0);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(not(windows))]
|
||||||
|
mod sys {
|
||||||
|
use std::fs::File;
|
||||||
|
pub fn try_lock(_: &File) -> std::io::Result<bool> {
|
||||||
|
Ok(true)
|
||||||
|
}
|
||||||
|
pub fn unlock(_: &File) {}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_damaged_record_is_no_process() {
|
||||||
|
let d = tempfile::tempdir().unwrap();
|
||||||
|
std::fs::create_dir_all(dir(d.path())).unwrap();
|
||||||
|
std::fs::write(dir(d.path()).join("mysql.json"), [0u8; 116]).unwrap();
|
||||||
|
assert!(running(d.path(), "mysql").is_none());
|
||||||
|
std::fs::write(dir(d.path()).join("auth.json"), b"").unwrap();
|
||||||
|
assert!(running(d.path(), "auth").is_none());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn this_process_is_recorded_and_found_running() {
|
||||||
|
let d = tempfile::tempdir().unwrap();
|
||||||
|
let me = record(d.path(), "probe", std::process::id()).unwrap();
|
||||||
|
assert_eq!(running(d.path(), "probe"), Some(me));
|
||||||
|
let text = std::fs::read_to_string(dir(d.path()).join("probe.json")).unwrap();
|
||||||
|
assert!(text.starts_with("{\n \"pid\": ") && text.ends_with("}\n"), "{text}");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn one_action_at_a_time() {
|
||||||
|
let d = tempfile::tempdir().unwrap();
|
||||||
|
let first = ControlLock::acquire(d.path(), "start-all", Duration::from_secs(1), &|_| {}).unwrap();
|
||||||
|
let owner: serde_json::Value = fsx::read_json(&dir(d.path()).join("control-owner.json")).unwrap();
|
||||||
|
assert_eq!(owner["action"], "start-all");
|
||||||
|
let said = std::sync::Mutex::new(Vec::new());
|
||||||
|
let second = ControlLock::acquire(d.path(), "stop-all", Duration::from_millis(600), &|m| said.lock().unwrap().push(m.to_string()));
|
||||||
|
if cfg!(windows) {
|
||||||
|
let err = second.err().expect("the second action waits and gives up").to_string();
|
||||||
|
assert!(err.contains("Another start/stop action is in progress") && err.contains("start-all"), "{err}");
|
||||||
|
assert_eq!(said.lock().unwrap().len(), 1);
|
||||||
|
}
|
||||||
|
drop(first);
|
||||||
|
assert!(!dir(d.path()).join("control-owner.json").exists());
|
||||||
|
ControlLock::acquire(d.path(), "stop-all", Duration::from_secs(1), &|_| {}).unwrap();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,300 @@
|
|||||||
|
//! The world server and the bug-report relay beside it (`manage.py start_world`, `watch_world`, `wait_relay`),
|
||||||
|
//! and the detailed-logging switch (`debug_logs`).
|
||||||
|
//!
|
||||||
|
//! A world is started through a supervisor process that outlives the caller: it starts `worldserver.exe`, keeps
|
||||||
|
//! the relay running while the world runs, and stops the relay when the world ends. The supervisor is
|
||||||
|
//! `coa-launcher.exe watch-world`, or `manage.py watch-world` on a repack that does not ship it yet (both write
|
||||||
|
//! the same records). The relay itself is still the Python `BugReport/relay.py`, run through the repack's
|
||||||
|
//! Python, until it is ported too.
|
||||||
|
|
||||||
|
use std::path::{Path, PathBuf};
|
||||||
|
use std::time::{Duration, Instant};
|
||||||
|
|
||||||
|
use crate::error::{Error, ErrorCode, Result};
|
||||||
|
use crate::launcher::services::{self, ensure_free, mysql, spawn, start_mysql, wait_ready, Progress};
|
||||||
|
use crate::launcher::spawn::Proc;
|
||||||
|
use crate::launcher::{settings::Settings, squid, state};
|
||||||
|
|
||||||
|
fn stop_relay_flag(root: &Path) -> std::path::PathBuf {
|
||||||
|
state::dir(root).join("stop-relay")
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The relay is up and has finished starting (it records itself as `relay-ready` once it serves).
|
||||||
|
pub fn wait_relay(root: &Path) -> Result<()> {
|
||||||
|
let until = Instant::now() + Duration::from_secs(20);
|
||||||
|
while Instant::now() < until {
|
||||||
|
if let (Some(relay), Some(ready)) = (state::running(root, "relay"), state::running(root, "relay-ready")) {
|
||||||
|
if relay == ready {
|
||||||
|
return Ok(());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
std::thread::sleep(Duration::from_millis(250));
|
||||||
|
}
|
||||||
|
Err(Error::Invalid("Bug-report relay is not ready; check BugReport/Logs/relay.log.".into()))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The process that runs `watch-world` for a started world.
|
||||||
|
#[derive(Debug, Clone)]
|
||||||
|
pub enum Supervisor {
|
||||||
|
/// `coa-launcher.exe` (this crate's launcher).
|
||||||
|
Launcher(PathBuf),
|
||||||
|
/// The repack's Python with `Scripts/manage.py`.
|
||||||
|
Python { python: PathBuf, script: PathBuf },
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Supervisor {
|
||||||
|
/// The supervisor a repack ships: `Scripts/coa-launcher.exe` when present, otherwise its Python launcher.
|
||||||
|
pub fn of(root: &Path) -> Result<Supervisor> {
|
||||||
|
let exe = root.join("Scripts/coa-launcher.exe");
|
||||||
|
if exe.is_file() {
|
||||||
|
return Ok(Supervisor::Launcher(exe));
|
||||||
|
}
|
||||||
|
let python = squid::package_root(root).join("Runtime/python/python.exe");
|
||||||
|
let script = root.join("Scripts/manage.py");
|
||||||
|
if python.is_file() && script.is_file() {
|
||||||
|
return Ok(Supervisor::Python { python, script });
|
||||||
|
}
|
||||||
|
Err(Error::Service(
|
||||||
|
ErrorCode::ServerFilesIncomplete,
|
||||||
|
"This server has no world supervisor (Scripts/coa-launcher.exe or Scripts/manage.py). Repair its program files.".into(),
|
||||||
|
))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// How long a world may take to open both of its listeners, together: slow worlds (many bots, a cold disk) are
|
||||||
|
/// common, and the limit must not depend on the bot module.
|
||||||
|
const WORLD_STARTUP_SECONDS: u64 = 1500;
|
||||||
|
|
||||||
|
/// Wait until the world's console answers a command (it can listen before it accepts logins).
|
||||||
|
fn wait_console(root: &Path, cfg: &Settings, until: Instant) -> Result<()> {
|
||||||
|
let mut last = String::new();
|
||||||
|
while Instant::now() < until {
|
||||||
|
if state::running(root, "world").is_none() {
|
||||||
|
return Err(Error::Service(
|
||||||
|
ErrorCode::StartupFailed,
|
||||||
|
"World startup failed: worldserver stopped before its console accepted commands.".into(),
|
||||||
|
));
|
||||||
|
}
|
||||||
|
match crate::ra::Ra::connect_to(cfg.ra_port, &cfg.ra_username, &cfg.ra_password).and_then(|mut ra| ra.run("server info")) {
|
||||||
|
Ok(_) => return Ok(()),
|
||||||
|
Err(e) => last = e.to_string(),
|
||||||
|
}
|
||||||
|
std::thread::sleep(Duration::from_millis(500));
|
||||||
|
}
|
||||||
|
Err(Error::Service(ErrorCode::StartupFailed, format!("World startup failed: its console is still starting. {last}")))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn seconds_until(until: Instant) -> u64 {
|
||||||
|
until.saturating_duration_since(Instant::now()).as_secs()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Start the world (and its database, unless it is shared), and wait until its console accepts commands.
|
||||||
|
pub fn start_world(root: &Path, cfg: &Settings, offset: i32, supervisor: &Supervisor, progress: Progress) -> Result<()> {
|
||||||
|
start_mysql(root, cfg, progress)?;
|
||||||
|
squid::validate_bots(root)?;
|
||||||
|
let until = Instant::now() + Duration::from_secs(squid::startup_timeout(root).max(WORLD_STARTUP_SECONDS));
|
||||||
|
if state::running(root, "world").is_some() {
|
||||||
|
if state::running(root, "supervisor").is_none() {
|
||||||
|
return Err(Error::Service(
|
||||||
|
ErrorCode::WorldserverAlreadyRunning,
|
||||||
|
"Worldserver has no repack supervisor. Use Stop_All_Server.bat before restarting it.".into(),
|
||||||
|
));
|
||||||
|
}
|
||||||
|
wait_ready(root, "world", cfg.world_port, seconds_until(until))?;
|
||||||
|
wait_relay(root)?;
|
||||||
|
wait_console(root, cfg, until)?;
|
||||||
|
progress("Worldserver and bug-report relay are already running.");
|
||||||
|
return Ok(());
|
||||||
|
}
|
||||||
|
ensure_free(cfg.world_port, progress)?;
|
||||||
|
ensure_free(cfg.ra_port, progress)?;
|
||||||
|
if state::running(root, "supervisor").is_some() || state::running(root, "relay").is_some() {
|
||||||
|
return Err(Error::Service(
|
||||||
|
ErrorCode::OperationInProgress,
|
||||||
|
"The previous world/relay shutdown is still finishing. Try again shortly.".into(),
|
||||||
|
));
|
||||||
|
}
|
||||||
|
squid::prepare_playerbots(root, cfg.mysql_port, &|sql| mysql(root, Some(sql), None), progress)?;
|
||||||
|
progress("Starting worldserver and its bug-report relay...");
|
||||||
|
let _ = std::fs::remove_file(stop_relay_flag(root));
|
||||||
|
let offset_text = offset.to_string();
|
||||||
|
let root_text = root.to_string_lossy().into_owned();
|
||||||
|
let log = root.join("Core/Logs/supervisor.log");
|
||||||
|
match supervisor {
|
||||||
|
Supervisor::Launcher(exe) => {
|
||||||
|
spawn(root, "supervisor", exe, &["--root", &root_text, "--port-offset", &offset_text, "watch-world"], root, &log, &cfg.env_remove)?
|
||||||
|
}
|
||||||
|
Supervisor::Python { python, script } => {
|
||||||
|
let script = script.to_string_lossy().into_owned();
|
||||||
|
spawn(root, "supervisor", python, &["-B", &script, "--port-offset", &offset_text, "watch-world"], root, &log, &cfg.env_remove)?
|
||||||
|
}
|
||||||
|
};
|
||||||
|
let first = Instant::now() + Duration::from_secs(20);
|
||||||
|
while state::running(root, "world").is_none() && Instant::now() < first {
|
||||||
|
if state::running(root, "supervisor").is_none() {
|
||||||
|
return Err(Error::Service(ErrorCode::StartupFailed, "World startup failed; check Core/Logs/supervisor.log.".into()));
|
||||||
|
}
|
||||||
|
std::thread::sleep(Duration::from_millis(250));
|
||||||
|
}
|
||||||
|
wait_ready(root, "world", cfg.world_port, seconds_until(until))?;
|
||||||
|
wait_ready(root, "world", cfg.ra_port, seconds_until(until))?;
|
||||||
|
wait_relay(root)?;
|
||||||
|
wait_console(root, cfg, until)?;
|
||||||
|
progress("Worldserver and automatic bug reporting are ready.");
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn spawn_child(root: &Path, name: &str, exe: &Path, args: &[&str], cwd: &Path, log: &Path) -> Result<Proc> {
|
||||||
|
// The supervisor was started with the environment its services should have.
|
||||||
|
let child = crate::launcher::spawn::start(exe, args, cwd, log, &[])?;
|
||||||
|
state::record(root, name, child.pid)?;
|
||||||
|
Ok(child)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The relay worker: `coa-launcher relay-worker` when the supervisor is the launcher (`launcher`), otherwise the
|
||||||
|
/// repack's Python running `Scripts/manage.py relay-worker` (BugReport/relay.py).
|
||||||
|
fn spawn_relay(root: &Path, launcher: Option<&Path>) -> Result<Proc> {
|
||||||
|
let log = root.join("BugReport/Logs/relay.log");
|
||||||
|
if let Some(exe) = launcher {
|
||||||
|
let root_text = root.to_string_lossy().into_owned();
|
||||||
|
return spawn_child(root, "relay", exe, &["--root", &root_text, "relay-worker"], root, &log);
|
||||||
|
}
|
||||||
|
let python = squid::package_root(root).join("Runtime/python/python.exe");
|
||||||
|
let manage = root.join("Scripts/manage.py");
|
||||||
|
if !python.is_file() || !manage.is_file() {
|
||||||
|
return Err(Error::Invalid("The bug-report relay needs the repack's Python and Scripts/manage.py.".into()));
|
||||||
|
}
|
||||||
|
let manage = manage.to_string_lossy().into_owned();
|
||||||
|
spawn_child(root, "relay", &python, &["-B", &manage, "relay-worker"], root, &root.join("BugReport/Logs/relay.log"))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The supervisor (`watch-world`): run the world, keep the relay alive while it runs, stop the relay after it.
|
||||||
|
/// `launcher` is the launcher executable that runs the relay (`None`: the Python relay).
|
||||||
|
pub fn watch_world(root: &Path, launcher: Option<&Path>, log: Progress) -> Result<()> {
|
||||||
|
squid::validate_bots(root)?;
|
||||||
|
let world = spawn_child(root, "world", &root.join("Core/worldserver.exe"), &["-c", "configs/worldserver.conf"], &root.join("Core"), &root.join("Core/Logs/world-console.log"))?;
|
||||||
|
let mut relay: Option<Proc> = None;
|
||||||
|
while world.try_wait().is_none() {
|
||||||
|
let dead = relay.as_ref().is_none_or(|r| r.try_wait().is_some());
|
||||||
|
if dead {
|
||||||
|
match spawn_relay(root, launcher) {
|
||||||
|
Ok(r) => relay = Some(r),
|
||||||
|
Err(e) => {
|
||||||
|
log(&format!("Report relay could not start ({e}); retrying."));
|
||||||
|
std::thread::sleep(Duration::from_secs(5));
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
std::thread::sleep(Duration::from_secs(2));
|
||||||
|
}
|
||||||
|
std::fs::write(stop_relay_flag(root), b"")?;
|
||||||
|
if let Some(r) = relay {
|
||||||
|
let until = Instant::now() + Duration::from_secs(40);
|
||||||
|
while r.try_wait().is_none() && Instant::now() < until {
|
||||||
|
std::thread::sleep(Duration::from_millis(250));
|
||||||
|
}
|
||||||
|
if r.try_wait().is_none() {
|
||||||
|
// An interrupted POST stays uncertain in the relay's journal; it is not resent.
|
||||||
|
if let Some(record) = state::running(root, "relay") {
|
||||||
|
services::terminate(&record)?;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------------------------------------------------------
|
||||||
|
// Detailed logging (Debug_Logs_On.bat / Debug_Logs_Off.bat)
|
||||||
|
// ---------------------------------------------------------------------------------------------------------------
|
||||||
|
|
||||||
|
const DEBUG_TEMPLATES: [&str; 2] = ["worldserver.conf.template", "authserver.conf.template"];
|
||||||
|
|
||||||
|
/// One template line with every logger forced to Trace and the console/server appenders to the most detail.
|
||||||
|
fn debug_line(line: &str) -> String {
|
||||||
|
let body = line.strip_prefix('#').unwrap_or(line).trim_start();
|
||||||
|
for appender in ["Appender.Console", "Appender.Server"] {
|
||||||
|
if let Some(rest) = body.strip_prefix(appender).and_then(|r| r.strip_prefix('=')) {
|
||||||
|
let parts: Vec<&str> = rest.splitn(4, ',').collect();
|
||||||
|
if parts.len() == 4 && parts[..3].iter().all(|p| !p.is_empty() && p.bytes().all(|b| b.is_ascii_digit())) {
|
||||||
|
return format!("{appender}={},6,7,{}", parts[0], parts[3]);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if let Some(rest) = body.strip_prefix("Logger.") {
|
||||||
|
if let Some((name, value)) = rest.split_once('=') {
|
||||||
|
if !name.is_empty() && name.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'_' || b == b'.') {
|
||||||
|
if let Some((level, tail)) = value.split_once(',') {
|
||||||
|
if !level.is_empty() && level.bytes().all(|b| b.is_ascii_digit()) {
|
||||||
|
return format!("Logger.{name}=6,{tail}");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let t = line.trim_end();
|
||||||
|
if let Some(v) = t.strip_prefix("Log.Async.Enable") {
|
||||||
|
let v = v.trim_start();
|
||||||
|
if let Some(n) = v.strip_prefix('=') {
|
||||||
|
let n = n.trim();
|
||||||
|
if !n.is_empty() && n.bytes().all(|b| b.is_ascii_digit()) {
|
||||||
|
return "Log.Async.Enable = 1".into();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
line.to_string()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Turn detailed logging on or off (the templates; services apply it at their next start). Returns the changed
|
||||||
|
/// templates.
|
||||||
|
pub fn debug_logs(root: &Path, enable: bool) -> Result<Vec<String>> {
|
||||||
|
let mut changed = Vec::new();
|
||||||
|
for name in DEBUG_TEMPLATES {
|
||||||
|
let path = root.join("Settings").join(name);
|
||||||
|
let original = root.join("Settings").join(format!("{name}.original"));
|
||||||
|
if !original.exists() {
|
||||||
|
std::fs::write(&original, std::fs::read(&path)?)?;
|
||||||
|
}
|
||||||
|
let new_bytes = if enable {
|
||||||
|
let text = String::from_utf8(std::fs::read(&original)?).map_err(|_| Error::Invalid(format!("{name} is not UTF-8.")))?;
|
||||||
|
let newline = if text.contains("\r\n") { "\r\n" } else { "\n" };
|
||||||
|
let mut out = text.lines().map(debug_line).collect::<Vec<_>>().join(newline);
|
||||||
|
if text.ends_with('\n') {
|
||||||
|
out.push_str(newline);
|
||||||
|
}
|
||||||
|
out.into_bytes()
|
||||||
|
} else {
|
||||||
|
std::fs::read(&original)?
|
||||||
|
};
|
||||||
|
if std::fs::read(&path)? != new_bytes {
|
||||||
|
std::fs::write(&path, &new_bytes)?;
|
||||||
|
changed.push(name.to_string());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
state::write_json(&state::dir(root).join("debug-logs.json"), &serde_json::json!({ "enabled": enable }))?;
|
||||||
|
Ok(changed)
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn detailed_logging_rewrites_loggers_and_restores_the_original() {
|
||||||
|
let d = tempfile::tempdir().unwrap();
|
||||||
|
std::fs::create_dir_all(d.path().join("Settings")).unwrap();
|
||||||
|
let world = "Appender.Console=1,3,0\r\nAppender.Server=2,2,0,Server.log,w\r\n#Logger.module=4,Console Server\r\nLogger.root=5,Console Server\r\nLog.Async.Enable = 0\r\nOther = 1\r\n";
|
||||||
|
std::fs::write(d.path().join("Settings/worldserver.conf.template"), world).unwrap();
|
||||||
|
std::fs::write(d.path().join("Settings/authserver.conf.template"), "Logger.root=2,Console\n").unwrap();
|
||||||
|
let changed = debug_logs(d.path(), true).unwrap();
|
||||||
|
assert_eq!(changed.len(), 2);
|
||||||
|
assert_eq!(
|
||||||
|
std::fs::read_to_string(d.path().join("Settings/worldserver.conf.template")).unwrap(),
|
||||||
|
"Appender.Console=1,3,0\r\nAppender.Server=2,6,7,Server.log,w\r\nLogger.module=6,Console Server\r\nLogger.root=6,Console Server\r\nLog.Async.Enable = 1\r\nOther = 1\r\n"
|
||||||
|
);
|
||||||
|
assert_eq!(debug_logs(d.path(), true).unwrap().len(), 0, "already on");
|
||||||
|
debug_logs(d.path(), false).unwrap();
|
||||||
|
assert_eq!(std::fs::read_to_string(d.path().join("Settings/worldserver.conf.template")).unwrap(), world);
|
||||||
|
assert_eq!(services::status(d.path())["debugLogs"], false);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,85 +0,0 @@
|
|||||||
import runpy
|
|
||||||
import sys
|
|
||||||
import time
|
|
||||||
from pathlib import Path
|
|
||||||
|
|
||||||
script = sys.argv[1]
|
|
||||||
sys.path.insert(0, str(Path(script).resolve().parent))
|
|
||||||
sys.argv = sys.argv[1:]
|
|
||||||
launcher = runpy.run_path(script, run_name="coa_manager_launcher")
|
|
||||||
original_wait = launcher["wait_ready"]
|
|
||||||
world_deadline = None
|
|
||||||
|
|
||||||
|
|
||||||
def wait_ready(name, port, seconds=180):
|
|
||||||
global world_deadline
|
|
||||||
if name == "mysql":
|
|
||||||
seconds = max(seconds, 300)
|
|
||||||
elif name == "world":
|
|
||||||
# Both game and console listeners belong to one startup, including on old repacks.
|
|
||||||
# Ordinary CoA worlds can load slowly too; this must not depend on SQUID.
|
|
||||||
if world_deadline is None:
|
|
||||||
world_deadline = time.monotonic() + max(seconds, 1500)
|
|
||||||
seconds = max(0, world_deadline - time.monotonic())
|
|
||||||
return original_wait(name, port, seconds)
|
|
||||||
|
|
||||||
|
|
||||||
launcher["start_mysql"].__globals__["wait_ready"] = wait_ready
|
|
||||||
if sys.argv[1] in ("stop-all", "force-stop-all"):
|
|
||||||
shutdown = launcher["stop_all"].__globals__
|
|
||||||
class UnsafeShutdown(Exception):
|
|
||||||
pass
|
|
||||||
|
|
||||||
def stop_owned_world(world):
|
|
||||||
expected = Path(script).resolve().parents[1] / "Core" / "worldserver.exe"
|
|
||||||
if Path(world.get("exe", "")) != expected or not shutdown["same_process"](world):
|
|
||||||
raise UnsafeShutdown("World process ownership could not be verified; the database was left running.")
|
|
||||||
try:
|
|
||||||
shutdown["terminate"](world)
|
|
||||||
except (OSError, RuntimeError) as error:
|
|
||||||
raise UnsafeShutdown("Worldserver could not be stopped safely; its database was left running.") from error
|
|
||||||
if not shutdown["wait_stopped"](world, 90):
|
|
||||||
raise UnsafeShutdown("Worldserver is still stopping; its database was left running.")
|
|
||||||
|
|
||||||
if "ra" in shutdown:
|
|
||||||
original_ra = shutdown["ra"]
|
|
||||||
|
|
||||||
def shutdown_command(command, config):
|
|
||||||
try:
|
|
||||||
return original_ra(command, config)
|
|
||||||
except (OSError, RuntimeError):
|
|
||||||
if not command.startswith("server shutdown "):
|
|
||||||
raise
|
|
||||||
world = shutdown["process"]("world")
|
|
||||||
if not world:
|
|
||||||
return "Worldserver has already stopped."
|
|
||||||
stop_owned_world(world)
|
|
||||||
return "Stopped this server's recorded world process without its unavailable console."
|
|
||||||
|
|
||||||
shutdown["ra"] = shutdown_command
|
|
||||||
config = launcher["settings"]()
|
|
||||||
with launcher["control_lock"]():
|
|
||||||
if sys.argv[1] == "force-stop-all":
|
|
||||||
world = shutdown["process"]("world")
|
|
||||||
if world:
|
|
||||||
stop_owned_world(world)
|
|
||||||
print("Force-stopped this server's verified world process; unsaved progress may be lost.", flush=True)
|
|
||||||
launcher["stop_all"](config)
|
|
||||||
else:
|
|
||||||
launcher["main"]()
|
|
||||||
if sys.argv[1] in ("start-all", "start-world"):
|
|
||||||
config = launcher["settings"]()
|
|
||||||
deadline = world_deadline if world_deadline is not None else time.monotonic() + 1500
|
|
||||||
last_error = None
|
|
||||||
while time.monotonic() < deadline:
|
|
||||||
if not launcher["process"]("world"):
|
|
||||||
raise RuntimeError("World startup failed: worldserver stopped before its console accepted commands.")
|
|
||||||
try:
|
|
||||||
launcher["ra"]("server info", config)
|
|
||||||
print("World console is accepting commands.", flush=True)
|
|
||||||
break
|
|
||||||
except (OSError, RuntimeError) as error:
|
|
||||||
last_error = error
|
|
||||||
time.sleep(0.5)
|
|
||||||
else:
|
|
||||||
raise RuntimeError(f"World startup failed: its console is still starting. {last_error}")
|
|
||||||
@@ -0,0 +1,222 @@
|
|||||||
|
//! `Scripts/manage.py` as Managers up to 0.9.10 edited it.
|
||||||
|
//!
|
||||||
|
//! Those Managers ran the repack's Python launcher themselves and changed its text: an import fix for their bridge
|
||||||
|
//! and a realm-profile patch (database and realm row of the active realm). This Manager starts servers with
|
||||||
|
//! [`crate::launcher`] and never edits the file; it only has to recognise those edits, so that an update or a file
|
||||||
|
//! check treats a file one of them changed as unmodified. Nothing here writes a file.
|
||||||
|
|
||||||
|
use crate::error::{Error, Result};
|
||||||
|
|
||||||
|
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";
|
||||||
|
|
||||||
|
fn launcher_insert() -> String {
|
||||||
|
LAUNCHER_REALM_INSERT
|
||||||
|
.replace("profiles-v1", "profiles-v2")
|
||||||
|
.replace(
|
||||||
|
"return 2 if",
|
||||||
|
"return 3 if coa_realm() == 'reborn' else 2 if",
|
||||||
|
)
|
||||||
|
.replace(
|
||||||
|
"return 'Wildcard' if",
|
||||||
|
"return 'Warcraft Reborn' if coa_realm() == 'reborn' else 'Wildcard' if",
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn launcher_replacements() -> Vec<(&'static str, String)> {
|
||||||
|
LAUNCHER_REALM_REPLACEMENTS.iter().map(|(from, to)| (*from, to
|
||||||
|
.replace("\"acore_world_wildcard\" if", "\"acore_world_reborn\" if coa_realm() == 'reborn' else \"acore_world_wildcard\" if")
|
||||||
|
.replace("\"acore_characters_wildcard\" if", "\"acore_characters_reborn\" if coa_realm() == 'reborn' else \"acore_characters_wildcard\" if"))).collect()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The realm-profile patch older Managers wrote.
|
||||||
|
pub(crate) fn patch_launcher(source: &str) -> Result<String> {
|
||||||
|
if source.contains("# coa-manager-realm-profiles-v2") {
|
||||||
|
return Ok(source.into());
|
||||||
|
}
|
||||||
|
if source.contains("# coa-manager-realm-profiles-v1") {
|
||||||
|
let original = unpatch_launcher(source)
|
||||||
|
.ok_or_else(|| Error::Invalid("Unrecognised realm launcher patch.".into()))?;
|
||||||
|
return patch_launcher(&original);
|
||||||
|
}
|
||||||
|
let mut out = source.to_string();
|
||||||
|
for (from, to) in launcher_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);
|
||||||
|
}
|
||||||
|
// 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!("{}{marker}", launcher_insert())))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Reverse only our exact realm transformation; callers must verify the recovered original hash.
|
||||||
|
pub(crate) fn unpatch_launcher(source: &str) -> Option<String> {
|
||||||
|
let (insert, replacements) = if source.contains(&launcher_insert()) {
|
||||||
|
(launcher_insert(), launcher_replacements())
|
||||||
|
} else if source.contains(LAUNCHER_REALM_INSERT) {
|
||||||
|
(
|
||||||
|
LAUNCHER_REALM_INSERT.into(),
|
||||||
|
LAUNCHER_REALM_REPLACEMENTS
|
||||||
|
.iter()
|
||||||
|
.map(|(a, b)| (*a, b.to_string()))
|
||||||
|
.collect(),
|
||||||
|
)
|
||||||
|
} else {
|
||||||
|
return None;
|
||||||
|
};
|
||||||
|
let mut original = source.replacen(&insert, "", 1);
|
||||||
|
for (from, to) in &replacements {
|
||||||
|
original = original.replace(to, from);
|
||||||
|
}
|
||||||
|
let mut check = original.clone();
|
||||||
|
for (from, to) in &replacements {
|
||||||
|
check = check.replace(from, to);
|
||||||
|
}
|
||||||
|
check = check.replace(
|
||||||
|
"if __name__ == \"__main__\":",
|
||||||
|
&format!("{insert}if __name__ == \"__main__\":"),
|
||||||
|
);
|
||||||
|
(check == source).then_some(original)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The import fix older Managers wrote (needed to run manage.py through their bridge).
|
||||||
|
pub(crate) fn patch_launcher_imports(text: &str) -> Result<String> {
|
||||||
|
let line = "sys.path.insert(0, str(Path(__file__).resolve().parent))";
|
||||||
|
if !text.contains("from squid_playerbots import") || text.contains(line) {
|
||||||
|
return Ok(text.into());
|
||||||
|
}
|
||||||
|
let root = "ROOT = Path(__file__).resolve().parents[1]";
|
||||||
|
if !text.contains(root) || !text.lines().any(|line| line.trim() == "import sys") {
|
||||||
|
return Err(Error::Invalid(
|
||||||
|
"The server launcher cannot load its integration scripts. Repair its program files."
|
||||||
|
.into(),
|
||||||
|
));
|
||||||
|
}
|
||||||
|
Ok(text.replacen(root, &format!("{root}\n{line}"), 1))
|
||||||
|
}
|
||||||
|
|
||||||
|
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;
|
||||||
|
}
|
||||||
|
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()),
|
||||||
|
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
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
use crate::fsx;
|
||||||
|
use std::collections::BTreeMap;
|
||||||
|
use std::fs;
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn old_launcher_upgrades_and_both_patch_versions_are_reversible() {
|
||||||
|
let original = "(\"WorldDatabaseInfo\", \"acore_world\")\n(\"CharacterDatabaseInfo\", \"acore_characters\")\nSET name='AzerothCore',address=\nWHERE id=1;\nmysql(\"UPDATE acore_auth.realmlist SET flag=0\nif __name__ == \"__main__\":\n";
|
||||||
|
let mut old = original.to_string();
|
||||||
|
for (from, to) in LAUNCHER_REALM_REPLACEMENTS {
|
||||||
|
old = old.replace(from, to);
|
||||||
|
}
|
||||||
|
old = old.replace(
|
||||||
|
"if __name__ == \"__main__\":",
|
||||||
|
&format!("{LAUNCHER_REALM_INSERT}if __name__ == \"__main__\":"),
|
||||||
|
);
|
||||||
|
assert_eq!(unpatch_launcher(&old).as_deref(), Some(original));
|
||||||
|
let new = patch_launcher(&old).unwrap();
|
||||||
|
assert!(new.contains("acore_world_reborn"));
|
||||||
|
assert!(new.contains("return 3 if coa_realm() == 'reborn'"));
|
||||||
|
assert!(new.contains("return 'Warcraft Reborn' if"));
|
||||||
|
assert_eq!(patch_launcher(&new).unwrap(), new);
|
||||||
|
assert_eq!(unpatch_launcher(&new).as_deref(), Some(original));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn unknown_launcher_is_refused_without_partial_patching() {
|
||||||
|
assert!(patch_launcher("print('custom launcher')").is_err());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn launcher_import_fix_is_idempotent_and_retains_other_code() {
|
||||||
|
let text = "import sys\nROOT = Path(__file__).resolve().parents[1]\nfrom squid_playerbots import validate_bots\ncustom = 42\n";
|
||||||
|
let fixed = patch_launcher_imports(text).unwrap();
|
||||||
|
assert!(fixed.contains("sys.path.insert(0, str(Path(__file__).resolve().parent))"));
|
||||||
|
assert!(fixed.ends_with("custom = 42\n"));
|
||||||
|
assert_eq!(patch_launcher_imports(&fixed).unwrap(), fixed);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_launcher_patched_by_an_older_manager_stays_pristine_but_external_edits_conflict() {
|
||||||
|
let d = tempfile::tempdir().unwrap();
|
||||||
|
let root = d.path().join("server");
|
||||||
|
let source = "(\"WorldDatabaseInfo\", \"acore_world\")\n(\"CharacterDatabaseInfo\", \"acore_characters\")\nSET name='AzerothCore',address=\nWHERE id=1;\nmysql(\"UPDATE acore_auth.realmlist SET flag=0\nif __name__ == \"__main__\":\n";
|
||||||
|
fsx::atomic_write(&root.join("Scripts/manage.py"), source.as_bytes()).unwrap();
|
||||||
|
// What an older Manager left: the realm patch applied and its hash recorded as the pristine one.
|
||||||
|
let patched = patch_launcher(source).unwrap();
|
||||||
|
fsx::atomic_write(&root.join("Scripts/manage.py"), patched.as_bytes()).unwrap();
|
||||||
|
let mut meta = crate::registry::InstallMeta::new(crate::registry::InstallKind::New, &root);
|
||||||
|
meta.original_hashes.insert("Scripts/manage.py".into(), fsx::sha256_bytes(patched.as_bytes()));
|
||||||
|
crate::registry::MetaDir::create(&root, &meta).unwrap();
|
||||||
|
assert!(crate::diag::verify_managed(&root, &meta).is_empty());
|
||||||
|
let manifest: crate::manifest::Manifest = serde_json::from_value(serde_json::json!({
|
||||||
|
"schema": 1, "kind": "update", "version": "2.0.0", "core": {"commit": null}, "builtAt": "fixture", "minManagerVersion": "0.1.0",
|
||||||
|
"files": [{"path":"Scripts/manage.py","sha256":fsx::sha256_bytes(b"next release"),"size":12,"owner":"core","policy":"replace"}]
|
||||||
|
})).unwrap();
|
||||||
|
assert_eq!(
|
||||||
|
crate::update::plan(&root, &meta, &manifest, &BTreeMap::new(), None).unwrap()[0].action,
|
||||||
|
crate::update::Action::Replace
|
||||||
|
);
|
||||||
|
let mut modified = fs::read(root.join("Scripts/manage.py")).unwrap();
|
||||||
|
modified.extend_from_slice(b"# custom edit\n");
|
||||||
|
fsx::atomic_write(&root.join("Scripts/manage.py"), &modified).unwrap();
|
||||||
|
assert_eq!(
|
||||||
|
crate::update::plan(&root, &meta, &manifest, &BTreeMap::new(), None).unwrap()[0].action,
|
||||||
|
crate::update::Action::Conflict
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -11,6 +11,7 @@ pub mod accounts;
|
|||||||
pub mod allsettings;
|
pub mod allsettings;
|
||||||
pub mod analyzer;
|
pub mod analyzer;
|
||||||
pub mod backup;
|
pub mod backup;
|
||||||
|
pub mod build_cache;
|
||||||
pub mod build_engine;
|
pub mod build_engine;
|
||||||
pub mod catalogue;
|
pub mod catalogue;
|
||||||
pub mod channels;
|
pub mod channels;
|
||||||
@@ -31,6 +32,7 @@ pub mod diag;
|
|||||||
pub mod docker;
|
pub mod docker;
|
||||||
pub mod download;
|
pub mod download;
|
||||||
pub mod driver;
|
pub mod driver;
|
||||||
|
pub mod legacy_launcher;
|
||||||
pub mod error;
|
pub mod error;
|
||||||
pub mod firewall;
|
pub mod firewall;
|
||||||
pub mod friends;
|
pub mod friends;
|
||||||
@@ -39,10 +41,12 @@ pub mod glue_config;
|
|||||||
pub mod health;
|
pub mod health;
|
||||||
pub mod install;
|
pub mod install;
|
||||||
pub mod layout;
|
pub mod layout;
|
||||||
|
pub mod launcher;
|
||||||
pub mod logging;
|
pub mod logging;
|
||||||
pub mod server_logging;
|
pub mod server_logging;
|
||||||
pub mod manifest;
|
pub mod manifest;
|
||||||
pub mod migrations;
|
pub mod migrations;
|
||||||
|
pub mod modular_copy;
|
||||||
pub mod modules;
|
pub mod modules;
|
||||||
pub mod module_sources;
|
pub mod module_sources;
|
||||||
pub mod msvc_setup;
|
pub mod msvc_setup;
|
||||||
@@ -72,7 +76,6 @@ pub mod remote_client;
|
|||||||
pub mod repair;
|
pub mod repair;
|
||||||
pub mod report;
|
pub mod report;
|
||||||
pub mod schema_check;
|
pub mod schema_check;
|
||||||
pub mod server_migration;
|
|
||||||
pub mod signing;
|
pub mod signing;
|
||||||
pub mod solver;
|
pub mod solver;
|
||||||
pub mod squid;
|
pub mod squid;
|
||||||
|
|||||||
@@ -0,0 +1,521 @@
|
|||||||
|
//! A modular copy of a classic server, next to it.
|
||||||
|
//!
|
||||||
|
//! A server with the classic core (every module compiled into `worldserver.exe`) is never converted in place.
|
||||||
|
//! The Modules Preview installs a new server beside it and copies the old one's data into it: every game
|
||||||
|
//! database (accounts, characters, world, bots) and the module settings. The old server is only read:
|
||||||
|
//!
|
||||||
|
//! * if its database is running, the schemas are dumped from it (consistent snapshots, nothing is written);
|
||||||
|
//! * if it is stopped, its data files are copied to a private folder and read by a temporary database
|
||||||
|
//! process of the NEW server; nothing of the old server is started or executed.
|
||||||
|
//!
|
||||||
|
//! The new server then takes the preview core like any other server (the caller applies the update).
|
||||||
|
|
||||||
|
use std::fs;
|
||||||
|
use std::path::{Path, PathBuf};
|
||||||
|
use std::process::{Child, Command, Stdio};
|
||||||
|
use std::time::{Duration, Instant};
|
||||||
|
|
||||||
|
use serde::Serialize;
|
||||||
|
|
||||||
|
use crate::db::{Account, Db};
|
||||||
|
use crate::error::{Error, Result};
|
||||||
|
use crate::fsx;
|
||||||
|
use crate::process::ServiceState;
|
||||||
|
|
||||||
|
/// Whether `root` runs the classic core: a Windows repack whose `worldserver.exe` carries no plugin-host
|
||||||
|
/// fingerprint.
|
||||||
|
pub fn is_classic(root: &Path) -> bool {
|
||||||
|
!crate::docker::is_docker(root)
|
||||||
|
&& root.join("Core/worldserver.exe").is_file()
|
||||||
|
&& crate::provenance::realm_host_fingerprint(root).is_none()
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Serialize)]
|
||||||
|
pub struct CopyReport {
|
||||||
|
pub schemas: Vec<String>,
|
||||||
|
pub accounts: u64,
|
||||||
|
pub characters: u64,
|
||||||
|
pub config_files: Vec<String>,
|
||||||
|
/// How the old data was read: "running database" or "copy of the stopped database".
|
||||||
|
pub read_from: String,
|
||||||
|
/// World settings the owner changed (Server Configuration) that were set on the new server too.
|
||||||
|
pub world_settings: Vec<String>,
|
||||||
|
/// Changed world settings the new server's configuration does not take, with the reason.
|
||||||
|
pub world_settings_skipped: Vec<String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// What a modular copy of `old` would take, read without changing anything: the old server is never started,
|
||||||
|
/// and its database is only queried when it is already running.
|
||||||
|
#[derive(Debug, Clone, Serialize)]
|
||||||
|
pub struct CopyPreview {
|
||||||
|
pub path: PathBuf,
|
||||||
|
/// The classic core (modules compiled in): the only kind that is copied.
|
||||||
|
pub classic: bool,
|
||||||
|
/// Already a modular core: it is added as it is, not copied.
|
||||||
|
pub modular: bool,
|
||||||
|
pub version: Option<String>,
|
||||||
|
/// "running", "stopped" or "missing" (no database folder).
|
||||||
|
pub database: String,
|
||||||
|
/// Read from the running database; `None` when it is stopped (they are counted while copying).
|
||||||
|
pub accounts: Option<u64>,
|
||||||
|
pub characters: Option<u64>,
|
||||||
|
pub schemas: Vec<String>,
|
||||||
|
/// Size of the old database files; a stopped database is copied once more while it is read.
|
||||||
|
pub database_bytes: u64,
|
||||||
|
/// Settings files that go along (module configs, realm profiles).
|
||||||
|
pub config_files: Vec<String>,
|
||||||
|
/// Extra worlds of the old server (`.realms/<name>`). Their databases are in the same MySQL and go along, and
|
||||||
|
/// the copied realm profile switches them on; the new server prepares their folders when it starts them.
|
||||||
|
pub extra_worlds: Vec<String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn preview(old: &Path) -> Result<CopyPreview> {
|
||||||
|
if !old.is_dir() {
|
||||||
|
return Err(Error::Invalid(format!("{} is not a folder.", old.display())));
|
||||||
|
}
|
||||||
|
let classic = is_classic(old);
|
||||||
|
let modular = !crate::docker::is_docker(old)
|
||||||
|
&& old.join("Core/worldserver.exe").is_file()
|
||||||
|
&& crate::provenance::realm_host_fingerprint(old).is_some();
|
||||||
|
let version = crate::registry::metadata_dir_for(old)
|
||||||
|
.ok()
|
||||||
|
.and_then(|dir| crate::registry::MetaDir::open(&dir).ok())
|
||||||
|
.and_then(|(_, meta)| meta.core.version);
|
||||||
|
let data = old.join("mysql/data");
|
||||||
|
let has_data = data.join("mysql").is_dir();
|
||||||
|
let observed = crate::process::observe(old, &crate::layout::read_ports(old));
|
||||||
|
let running_db = (has_data && observed.mysql.state == ServiceState::Running)
|
||||||
|
.then(|| Db::from_repack(old, Account::Admin).ok())
|
||||||
|
.flatten()
|
||||||
|
.filter(|db| db.ping())
|
||||||
|
.map(|db| db.for_realm(crate::realms::Mode::Coa));
|
||||||
|
let (database, accounts, characters, schemas) = match &running_db {
|
||||||
|
Some(db) => (
|
||||||
|
"running",
|
||||||
|
Some(count(db, "SELECT COUNT(*) FROM acore_auth.account;")),
|
||||||
|
Some(count(db, "SELECT COUNT(*) FROM acore_characters.characters;")),
|
||||||
|
game_schemas(db).unwrap_or_default(),
|
||||||
|
),
|
||||||
|
None if has_data => ("stopped", None, None, Vec::new()),
|
||||||
|
None => ("missing", None, None, Vec::new()),
|
||||||
|
};
|
||||||
|
let mut extra_worlds: Vec<String> = fs::read_dir(old.join(".realms"))
|
||||||
|
.map(|rd| rd.flatten().filter(|e| e.path().is_dir()).map(|e| e.file_name().to_string_lossy().into_owned()).collect())
|
||||||
|
.unwrap_or_default();
|
||||||
|
extra_worlds.sort();
|
||||||
|
Ok(CopyPreview {
|
||||||
|
path: old.to_path_buf(),
|
||||||
|
classic,
|
||||||
|
modular,
|
||||||
|
version,
|
||||||
|
database: database.into(),
|
||||||
|
accounts,
|
||||||
|
characters,
|
||||||
|
schemas,
|
||||||
|
database_bytes: if has_data { dir_size(&data) } else { 0 },
|
||||||
|
config_files: settings_files(old),
|
||||||
|
extra_worlds,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Game schemas of a CoA server: `acore_*` (auth, characters, world, their Wildcard/Reborn variants, bots).
|
||||||
|
fn game_schemas(db: &Db) -> Result<Vec<String>> {
|
||||||
|
let mut out: Vec<String> = db
|
||||||
|
.query("SELECT SCHEMA_NAME FROM information_schema.SCHEMATA WHERE SCHEMA_NAME LIKE 'acore\\_%' ORDER BY SCHEMA_NAME;")?
|
||||||
|
.lines()
|
||||||
|
.map(|l| l.trim().to_string())
|
||||||
|
.filter(|s| !s.is_empty() && s.chars().all(|c| c.is_ascii_alphanumeric() || c == '_'))
|
||||||
|
// work schemas a restore leaves behind are not game data
|
||||||
|
.filter(|s| !s.contains("_restore_") && !s.contains("_before_restore_"))
|
||||||
|
.collect();
|
||||||
|
out.dedup();
|
||||||
|
if !out.iter().any(|s| s == "acore_auth") || !out.iter().any(|s| s == "acore_characters") {
|
||||||
|
return Err(Error::Invalid("The old server's database has no accounts or characters schema.".into()));
|
||||||
|
}
|
||||||
|
Ok(out)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn count(db: &Db, sql: &str) -> u64 {
|
||||||
|
db.query(sql).ok().and_then(|s| s.trim().parse().ok()).unwrap_or(0)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A database process of the new server reading a private copy of the old server's stopped data files.
|
||||||
|
struct TemporaryDatabase {
|
||||||
|
child: Child,
|
||||||
|
dir: PathBuf,
|
||||||
|
db: Option<Db>,
|
||||||
|
stopped: bool,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl TemporaryDatabase {
|
||||||
|
/// Shut it down cleanly, force it if it does not go, and remove the private copy. Fails if the process is
|
||||||
|
/// still there afterwards, so a leftover database never holds the new server's files.
|
||||||
|
fn stop(&mut self) -> Result<()> {
|
||||||
|
if self.stopped {
|
||||||
|
return Ok(());
|
||||||
|
}
|
||||||
|
if let Some(db) = &self.db {
|
||||||
|
let _ = db.shutdown_server();
|
||||||
|
}
|
||||||
|
let deadline = Instant::now() + Duration::from_secs(90);
|
||||||
|
loop {
|
||||||
|
match self.child.try_wait()? {
|
||||||
|
Some(_) => break,
|
||||||
|
None if Instant::now() > deadline => {
|
||||||
|
tracing::warn!(pid = self.child.id(), "temporary database did not shut down; terminating it");
|
||||||
|
self.child.kill()?;
|
||||||
|
self.child.wait()?;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
None => std::thread::sleep(Duration::from_millis(250)),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
self.stopped = true;
|
||||||
|
fs::remove_dir_all(&self.dir)?;
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Drop for TemporaryDatabase {
|
||||||
|
fn drop(&mut self) {
|
||||||
|
if !self.stopped {
|
||||||
|
if let Err(e) = self.stop() {
|
||||||
|
tracing::warn!(error = %e, pid = self.child.id(), "temporary database left behind");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn copy_tree(from: &Path, to: &Path) -> Result<u64> {
|
||||||
|
let mut bytes = 0;
|
||||||
|
fs::create_dir_all(to)?;
|
||||||
|
for entry in fs::read_dir(from)? {
|
||||||
|
let entry = entry?;
|
||||||
|
let md = fs::symlink_metadata(entry.path())?;
|
||||||
|
if md.file_type().is_symlink() {
|
||||||
|
return Err(Error::Invalid(format!("{} is a link; the database folder is not copied.", entry.path().display())));
|
||||||
|
}
|
||||||
|
let target = to.join(entry.file_name());
|
||||||
|
if md.is_dir() {
|
||||||
|
bytes += copy_tree(&entry.path(), &target)?;
|
||||||
|
} else {
|
||||||
|
fs::copy(entry.path(), &target)?;
|
||||||
|
bytes += md.len();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Ok(bytes)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn dir_size(dir: &Path) -> u64 {
|
||||||
|
fs::read_dir(dir).map(|rd| rd.flatten().map(|e| {
|
||||||
|
let p = e.path();
|
||||||
|
if p.is_dir() { dir_size(&p) } else { e.metadata().map(|m| m.len()).unwrap_or(0) }
|
||||||
|
}).sum()).unwrap_or(0)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn start_temporary(old: &Path, new: &Path, work: &Path, progress: &dyn Fn(&str)) -> Result<(TemporaryDatabase, Db)> {
|
||||||
|
let source = old.join("mysql/data");
|
||||||
|
if !source.join("mysql").is_dir() || !source.join("ibdata1").is_file() {
|
||||||
|
return Err(Error::Invalid("The old server's database folder is incomplete.".into()));
|
||||||
|
}
|
||||||
|
let dir = work.join("old-database");
|
||||||
|
let _ = fs::remove_dir_all(&dir);
|
||||||
|
fsx::require_space(work, dir_size(&source))?;
|
||||||
|
progress("Copying the old server's database files");
|
||||||
|
let data = dir.join("data");
|
||||||
|
copy_tree(&source, &data)?;
|
||||||
|
let (root_password, _) = crate::db::credentials(old)?;
|
||||||
|
let bin = new.join("mysql/bin");
|
||||||
|
let port = crate::install::free_port()?;
|
||||||
|
let child = Command::new(bin.join("mysqld.exe"))
|
||||||
|
.arg("--no-defaults")
|
||||||
|
.arg(format!("--basedir={}", new.join("mysql").display()))
|
||||||
|
.arg(format!("--datadir={}", data.display()))
|
||||||
|
.arg(format!("--port={port}"))
|
||||||
|
.args(["--bind-address=127.0.0.1", "--mysqlx=0", "--skip-log-bin", "--character-set-server=utf8mb4",
|
||||||
|
"--collation-server=utf8mb4_unicode_ci", "--max_allowed_packet=128M"])
|
||||||
|
.arg(format!("--log-error={}", dir.join("mysql-error.log").display()))
|
||||||
|
.arg(format!("--pid-file={}", dir.join("mysql.pid").display()))
|
||||||
|
.stdout(Stdio::null())
|
||||||
|
.stderr(Stdio::null())
|
||||||
|
.creation_flags_hidden()
|
||||||
|
.spawn()?;
|
||||||
|
let db = Db::with_tools(bin, port, "root", &root_password, crate::realms::Mode::Coa);
|
||||||
|
let mut temp = TemporaryDatabase { child, dir, db: Some(db.clone()), stopped: false };
|
||||||
|
progress("Opening the copy of the old database");
|
||||||
|
let deadline = Instant::now() + Duration::from_secs(300);
|
||||||
|
while !db.ping() {
|
||||||
|
if let Ok(Some(status)) = temp.child.try_wait() {
|
||||||
|
let log = fs::read_to_string(temp.dir.join("mysql-error.log")).unwrap_or_default();
|
||||||
|
let tail: Vec<&str> = log.lines().rev().take(8).collect();
|
||||||
|
return Err(Error::Invalid(format!(
|
||||||
|
"The copy of the old database did not open ({status}). {}",
|
||||||
|
tail.into_iter().rev().collect::<Vec<_>>().join(" ")
|
||||||
|
)));
|
||||||
|
}
|
||||||
|
if Instant::now() > deadline {
|
||||||
|
return Err(Error::Invalid("The copy of the old database did not open within 5 minutes.".into()));
|
||||||
|
}
|
||||||
|
std::thread::sleep(Duration::from_millis(300));
|
||||||
|
}
|
||||||
|
Ok((temp, db))
|
||||||
|
}
|
||||||
|
|
||||||
|
trait HiddenWindow {
|
||||||
|
fn creation_flags_hidden(&mut self) -> &mut Self;
|
||||||
|
}
|
||||||
|
|
||||||
|
impl HiddenWindow for Command {
|
||||||
|
fn creation_flags_hidden(&mut self) -> &mut Self {
|
||||||
|
#[cfg(windows)]
|
||||||
|
{
|
||||||
|
use std::os::windows::process::CommandExt;
|
||||||
|
self.creation_flags(0x0800_0000);
|
||||||
|
}
|
||||||
|
self
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Settings the owner may have changed that the new core can take as they are: the module configs
|
||||||
|
/// (`Core/configs/modules/*.conf`; the shipped `.dist` files belong to the new core) and the realm profiles.
|
||||||
|
/// `worldserver.conf` and `authserver.conf` are rendered by the launcher from the new server's own
|
||||||
|
/// templates at every start, so they are not copied.
|
||||||
|
fn settings_files(old: &Path) -> Vec<String> {
|
||||||
|
crate::backup::config_files(old)
|
||||||
|
.into_iter()
|
||||||
|
.filter(|f| {
|
||||||
|
(f.starts_with("Core/configs/modules/") && f.ends_with(".conf") && !f.ends_with("/mod_ascension_compat.conf"))
|
||||||
|
|| f.starts_with("Settings/realm-profile")
|
||||||
|
})
|
||||||
|
.collect()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Copy the old server's data into `new`, a server just installed and not yet started by anyone.
|
||||||
|
pub fn copy_data(old: &Path, new: &Path, progress: &dyn Fn(&str)) -> Result<CopyReport> {
|
||||||
|
if !is_classic(old) {
|
||||||
|
return Err(Error::Invalid("Only a server with the classic core is copied.".into()));
|
||||||
|
}
|
||||||
|
if fsx::canonicalize_lenient(old)? == fsx::canonicalize_lenient(new)? {
|
||||||
|
return Err(Error::Invalid("The new server must be in another folder.".into()));
|
||||||
|
}
|
||||||
|
let work = crate::registry::metadata_dir_for(new)?.join("import");
|
||||||
|
let _ = fs::remove_dir_all(&work);
|
||||||
|
fs::create_dir_all(&work)?;
|
||||||
|
|
||||||
|
// 1. Read the old databases.
|
||||||
|
let observed = crate::process::observe(old, &crate::layout::read_ports(old));
|
||||||
|
let running = observed.mysql.state == ServiceState::Running
|
||||||
|
&& Db::from_repack(old, Account::Admin).map(|db| db.ping()).unwrap_or(false);
|
||||||
|
let mut temporary: Option<TemporaryDatabase> = None;
|
||||||
|
let (source, read_from) = if running {
|
||||||
|
(Db::from_repack(old, Account::Admin)?.for_realm(crate::realms::Mode::Coa), "running database")
|
||||||
|
} else {
|
||||||
|
let (temp, db) = start_temporary(old, new, &work, progress)?;
|
||||||
|
temporary = Some(temp);
|
||||||
|
(db, "copy of the stopped database")
|
||||||
|
};
|
||||||
|
let schemas = game_schemas(&source)?;
|
||||||
|
let accounts = count(&source, "SELECT COUNT(*) FROM acore_auth.account;");
|
||||||
|
let characters = count(&source, "SELECT COUNT(*) FROM acore_characters.characters;");
|
||||||
|
let mut dumps = Vec::new();
|
||||||
|
for schema in &schemas {
|
||||||
|
progress(&format!("Copying {schema}"));
|
||||||
|
let file = work.join(format!("{schema}.sql.zst"));
|
||||||
|
source.dump_to(schema, &file)?;
|
||||||
|
dumps.push((schema.clone(), file));
|
||||||
|
}
|
||||||
|
// The private copy of the old data files is not needed any more; its database must be gone before the new
|
||||||
|
// server's own database starts.
|
||||||
|
if let Some(mut temp) = temporary.take() {
|
||||||
|
progress("Closing the copy of the old database");
|
||||||
|
temp.stop()?;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 2. Put them into the new server, on ports nobody uses, so a running old server is not disturbed.
|
||||||
|
crate::install::with_scratch_ports(new, || {
|
||||||
|
crate::backup::with_database(new, |db| {
|
||||||
|
let db = db.clone().for_realm(crate::realms::Mode::Coa);
|
||||||
|
for (schema, file) in &dumps {
|
||||||
|
progress(&format!("Importing {schema}"));
|
||||||
|
db.query(&format!(
|
||||||
|
"DROP DATABASE IF EXISTS `{schema}`; CREATE DATABASE `{schema}` CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;"
|
||||||
|
))?;
|
||||||
|
db.import_from(schema, file)?;
|
||||||
|
}
|
||||||
|
let (a, c) = (
|
||||||
|
count(&db, "SELECT COUNT(*) FROM acore_auth.account;"),
|
||||||
|
count(&db, "SELECT COUNT(*) FROM acore_characters.characters;"),
|
||||||
|
);
|
||||||
|
if (a, c) != (accounts, characters) {
|
||||||
|
return Err(Error::Invalid(format!(
|
||||||
|
"The copy is incomplete: {a} of {accounts} accounts and {c} of {characters} characters arrived."
|
||||||
|
)));
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
})
|
||||||
|
})?;
|
||||||
|
|
||||||
|
// 3. Settings: module configs and realm profiles; ports and console login as the old server had them
|
||||||
|
// (the console account lives in the copied accounts database).
|
||||||
|
progress("Copying settings");
|
||||||
|
let files = settings_files(old);
|
||||||
|
for rel in &files {
|
||||||
|
let from = fsx::ensure_within(old, &fsx::safe_join(old, rel)?)?;
|
||||||
|
let to = fsx::ensure_within(new, &fsx::safe_join(new, rel)?)?;
|
||||||
|
fsx::atomic_write(&to, &fs::read(from)?)?;
|
||||||
|
}
|
||||||
|
let old_repack: serde_json::Value = fsx::read_json(&old.join("Settings/repack.json"))?;
|
||||||
|
let mut repack: serde_json::Value = fsx::read_json(&new.join("Settings/repack.json"))?;
|
||||||
|
if let (Some(dst), Some(src)) = (repack.as_object_mut(), old_repack.as_object()) {
|
||||||
|
for (k, v) in src {
|
||||||
|
dst.insert(k.clone(), v.clone());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
fsx::atomic_write_json(&new.join("Settings/repack.json"), &repack)?;
|
||||||
|
let _ = fs::remove_dir_all(&work);
|
||||||
|
progress("Copying world settings");
|
||||||
|
let (world_settings, world_settings_skipped) = carry_world_settings(old, new)?;
|
||||||
|
Ok(CopyReport {
|
||||||
|
schemas,
|
||||||
|
accounts,
|
||||||
|
characters,
|
||||||
|
config_files: files,
|
||||||
|
read_from: read_from.into(),
|
||||||
|
world_settings,
|
||||||
|
world_settings_skipped,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The world settings changed on the old server (they live in its `Settings/worldserver.conf.template`, which the new
|
||||||
|
/// server does not take: it keeps the template of its own version) are set on the new server through the same checks
|
||||||
|
/// the Server Configuration page uses. Settings the Manager owns (ports, folders, passwords) are not among them.
|
||||||
|
///
|
||||||
|
/// The shipped template already differs from `worldserver.conf.dist` in many places, so "changed" means "differs from
|
||||||
|
/// what the new server has now": for a copy onto the same version that is exactly what the owner changed. (A value the
|
||||||
|
/// owner never touched but a newer release ships differently cannot be told apart from an owner's change; it keeps the
|
||||||
|
/// old server's value, which is what that server ran with.)
|
||||||
|
fn carry_world_settings(old: &Path, new: &Path) -> Result<(Vec<String>, Vec<String>)> {
|
||||||
|
let current: std::collections::BTreeMap<String, String> =
|
||||||
|
crate::allsettings::list(new)?.into_iter().map(|i| (i.key, i.value)).collect();
|
||||||
|
let mut changes = std::collections::BTreeMap::new();
|
||||||
|
let mut skipped = Vec::new();
|
||||||
|
for item in crate::allsettings::list(old)? {
|
||||||
|
match current.get(&item.key) {
|
||||||
|
Some(now) if *now == item.value => {}
|
||||||
|
Some(_) => {
|
||||||
|
changes.insert(item.key, item.value);
|
||||||
|
}
|
||||||
|
None if item.changed => skipped.push(format!("{}: not a setting of the new version", item.key)),
|
||||||
|
None => {}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let meta = crate::registry::metadata_dir_for(new)?;
|
||||||
|
let mut carried = Vec::new();
|
||||||
|
match crate::allsettings::save(new, &meta, &changes) {
|
||||||
|
Ok(set) => carried.extend(set),
|
||||||
|
// One value the new version refuses must not lose the others: set them one at a time.
|
||||||
|
Err(_) => {
|
||||||
|
for (key, value) in changes {
|
||||||
|
match crate::allsettings::save(new, &meta, &std::collections::BTreeMap::from([(key.clone(), value)])) {
|
||||||
|
Ok(set) => carried.extend(set),
|
||||||
|
Err(e) => skipped.push(format!("{key}: {e}")),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Ok((carried, skipped))
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
|
||||||
|
const DIST: &str = "[worldserver]\r\n\r\n#\r\n# Rate.Drop.Item.Epic\r\n# Description: Epic drops.\r\n# Default: 1\r\n#\r\n\r\nRate.Drop.Item.Epic = 1\r\n\r\n#\r\n# LoginDatabaseInfo\r\n# Description: secret\r\n#\r\n\r\nLoginDatabaseInfo = \"127.0.0.1;3306;a;b;c\"\r\n\r\n#\r\n# Instance.ResetTimeHour\r\n# Description: Hour of the reset.\r\n# Default: 4\r\n#\r\n\r\nInstance.ResetTimeHour = 4\r\n";
|
||||||
|
|
||||||
|
fn world(root: &Path, dist: &str, conf: &str) {
|
||||||
|
fs::create_dir_all(root.join("Core/configs")).unwrap();
|
||||||
|
fs::create_dir_all(root.join("Settings")).unwrap();
|
||||||
|
fs::create_dir_all(crate::registry::metadata_dir_for(root).unwrap()).unwrap();
|
||||||
|
fs::write(root.join("Core/configs/worldserver.conf.dist"), dist).unwrap();
|
||||||
|
fs::write(root.join("Settings/worldserver.conf.template"), conf).unwrap();
|
||||||
|
fs::write(root.join("Core/configs/worldserver.conf"), conf).unwrap();
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn changed_world_settings_go_to_the_new_server_and_the_rest_keep_its_defaults() {
|
||||||
|
let dir = tempfile::tempdir().unwrap();
|
||||||
|
let (old, new) = (dir.path().join("old"), dir.path().join("new"));
|
||||||
|
let old_dist = format!("{DIST}\r\n#\r\n# Old.Only\r\n# Description: gone in the new version.\r\n# Default: 1\r\n#\r\n\r\nOld.Only = 1\r\n");
|
||||||
|
world(&old, &old_dist, "[worldserver]\r\nRate.Drop.Item.Epic = 3\r\nOld.Only = 2\r\nLoginDatabaseInfo = \"old\"\r\n");
|
||||||
|
world(&new, DIST, "[worldserver]\r\nLoginDatabaseInfo = \"new\"\r\n");
|
||||||
|
|
||||||
|
let (carried, skipped) = carry_world_settings(&old, &new).unwrap();
|
||||||
|
assert_eq!(carried, ["Rate.Drop.Item.Epic"]);
|
||||||
|
assert_eq!(skipped.len(), 1, "{skipped:?}");
|
||||||
|
assert!(skipped[0].starts_with("Old.Only"));
|
||||||
|
for f in ["Settings/worldserver.conf.template", "Core/configs/worldserver.conf"] {
|
||||||
|
let text = fs::read_to_string(new.join(f)).unwrap();
|
||||||
|
assert!(text.contains("Rate.Drop.Item.Epic = 3"), "{f}: {text}");
|
||||||
|
assert!(text.contains("LoginDatabaseInfo = \"new\""), "the Manager's own settings stay: {text}");
|
||||||
|
assert!(!text.contains("Old.Only"), "{text}");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn the_preview_of_a_folder_reads_only_files() {
|
||||||
|
let dir = tempfile::tempdir().unwrap();
|
||||||
|
let classic = dir.path().join("classic");
|
||||||
|
fs::create_dir_all(classic.join("Core/configs/modules")).unwrap();
|
||||||
|
fs::create_dir_all(classic.join("mysql/data/mysql")).unwrap();
|
||||||
|
fs::create_dir_all(classic.join(".realms/secondary")).unwrap();
|
||||||
|
fs::write(classic.join("Core/worldserver.exe"), b"not a plugin host").unwrap();
|
||||||
|
fs::write(classic.join("Core/configs/modules/mod_x.conf"), b"x").unwrap();
|
||||||
|
fs::write(classic.join("mysql/data/ibdata1"), vec![0u8; 2048]).unwrap();
|
||||||
|
let p = preview(&classic).unwrap();
|
||||||
|
assert!(p.classic && !p.modular);
|
||||||
|
assert_eq!(p.database, "stopped");
|
||||||
|
assert_eq!((p.accounts, p.characters), (None, None), "a stopped database is not opened");
|
||||||
|
assert_eq!(p.database_bytes, 2048);
|
||||||
|
assert_eq!(p.config_files, ["Core/configs/modules/mod_x.conf"]);
|
||||||
|
assert_eq!(p.extra_worlds, ["secondary"]);
|
||||||
|
|
||||||
|
let empty = dir.path().join("empty");
|
||||||
|
fs::create_dir_all(&empty).unwrap();
|
||||||
|
let p = preview(&empty).unwrap();
|
||||||
|
assert!(!p.classic && !p.modular);
|
||||||
|
assert_eq!(p.database, "missing");
|
||||||
|
assert!(preview(&dir.path().join("nowhere")).is_err());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn only_owner_settings_are_copied() {
|
||||||
|
let dir = tempfile::tempdir().unwrap();
|
||||||
|
let old = dir.path();
|
||||||
|
for rel in [
|
||||||
|
"Core/configs/worldserver.conf",
|
||||||
|
"Core/configs/worldserver.conf.dist",
|
||||||
|
"Core/configs/modules/mod_x.conf",
|
||||||
|
"Core/configs/modules/mod_x.conf.dist",
|
||||||
|
"Core/configs/modules/mod_ascension_compat.conf",
|
||||||
|
"Settings/repack.json",
|
||||||
|
"Settings/worldserver.conf.template",
|
||||||
|
"Settings/realm-profile.json",
|
||||||
|
] {
|
||||||
|
let p = old.join(rel);
|
||||||
|
fs::create_dir_all(p.parent().unwrap()).unwrap();
|
||||||
|
fs::write(p, b"x").unwrap();
|
||||||
|
}
|
||||||
|
let mut got = settings_files(old);
|
||||||
|
got.sort();
|
||||||
|
assert_eq!(got, vec![
|
||||||
|
"Core/configs/modules/mod_x.conf".to_string(),
|
||||||
|
"Settings/realm-profile.json".to_string(),
|
||||||
|
]);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_folder_without_a_core_is_not_classic() {
|
||||||
|
let dir = tempfile::tempdir().unwrap();
|
||||||
|
assert!(!is_classic(dir.path()));
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -61,10 +61,24 @@ pub fn fetch_pinned(owner: &str, repo: &str, sha: &str, cache_root: &Path) -> Re
|
|||||||
Ok(dest)
|
Ok(dest)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Game-client and media files a server module's build never reads (client patches, DBC/map data, textures,
|
||||||
|
/// archives). Some repositories carry hundreds of MB of them next to a few KB of server code; they are left out
|
||||||
|
/// of the sources, and their names listed in `.coa_skipped_assets`.
|
||||||
|
fn is_client_asset(rel: &Path) -> bool {
|
||||||
|
const EXT: [&str; 22] = [
|
||||||
|
"mpq", "dbc", "db2", "adt", "wdt", "wdl", "wmo", "m2", "skin", "anim", "blp", "tga", "trs", "vmtile", "vmtree",
|
||||||
|
"mmap", "mmtile", "zip", "7z", "rar", "mp3", "ogg",
|
||||||
|
];
|
||||||
|
rel.extension()
|
||||||
|
.and_then(|e| e.to_str())
|
||||||
|
.is_some_and(|e| EXT.iter().any(|x| x.eq_ignore_ascii_case(e)))
|
||||||
|
}
|
||||||
|
|
||||||
/// Extracts a GitHub tar.gz (one top-level `<repo>-<sha>/` folder) into `dest`, files and folders only.
|
/// Extracts a GitHub tar.gz (one top-level `<repo>-<sha>/` folder) into `dest`, files and folders only.
|
||||||
fn unpack(reader: impl Read, dest: &Path) -> Result<()> {
|
pub(crate) fn unpack(reader: impl Read, dest: &Path) -> Result<()> {
|
||||||
let mut archive = tar::Archive::new(flate2::read::GzDecoder::new(reader));
|
let mut archive = tar::Archive::new(flate2::read::GzDecoder::new(reader));
|
||||||
let mut total = 0u64;
|
let mut total = 0u64;
|
||||||
|
let mut skipped = Vec::new();
|
||||||
for entry in archive.entries()? {
|
for entry in archive.entries()? {
|
||||||
let mut entry = entry?;
|
let mut entry = entry?;
|
||||||
let path = entry.path()?.into_owned();
|
let path = entry.path()?.into_owned();
|
||||||
@@ -79,6 +93,8 @@ fn unpack(reader: impl Read, dest: &Path) -> Result<()> {
|
|||||||
let target = dest.join(&rel);
|
let target = dest.join(&rel);
|
||||||
if kind.is_dir() {
|
if kind.is_dir() {
|
||||||
fs::create_dir_all(&target)?;
|
fs::create_dir_all(&target)?;
|
||||||
|
} else if kind.is_file() && is_client_asset(&rel) {
|
||||||
|
skipped.push(rel.to_string_lossy().replace('\\', "/"));
|
||||||
} else if kind.is_file() {
|
} else if kind.is_file() {
|
||||||
total += entry.header().size()?;
|
total += entry.header().size()?;
|
||||||
if total > MAX_ARCHIVE_BYTES {
|
if total > MAX_ARCHIVE_BYTES {
|
||||||
@@ -90,6 +106,9 @@ fn unpack(reader: impl Read, dest: &Path) -> Result<()> {
|
|||||||
}
|
}
|
||||||
// Links and special entries are not part of a module's sources: skipped.
|
// Links and special entries are not part of a module's sources: skipped.
|
||||||
}
|
}
|
||||||
|
if !skipped.is_empty() {
|
||||||
|
fs::write(dest.join(".coa_skipped_assets"), skipped.join("\n"))?;
|
||||||
|
}
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -118,6 +137,24 @@ mod tests {
|
|||||||
assert!(dir.path().join("conf/x.conf.dist").is_file());
|
assert!(dir.path().join("conf/x.conf.dist").is_file());
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn client_assets_are_left_out_and_listed() {
|
||||||
|
let dir = tempfile::tempdir().unwrap();
|
||||||
|
let gz = tar_gz(&[
|
||||||
|
("mod-bg-abc/server-side/src/BG.cpp", b"int a;"),
|
||||||
|
("mod-bg-abc/client-side/DBFilesClient/Spell.dbc", b"dbc"),
|
||||||
|
("mod-bg-abc/client-data.zip", b"zip"),
|
||||||
|
("mod-bg-abc/data/sql/db-world/bg.sql", b"SELECT 1;"),
|
||||||
|
]);
|
||||||
|
unpack(&gz[..], dir.path()).unwrap();
|
||||||
|
assert!(dir.path().join("server-side/src/BG.cpp").is_file());
|
||||||
|
assert!(dir.path().join("data/sql/db-world/bg.sql").is_file());
|
||||||
|
assert!(!dir.path().join("client-side/DBFilesClient/Spell.dbc").exists());
|
||||||
|
assert!(!dir.path().join("client-data.zip").exists());
|
||||||
|
let listed = fs::read_to_string(dir.path().join(".coa_skipped_assets")).unwrap();
|
||||||
|
assert!(listed.contains("Spell.dbc") && listed.contains("client-data.zip"));
|
||||||
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn bad_names_are_refused_before_any_download() {
|
fn bad_names_are_refused_before_any_download() {
|
||||||
let dir = tempfile::tempdir().unwrap();
|
let dir = tempfile::tempdir().unwrap();
|
||||||
|
|||||||
@@ -711,6 +711,17 @@ pub fn ensure_bot_exclusivity(root: &Path) -> Result<()> {
|
|||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Dungeon Clear is part of SQUID's Playerbots (the plugin core builds it into the SQUID DLL): it goes on
|
||||||
|
/// with SQUID, and off with it, wherever its config exists.
|
||||||
|
fn switch_on_dungeon_clear_with_squid(cat: &[Entry], root: &Path, meta: &Path) {
|
||||||
|
if let Some(dc) = cat.iter().find(|entry| entry.id == "dungeon-clear") {
|
||||||
|
let name = conf_name(root, dc);
|
||||||
|
if dir(root).join(&name).exists() || dir(root).join(format!("{name}.dist")).exists() {
|
||||||
|
let _ = set_enabled_in(cat, root, meta, "dungeon-clear", true);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
fn set_enabled_in(cat: &[Entry], root: &Path, meta: &Path, id: &str, on: bool) -> Result<()> {
|
fn set_enabled_in(cat: &[Entry], root: &Path, meta: &Path, id: &str, on: bool) -> Result<()> {
|
||||||
match entry_in(cat, id) {
|
match entry_in(cat, id) {
|
||||||
Ok(e) => {
|
Ok(e) => {
|
||||||
@@ -770,6 +781,7 @@ fn set_enabled_in(cat: &[Entry], root: &Path, meta: &Path, id: &str, on: bool) -
|
|||||||
}
|
}
|
||||||
if id == "playerbots" && on {
|
if id == "playerbots" && on {
|
||||||
let _ = crate::plugins::record_squid_migrations_applied(root);
|
let _ = crate::plugins::record_squid_migrations_applied(root);
|
||||||
|
switch_on_dungeon_clear_with_squid(cat, root, meta);
|
||||||
}
|
}
|
||||||
|
|
||||||
tracing::info!(module = id, on, "module switched");
|
tracing::info!(module = id, on, "module switched");
|
||||||
@@ -806,6 +818,9 @@ fn set_enabled_in(cat: &[Entry], root: &Path, meta: &Path, id: &str, on: bool) -
|
|||||||
let _ = set_enabled_in(cat, root, meta, "dungeon-clear", false);
|
let _ = set_enabled_in(cat, root, meta, "dungeon-clear", false);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
if id == "playerbots" && on {
|
||||||
|
switch_on_dungeon_clear_with_squid(cat, root, meta);
|
||||||
|
}
|
||||||
return Ok(());
|
return Ok(());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -1255,7 +1270,7 @@ mod tests {
|
|||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn dungeon_clear_requires_squid_and_stays_off_after_squid_is_reenabled() {
|
fn dungeon_clear_requires_squid_and_follows_it() {
|
||||||
let d = tempfile::tempdir().unwrap();
|
let d = tempfile::tempdir().unwrap();
|
||||||
let root = d.path();
|
let root = d.path();
|
||||||
fs::create_dir_all(dir(root)).unwrap();
|
fs::create_dir_all(dir(root)).unwrap();
|
||||||
@@ -1266,13 +1281,13 @@ mod tests {
|
|||||||
let cat = catalog();
|
let cat = catalog();
|
||||||
assert!(set_enabled_in(&cat, root, root, "dungeon-clear", true).is_err());
|
assert!(set_enabled_in(&cat, root, root, "dungeon-clear", true).is_err());
|
||||||
assert!(!list_in(&cat, root).iter().find(|entry| entry.id == "dungeon-clear").unwrap().switchable);
|
assert!(!list_in(&cat, root).iter().find(|entry| entry.id == "dungeon-clear").unwrap().switchable);
|
||||||
|
// part of SQUID: on with it, off with it, on again with it
|
||||||
set_enabled_in(&cat, root, root, "playerbots", true).unwrap();
|
set_enabled_in(&cat, root, root, "playerbots", true).unwrap();
|
||||||
set_enabled_in(&cat, root, root, "dungeon-clear", true).unwrap();
|
|
||||||
assert!(read(&dungeon).unwrap().get("DungeonClear.Enable").map(truthy).unwrap());
|
assert!(read(&dungeon).unwrap().get("DungeonClear.Enable").map(truthy).unwrap());
|
||||||
set_enabled_in(&cat, root, root, "playerbots", false).unwrap();
|
set_enabled_in(&cat, root, root, "playerbots", false).unwrap();
|
||||||
assert!(!read(&dungeon).unwrap().get("DungeonClear.Enable").map(truthy).unwrap());
|
assert!(!read(&dungeon).unwrap().get("DungeonClear.Enable").map(truthy).unwrap());
|
||||||
set_enabled_in(&cat, root, root, "playerbots", true).unwrap();
|
set_enabled_in(&cat, root, root, "playerbots", true).unwrap();
|
||||||
assert!(!read(&dungeon).unwrap().get("DungeonClear.Enable").map(truthy).unwrap());
|
assert!(read(&dungeon).unwrap().get("DungeonClear.Enable").map(truthy).unwrap());
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
|
|||||||
File diff suppressed because it is too large.
Load diff
@@ -49,19 +49,17 @@ fn parse_counts(out: &str) -> Result<Population> {
|
|||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Read-only query with the game's own database account. Routes automatically to the active realm's characters database.
|
/// Read-only query with the game's own database account. Requires the database to be running.
|
||||||
pub fn query(root: &Path) -> Result<Population> {
|
pub fn query(root: &Path) -> Result<Population> {
|
||||||
let mode = crate::realms::state(root)
|
let db = Db::from_repack(root, Account::App)?;
|
||||||
.map(|s| s.active)
|
query_with(
|
||||||
.unwrap_or(crate::realms::Mode::Coa);
|
&db,
|
||||||
query_for_realm(root, mode)
|
&bot_account_prefix(root),
|
||||||
|
&crate::accounts::squid_bot_prefix(root),
|
||||||
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
fn counts_sql(prefix: &str, squid_prefix: &str) -> Result<String> {
|
fn counts_sql(prefix: &str, squid_prefix: &str) -> Result<String> {
|
||||||
counts_sql_for_db("acore_characters", prefix, squid_prefix)
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn counts_sql_for_db(chars_db: &str, prefix: &str, squid_prefix: &str) -> Result<String> {
|
|
||||||
if [prefix, squid_prefix]
|
if [prefix, squid_prefix]
|
||||||
.iter()
|
.iter()
|
||||||
.any(|prefix| prefix.is_empty() || !prefix.chars().all(|c| c.is_ascii_alphanumeric()))
|
.any(|prefix| prefix.is_empty() || !prefix.chars().all(|c| c.is_ascii_alphanumeric()))
|
||||||
@@ -76,9 +74,9 @@ pub fn counts_sql_for_db(chars_db: &str, prefix: &str, squid_prefix: &str) -> Re
|
|||||||
let bots =
|
let bots =
|
||||||
format!("(UPPER(a.username) LIKE '{prefix}%' OR UPPER(a.username) LIKE '{squid_prefix}%')");
|
format!("(UPPER(a.username) LIKE '{prefix}%' OR UPPER(a.username) LIKE '{squid_prefix}%')");
|
||||||
Ok(format!(
|
Ok(format!(
|
||||||
"SELECT (SELECT COUNT(*) FROM {chars_db}.characters WHERE online=1), \
|
"SELECT (SELECT COUNT(*) FROM acore_characters.characters WHERE online=1), \
|
||||||
(SELECT COUNT(*) FROM {chars_db}.characters c JOIN acore_auth.account a ON a.id=c.account WHERE c.online=1 AND {bots}), \
|
(SELECT COUNT(*) FROM acore_characters.characters c JOIN acore_auth.account a ON a.id=c.account WHERE c.online=1 AND {bots}), \
|
||||||
(SELECT COUNT(*) FROM {chars_db}.characters c JOIN acore_auth.account a ON a.id=c.account WHERE {bots});"
|
(SELECT COUNT(*) FROM acore_characters.characters c JOIN acore_auth.account a ON a.id=c.account WHERE {bots});"
|
||||||
))
|
))
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -87,21 +85,6 @@ pub fn query_with(db: &Db, prefix: &str, squid_prefix: &str) -> Result<Populatio
|
|||||||
parse_counts(&db.query(&counts_sql(prefix, squid_prefix)?)?)
|
parse_counts(&db.query(&counts_sql(prefix, squid_prefix)?)?)
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn query_for_schema(db: &Db, chars_db: &str, prefix: &str, squid_prefix: &str) -> Result<Population> {
|
|
||||||
parse_counts(&db.query(&counts_sql_for_db(chars_db, prefix, squid_prefix)?)?)
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn query_for_realm(root: &Path, mode: crate::realms::Mode) -> Result<Population> {
|
|
||||||
let db = Db::from_repack(root, Account::App)?;
|
|
||||||
let schema = mode.schema("characters")?;
|
|
||||||
query_for_schema(
|
|
||||||
&db,
|
|
||||||
schema,
|
|
||||||
&bot_account_prefix(root),
|
|
||||||
&crate::accounts::squid_bot_prefix(root),
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Debug, Clone, Serialize)]
|
#[derive(Debug, Clone, Serialize)]
|
||||||
pub struct Hardware {
|
pub struct Hardware {
|
||||||
pub cores: u32,
|
pub cores: u32,
|
||||||
|
|||||||
+22
-670
File diff suppressed because it is too large.
Load diff
+53
-236
@@ -185,20 +185,8 @@ pub fn view(root: &Path) -> Result<View> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
pub fn guard_module(root: &Path, id: &str) -> Result<()> {
|
pub fn guard_module(root: &Path, id: &str) -> Result<()> {
|
||||||
let s = state(root)?;
|
if state(root)?.active != Mode::Coa && matches!(id, "companions" | "playerbots") {
|
||||||
if matches!(id, "companions" | "playerbots") {
|
return Err(Error::Invalid("Bot class mechanics have not been validated for this realm. This module is unavailable on this realm.".into()));
|
||||||
if let Ok(v) = view(root) {
|
|
||||||
if s.active == Mode::Wildcard && !v.supported {
|
|
||||||
return Err(Error::Invalid(
|
|
||||||
"The installed server binary does not support Wildcard mode.".into(),
|
|
||||||
));
|
|
||||||
}
|
|
||||||
if s.active == Mode::Reborn && !v.reborn_supported {
|
|
||||||
return Err(Error::Invalid(
|
|
||||||
"The installed server binary does not support Warcraft Reborn mode.".into(),
|
|
||||||
));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
@@ -308,14 +296,20 @@ fn wildcard_configs(mut files: Files) -> Result<Files> {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
// Preserve existing CoaBots.Enable if present; do not force enable or alter alternative bot systems
|
for (key, value) in [("CoaBots.Enable", "0"), ("CoaBots.AutoLoginOnStartup", "0")] {
|
||||||
if let Some(bytes) = files.get("Core/configs/modules/mod_coa_playerbots.conf") {
|
set(
|
||||||
if let Ok(conf) = ConfFile::parse_bytes(bytes) {
|
&mut files,
|
||||||
if conf.get("CoaBots.Enable") == Some("1") {
|
"Core/configs/modules/mod_coa_playerbots.conf",
|
||||||
set(&mut files, "Core/configs/modules/mod_coa_playerbots.conf", "CoaBots.Enable", "1")?;
|
key,
|
||||||
}
|
value,
|
||||||
}
|
)?;
|
||||||
}
|
}
|
||||||
|
set(
|
||||||
|
&mut files,
|
||||||
|
"Core/configs/modules/playerbots.conf",
|
||||||
|
"AiPlayerbot.Enabled",
|
||||||
|
"0",
|
||||||
|
)?;
|
||||||
Ok(files)
|
Ok(files)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -343,14 +337,20 @@ fn reborn_configs(mut files: Files) -> Result<Files> {
|
|||||||
set(&mut files, path, "RealmID", "3")?;
|
set(&mut files, path, "RealmID", "3")?;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
// Preserve existing CoaBots.Enable if present; do not force enable or alter alternative bot systems
|
for (key, value) in [("CoaBots.Enable", "0"), ("CoaBots.AutoLoginOnStartup", "0")] {
|
||||||
if let Some(bytes) = files.get("Core/configs/modules/mod_coa_playerbots.conf") {
|
set(
|
||||||
if let Ok(conf) = ConfFile::parse_bytes(bytes) {
|
&mut files,
|
||||||
if conf.get("CoaBots.Enable") == Some("1") {
|
"Core/configs/modules/mod_coa_playerbots.conf",
|
||||||
set(&mut files, "Core/configs/modules/mod_coa_playerbots.conf", "CoaBots.Enable", "1")?;
|
key,
|
||||||
}
|
value,
|
||||||
}
|
)?;
|
||||||
}
|
}
|
||||||
|
set(
|
||||||
|
&mut files,
|
||||||
|
"Core/configs/modules/playerbots.conf",
|
||||||
|
"AiPlayerbot.Enabled",
|
||||||
|
"0",
|
||||||
|
)?;
|
||||||
Ok(files)
|
Ok(files)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -534,8 +534,6 @@ pub fn ensure_created(root: &Path, mode: Mode) -> Result<()> {
|
|||||||
"Update the server to a build with Warcraft Reborn support first.".into(),
|
"Update the server to a build with Warcraft Reborn support first.".into(),
|
||||||
));
|
));
|
||||||
}
|
}
|
||||||
// Verify launcher support before creating databases, as selecting a realm does.
|
|
||||||
prepare_launcher(root)?;
|
|
||||||
let before = configs(root)?;
|
let before = configs(root)?;
|
||||||
create_realm(root, &mut s, mode, &before)
|
create_realm(root, &mut s, mode, &before)
|
||||||
}
|
}
|
||||||
@@ -565,8 +563,6 @@ pub fn select(root: &Path, mode: Mode) -> Result<View> {
|
|||||||
"Disable the realms that start together before switching realms.".into(),
|
"Disable the realms that start together before switching realms.".into(),
|
||||||
));
|
));
|
||||||
}
|
}
|
||||||
// Verify launcher support before creating databases or changing the selected realm.
|
|
||||||
prepare_launcher(root)?;
|
|
||||||
let before = configs(root)?;
|
let before = configs(root)?;
|
||||||
fsx::atomic_write_json(&snapshot(root, s.active), &before)?;
|
fsx::atomic_write_json(&snapshot(root, s.active), &before)?;
|
||||||
create_realm(root, &mut s, mode, &before)?;
|
create_realm(root, &mut s, mode, &before)?;
|
||||||
@@ -608,125 +604,6 @@ pub fn select(root: &Path, mode: Mode) -> Result<View> {
|
|||||||
view(root)
|
view(root)
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Adapt the bundled launcher's canonical schema and realm choices without changing its supervision logic.
|
|
||||||
pub fn prepare_launcher(root: &Path) -> Result<()> {
|
|
||||||
// A Docker server has no launcher to adapt: the Docker backend reads the active realm itself.
|
|
||||||
if crate::docker::is_docker(root) {
|
|
||||||
return Ok(());
|
|
||||||
}
|
|
||||||
let path = root.join("Scripts/manage.py");
|
|
||||||
let source = fs::read_to_string(&path)?;
|
|
||||||
let patched = patch_launcher(&source)?;
|
|
||||||
if patched != source {
|
|
||||||
fsx::atomic_write(&path, patched.as_bytes())?;
|
|
||||||
// A Manager-owned transformation is still pristine for subsequent updates and file checks.
|
|
||||||
if let Ok(dir) = crate::registry::metadata_dir_for(root) {
|
|
||||||
if let Ok((_, mut meta)) = crate::registry::MetaDir::open(&dir) {
|
|
||||||
if meta
|
|
||||||
.original_hashes
|
|
||||||
.get("Scripts/manage.py")
|
|
||||||
.is_some_and(|hash| hash == &fsx::sha256_bytes(source.as_bytes()))
|
|
||||||
{
|
|
||||||
meta.original_hashes.insert(
|
|
||||||
"Scripts/manage.py".into(),
|
|
||||||
fsx::sha256_bytes(patched.as_bytes()),
|
|
||||||
);
|
|
||||||
fsx::atomic_write_json(&dir.join("install.json"), &meta)?;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
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";
|
|
||||||
|
|
||||||
fn launcher_insert() -> String {
|
|
||||||
LAUNCHER_REALM_INSERT
|
|
||||||
.replace("profiles-v1", "profiles-v2")
|
|
||||||
.replace(
|
|
||||||
"return 2 if",
|
|
||||||
"return 3 if coa_realm() == 'reborn' else 2 if",
|
|
||||||
)
|
|
||||||
.replace(
|
|
||||||
"return 'Wildcard' if",
|
|
||||||
"return 'Warcraft Reborn' if coa_realm() == 'reborn' else 'Wildcard' if",
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
fn launcher_replacements() -> Vec<(&'static str, String)> {
|
|
||||||
LAUNCHER_REALM_REPLACEMENTS.iter().map(|(from, to)| (*from, to
|
|
||||||
.replace("\"acore_world_wildcard\" if", "\"acore_world_reborn\" if coa_realm() == 'reborn' else \"acore_world_wildcard\" if")
|
|
||||||
.replace("\"acore_characters_wildcard\" if", "\"acore_characters_reborn\" if coa_realm() == 'reborn' else \"acore_characters_wildcard\" if"))).collect()
|
|
||||||
}
|
|
||||||
|
|
||||||
pub(crate) fn patch_launcher(source: &str) -> Result<String> {
|
|
||||||
if source.contains("# coa-manager-realm-profiles-v2") {
|
|
||||||
return Ok(source.into());
|
|
||||||
}
|
|
||||||
if source.contains("# coa-manager-realm-profiles-v1") {
|
|
||||||
let original = unpatch_launcher(source)
|
|
||||||
.ok_or_else(|| Error::Invalid("Unrecognised realm launcher patch.".into()))?;
|
|
||||||
return patch_launcher(&original);
|
|
||||||
}
|
|
||||||
let mut out = source.to_string();
|
|
||||||
for (from, to) in launcher_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);
|
|
||||||
}
|
|
||||||
// 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!("{}{marker}", launcher_insert())))
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Reverse only our exact realm transformation; callers must verify the recovered original hash.
|
|
||||||
pub(crate) fn unpatch_launcher(source: &str) -> Option<String> {
|
|
||||||
let (insert, replacements) = if source.contains(&launcher_insert()) {
|
|
||||||
(launcher_insert(), launcher_replacements())
|
|
||||||
} else if source.contains(LAUNCHER_REALM_INSERT) {
|
|
||||||
(
|
|
||||||
LAUNCHER_REALM_INSERT.into(),
|
|
||||||
LAUNCHER_REALM_REPLACEMENTS
|
|
||||||
.iter()
|
|
||||||
.map(|(a, b)| (*a, b.to_string()))
|
|
||||||
.collect(),
|
|
||||||
)
|
|
||||||
} else {
|
|
||||||
return None;
|
|
||||||
};
|
|
||||||
let mut original = source.replacen(&insert, "", 1);
|
|
||||||
for (from, to) in &replacements {
|
|
||||||
original = original.replace(to, from);
|
|
||||||
}
|
|
||||||
let mut check = original.clone();
|
|
||||||
for (from, to) in &replacements {
|
|
||||||
check = check.replace(from, to);
|
|
||||||
}
|
|
||||||
check = check.replace(
|
|
||||||
"if __name__ == \"__main__\":",
|
|
||||||
&format!("{insert}if __name__ == \"__main__\":"),
|
|
||||||
);
|
|
||||||
(check == source).then_some(original)
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The character-creation model the world server advertises for a realm. Every realm has its own database and its own
|
/// The character-creation model the world server advertises for a realm. Every realm has its own database and its own
|
||||||
/// entry on Overview, so it advertises exactly one model: a list such as `"coa wcr"` would let players create
|
/// entry on Overview, so it advertises exactly one model: a list such as `"coa wcr"` would let players create
|
||||||
/// Warcraft Reborn characters in the Conquest of Azeroth realm.
|
/// Warcraft Reborn characters in the Conquest of Azeroth realm.
|
||||||
@@ -770,7 +647,6 @@ pub fn before_start(root: &Path) -> Result<()> {
|
|||||||
if !root.join(STATE).exists() {
|
if !root.join(STATE).exists() {
|
||||||
return Ok(());
|
return Ok(());
|
||||||
}
|
}
|
||||||
prepare_launcher(root)?;
|
|
||||||
if s.simultaneous && !view(root)?.supported {
|
if s.simultaneous && !view(root)?.supported {
|
||||||
return Err(Error::Invalid(
|
return Err(Error::Invalid(
|
||||||
"The installed server build does not support simultaneous Wildcard startup.".into(),
|
"The installed server build does not support simultaneous Wildcard startup.".into(),
|
||||||
@@ -805,7 +681,19 @@ pub fn before_start(root: &Path) -> Result<()> {
|
|||||||
"The installed server build does not support Wildcard.".into(),
|
"The installed server build does not support Wildcard.".into(),
|
||||||
));
|
));
|
||||||
}
|
}
|
||||||
// Multi-realm Playerbots 1.0: bots are supported and enabled on all realms
|
let path = root.join("Core/configs/modules/mod_coa_playerbots.conf");
|
||||||
|
let mut conf = ConfFile::parse_bytes(&fs::read(&path)?)?;
|
||||||
|
conf.set("CoaBots.Enable", "0", &[]);
|
||||||
|
fsx::atomic_write(&path, conf.to_text().as_bytes())?;
|
||||||
|
let path = root.join("Core/configs/modules/playerbots.conf");
|
||||||
|
let bytes = if path.exists() {
|
||||||
|
fs::read(&path)?
|
||||||
|
} else {
|
||||||
|
b"[worldserver]\n".to_vec()
|
||||||
|
};
|
||||||
|
let mut conf = ConfFile::parse_bytes(&bytes)?;
|
||||||
|
conf.set("AiPlayerbot.Enabled", "0", &[]);
|
||||||
|
fsx::atomic_write(&path, conf.to_text().as_bytes())?;
|
||||||
}
|
}
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
@@ -925,12 +813,11 @@ mod tests {
|
|||||||
.get("RealmID"),
|
.get("RealmID"),
|
||||||
Some("3")
|
Some("3")
|
||||||
);
|
);
|
||||||
// Requirement 6: Never alter alternative bot system settings (AiPlayerbot.Enabled) without explicit user choice
|
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
ConfFile::parse_bytes(&reborn["Core/configs/modules/playerbots.conf"])
|
ConfFile::parse_bytes(&reborn["Core/configs/modules/playerbots.conf"])
|
||||||
.unwrap()
|
.unwrap()
|
||||||
.get("AiPlayerbot.Enabled"),
|
.get("AiPlayerbot.Enabled"),
|
||||||
Some("1")
|
Some("0")
|
||||||
);
|
);
|
||||||
write_configs(t.path(), &reborn).unwrap();
|
write_configs(t.path(), &reborn).unwrap();
|
||||||
write_configs(t.path(), &coa).unwrap();
|
write_configs(t.path(), &coa).unwrap();
|
||||||
@@ -944,8 +831,8 @@ mod tests {
|
|||||||
},
|
},
|
||||||
)
|
)
|
||||||
.unwrap();
|
.unwrap();
|
||||||
assert!(guard_module(t.path(), "companions").is_ok());
|
assert!(guard_module(t.path(), "companions").is_err());
|
||||||
assert!(guard_module(t.path(), "playerbots").is_ok());
|
assert!(guard_module(t.path(), "playerbots").is_err());
|
||||||
assert!(guard_module(t.path(), "content-scaling").is_ok());
|
assert!(guard_module(t.path(), "content-scaling").is_ok());
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1096,26 +983,6 @@ CoA.GameModeMask = 0
|
|||||||
assert!(!v.supported);
|
assert!(!v.supported);
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn old_launcher_upgrades_and_both_patch_versions_are_reversible() {
|
|
||||||
let original = "(\"WorldDatabaseInfo\", \"acore_world\")\n(\"CharacterDatabaseInfo\", \"acore_characters\")\nSET name='AzerothCore',address=\nWHERE id=1;\nmysql(\"UPDATE acore_auth.realmlist SET flag=0\nif __name__ == \"__main__\":\n";
|
|
||||||
let mut old = original.to_string();
|
|
||||||
for (from, to) in LAUNCHER_REALM_REPLACEMENTS {
|
|
||||||
old = old.replace(from, to);
|
|
||||||
}
|
|
||||||
old = old.replace(
|
|
||||||
"if __name__ == \"__main__\":",
|
|
||||||
&format!("{LAUNCHER_REALM_INSERT}if __name__ == \"__main__\":"),
|
|
||||||
);
|
|
||||||
assert_eq!(unpatch_launcher(&old).as_deref(), Some(original));
|
|
||||||
let new = patch_launcher(&old).unwrap();
|
|
||||||
assert!(new.contains("acore_world_reborn"));
|
|
||||||
assert!(new.contains("return 3 if coa_realm() == 'reborn'"));
|
|
||||||
assert!(new.contains("return 'Warcraft Reborn' if"));
|
|
||||||
assert_eq!(patch_launcher(&new).unwrap(), new);
|
|
||||||
assert_eq!(unpatch_launcher(&new).as_deref(), Some(original));
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn a_docker_server_is_checked_for_wildcard_support_in_its_own_binary() {
|
fn a_docker_server_is_checked_for_wildcard_support_in_its_own_binary() {
|
||||||
let d = tempfile::tempdir().unwrap();
|
let d = tempfile::tempdir().unwrap();
|
||||||
@@ -1146,20 +1013,6 @@ CoA.GameModeMask = 0
|
|||||||
assert!(view(d.path()).unwrap().supported);
|
assert!(view(d.path()).unwrap().supported);
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn a_docker_server_has_no_launcher_to_adapt() {
|
|
||||||
let d = tempfile::tempdir().unwrap();
|
|
||||||
fs::create_dir_all(d.path().join("Settings")).unwrap();
|
|
||||||
// No Scripts/manage.py anywhere: on a repack this fails, on a Docker server there is nothing to do.
|
|
||||||
assert!(prepare_launcher(d.path()).is_err());
|
|
||||||
fs::write(
|
|
||||||
d.path().join("Settings/docker.json"),
|
|
||||||
br#"{"project":"t1"}"#,
|
|
||||||
)
|
|
||||||
.unwrap();
|
|
||||||
prepare_launcher(d.path()).unwrap();
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn fresh_wildcard_disables_bots_and_preserves_scaling() {
|
fn fresh_wildcard_disables_bots_and_preserves_scaling() {
|
||||||
let mut f = Files::new();
|
let mut f = Files::new();
|
||||||
@@ -1167,10 +1020,6 @@ CoA.GameModeMask = 0
|
|||||||
"Core/configs/modules/mod-coa-content-scaling.conf".into(),
|
"Core/configs/modules/mod-coa-content-scaling.conf".into(),
|
||||||
b"[worldserver]\nCoAContentScaling.Enable = 1\n".to_vec(),
|
b"[worldserver]\nCoAContentScaling.Enable = 1\n".to_vec(),
|
||||||
);
|
);
|
||||||
f.insert(
|
|
||||||
"Core/configs/modules/mod_coa_playerbots.conf".into(),
|
|
||||||
b"[worldserver]\nCoaBots.Enable = 1\n".to_vec(),
|
|
||||||
);
|
|
||||||
f.insert(
|
f.insert(
|
||||||
"Settings/worldserver.conf.template".into(),
|
"Settings/worldserver.conf.template".into(),
|
||||||
b"[worldserver]\nRealmID = 1\n".to_vec(),
|
b"[worldserver]\nRealmID = 1\n".to_vec(),
|
||||||
@@ -1181,7 +1030,7 @@ CoA.GameModeMask = 0
|
|||||||
f["Core/configs/modules/mod-coa-content-scaling.conf"]
|
f["Core/configs/modules/mod-coa-content-scaling.conf"]
|
||||||
);
|
);
|
||||||
let c = ConfFile::parse_bytes(&w["Core/configs/modules/mod_coa_playerbots.conf"]).unwrap();
|
let c = ConfFile::parse_bytes(&w["Core/configs/modules/mod_coa_playerbots.conf"]).unwrap();
|
||||||
assert_eq!(c.get("CoaBots.Enable"), Some("1"));
|
assert_eq!(c.get("CoaBots.Enable"), Some("0"));
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
ConfFile::parse_bytes(&w["Settings/worldserver.conf.template"])
|
ConfFile::parse_bytes(&w["Settings/worldserver.conf.template"])
|
||||||
.unwrap()
|
.unwrap()
|
||||||
@@ -1253,46 +1102,14 @@ CoA.GameModeMask = 0
|
|||||||
},
|
},
|
||||||
)
|
)
|
||||||
.unwrap();
|
.unwrap();
|
||||||
assert!(guard_module(t.path(), "companions").is_ok());
|
assert!(crate::modules::set_enabled(t.path(), t.path(), "companions", true).is_err());
|
||||||
assert!(guard_module(t.path(), "playerbots").is_ok());
|
assert!(crate::config::save(
|
||||||
|
t.path(),
|
||||||
|
t.path(),
|
||||||
|
crate::config::Scope::Bots,
|
||||||
|
&BTreeMap::new()
|
||||||
|
)
|
||||||
|
.is_err());
|
||||||
assert!(guard_module(t.path(), "content-scaling").is_ok());
|
assert!(guard_module(t.path(), "content-scaling").is_ok());
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn unknown_launcher_is_refused_without_partial_patching() {
|
|
||||||
assert!(patch_launcher("print('custom launcher')").is_err());
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn managed_launcher_patch_remains_pristine_but_external_edits_conflict() {
|
|
||||||
let d = tempfile::tempdir().unwrap();
|
|
||||||
let root = d.path().join("server");
|
|
||||||
let source = "(\"WorldDatabaseInfo\", \"acore_world\")\n(\"CharacterDatabaseInfo\", \"acore_characters\")\nSET name='AzerothCore',address=\nWHERE id=1;\nmysql(\"UPDATE acore_auth.realmlist SET flag=0\nif __name__ == \"__main__\":\n";
|
|
||||||
fsx::atomic_write(&root.join("Scripts/manage.py"), source.as_bytes()).unwrap();
|
|
||||||
let mut meta = crate::registry::InstallMeta::new(crate::registry::InstallKind::New, &root);
|
|
||||||
meta.original_hashes.insert(
|
|
||||||
"Scripts/manage.py".into(),
|
|
||||||
fsx::sha256_bytes(source.as_bytes()),
|
|
||||||
);
|
|
||||||
let dir = crate::registry::MetaDir::create(&root, &meta).unwrap();
|
|
||||||
prepare_launcher(&root).unwrap();
|
|
||||||
let (_, meta) = crate::registry::MetaDir::open(&dir.root).unwrap();
|
|
||||||
assert!(crate::diag::verify_managed(&root, &meta).is_empty());
|
|
||||||
let manifest: crate::manifest::Manifest = serde_json::from_value(serde_json::json!({
|
|
||||||
"schema": 1, "kind": "update", "version": "2.0.0", "core": {"commit": null}, "builtAt": "fixture", "minManagerVersion": "0.1.0",
|
|
||||||
"files": [{"path":"Scripts/manage.py","sha256":fsx::sha256_bytes(b"next release"),"size":12,"owner":"core","policy":"replace"}]
|
|
||||||
})).unwrap();
|
|
||||||
assert_eq!(
|
|
||||||
crate::update::plan(&root, &meta, &manifest, &BTreeMap::new(), None).unwrap()[0].action,
|
|
||||||
crate::update::Action::Replace
|
|
||||||
);
|
|
||||||
let mut modified = fs::read(root.join("Scripts/manage.py")).unwrap();
|
|
||||||
modified.extend_from_slice(b"# custom edit\n");
|
|
||||||
fsx::atomic_write(&root.join("Scripts/manage.py"), &modified).unwrap();
|
|
||||||
prepare_launcher(&root).unwrap();
|
|
||||||
assert_eq!(
|
|
||||||
crate::update::plan(&root, &meta, &manifest, &BTreeMap::new(), None).unwrap()[0].action,
|
|
||||||
crate::update::Action::Conflict
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
@@ -259,9 +259,32 @@ fn split_repo(repo: &str) -> std::result::Result<(&str, &str), String> {
|
|||||||
.ok_or_else(|| format!("invalid repository '{repo}'"))
|
.ok_or_else(|| format!("invalid repository '{repo}'"))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Mark a server that starts with the bare core: the modules the core recommends are not installed on it
|
||||||
|
/// (the owner adds modules from the Modules page). Taken into account the first time a plugin-host core
|
||||||
|
/// arrives; after that every recommended module counts as dealt with.
|
||||||
|
pub fn decline_recommended(realm_root: &Path) -> Result<()> {
|
||||||
|
let body = serde_json::json!({ "schema": 1, "handled": load_handled(realm_root), "declineAll": true });
|
||||||
|
fs::create_dir_all(plugins::meta_dir(realm_root))?;
|
||||||
|
crate::fsx::atomic_write(&handled_path(realm_root), serde_json::to_string_pretty(&body)?.as_bytes())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn declined_all(realm_root: &Path) -> bool {
|
||||||
|
fs::read(handled_path(realm_root)).ok()
|
||||||
|
.and_then(|b| serde_json::from_slice::<serde_json::Value>(&b).ok())
|
||||||
|
.and_then(|v| v.get("declineAll")?.as_bool())
|
||||||
|
.unwrap_or(false)
|
||||||
|
}
|
||||||
|
|
||||||
fn install_recommended(realm_root: &Path, progress: &dyn Fn(&str, &str)) -> Vec<ModuleRebuild> {
|
fn install_recommended(realm_root: &Path, progress: &dyn Fn(&str, &str)) -> Vec<ModuleRebuild> {
|
||||||
let Some(rec) = recommended(realm_root) else { return Vec::new() };
|
let Some(rec) = recommended(realm_root) else { return Vec::new() };
|
||||||
let mut handled = load_handled(realm_root);
|
let mut handled = load_handled(realm_root);
|
||||||
|
if declined_all(realm_root) {
|
||||||
|
for m in &rec.modules {
|
||||||
|
handled.entry(m.id.clone()).or_insert_with(|| "not installed: new server with the bare core".into());
|
||||||
|
}
|
||||||
|
save_handled(realm_root, &handled); // drops the mark: it applies to this first core only
|
||||||
|
return Vec::new();
|
||||||
|
}
|
||||||
let mut out = Vec::new();
|
let mut out = Vec::new();
|
||||||
for m in &rec.modules {
|
for m in &rec.modules {
|
||||||
let registry = plugins::load_registry(realm_root).unwrap_or_default();
|
let registry = plugins::load_registry(realm_root).unwrap_or_default();
|
||||||
@@ -455,6 +478,25 @@ mod tests {
|
|||||||
assert!(!handled.contains_key("companions"));
|
assert!(!handled.contains_key("companions"));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_new_server_with_the_bare_core_installs_no_recommended_module() {
|
||||||
|
let dir = tempfile::tempdir().unwrap();
|
||||||
|
let server = dir.path();
|
||||||
|
fs::create_dir_all(server.join("Core/configs/modules")).unwrap();
|
||||||
|
fs::create_dir_all(server.join("Core/plugins")).unwrap();
|
||||||
|
fs::write(server.join("Core/worldserver.exe"), image("worldserver", &"c".repeat(64))).unwrap();
|
||||||
|
decline_recommended(server).unwrap();
|
||||||
|
// the mark is written before the plugin-host core (and its recommended.json) arrives
|
||||||
|
fs::write(server.join("Core/plugins/recommended.json"), r#"{"schema":1,"modules":[
|
||||||
|
{"id":"companions","repo":"not-a-repo","commit":"0000000000000000000000000000000000000000"}]}"#).unwrap();
|
||||||
|
let out = rebuild_for_current_core(server, &|_, _| panic!("nothing is built")).unwrap();
|
||||||
|
assert!(out.is_empty(), "{out:?}");
|
||||||
|
assert!(load_handled(server)["companions"].contains("bare core"));
|
||||||
|
assert!(!declined_all(server), "the mark applies to the first plugin-host core only");
|
||||||
|
// a later core change does not bring it back either
|
||||||
|
assert!(rebuild_for_current_core(server, &|_, _| panic!("nothing is built")).unwrap().is_empty());
|
||||||
|
}
|
||||||
|
|
||||||
/// Real run: COA_TEST_RECOMMENDED_REALM is a plugin-host realm with Core/plugins/recommended.json (or
|
/// Real run: COA_TEST_RECOMMENDED_REALM is a plugin-host realm with Core/plugins/recommended.json (or
|
||||||
/// plugins/recommended.json); the modules are downloaded from GitHub, built and switched on.
|
/// plugins/recommended.json); the modules are downloaded from GitHub, built and switched on.
|
||||||
#[test]
|
#[test]
|
||||||
|
|||||||
@@ -1,595 +0,0 @@
|
|||||||
//! Server Migration Center (Перенос сервера).
|
|
||||||
//!
|
|
||||||
//! Subsystem for discovering, inspecting, comparing, planning, and executing non-destructive
|
|
||||||
//! server migrations from legacy or external AzerothCore/CoA servers into CSM Modules Preview realms.
|
|
||||||
//!
|
|
||||||
//! Migration Lifecycle:
|
|
||||||
//! Discover -> Inspect -> Classify -> Compare -> Plan -> Backup -> Transfer -> Validate -> Commit.
|
|
||||||
|
|
||||||
use std::collections::{BTreeMap, BTreeSet};
|
|
||||||
use std::fs;
|
|
||||||
use std::path::{Path, PathBuf};
|
|
||||||
use std::time::Instant;
|
|
||||||
|
|
||||||
use serde::{Deserialize, Serialize};
|
|
||||||
|
|
||||||
use crate::error::{Error, Result};
|
|
||||||
use crate::fsx;
|
|
||||||
|
|
||||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
|
|
||||||
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
|
|
||||||
pub enum SourceClassification {
|
|
||||||
CsmManagedCoa,
|
|
||||||
LegacyEmbeddedCoa,
|
|
||||||
StandardAzerothCore,
|
|
||||||
UnknownCustom,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
|
||||||
pub struct DetectedModule {
|
|
||||||
pub id: String,
|
|
||||||
pub name: String,
|
|
||||||
pub detected_via: String,
|
|
||||||
pub version: Option<String>,
|
|
||||||
pub has_database_data: bool,
|
|
||||||
pub is_supported_by_preview: bool,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
|
||||||
pub struct SourceInspectionReport {
|
|
||||||
pub source_path: PathBuf,
|
|
||||||
pub source_type: SourceClassification,
|
|
||||||
pub core_version: Option<String>,
|
|
||||||
pub schema_version: Option<String>,
|
|
||||||
pub accounts_count: usize,
|
|
||||||
pub characters_count: usize,
|
|
||||||
pub detected_modules: Vec<DetectedModule>,
|
|
||||||
pub module_tables: BTreeMap<String, Vec<String>>,
|
|
||||||
pub custom_race_support: bool,
|
|
||||||
pub compatibility_notes: Vec<String>,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
|
||||||
pub struct MigrationScope {
|
|
||||||
pub accounts_and_characters: bool,
|
|
||||||
pub module_owned_data: bool,
|
|
||||||
pub server_configuration: bool,
|
|
||||||
pub selected_modules: Vec<String>,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl Default for MigrationScope {
|
|
||||||
fn default() -> Self {
|
|
||||||
Self {
|
|
||||||
accounts_and_characters: true,
|
|
||||||
module_owned_data: true,
|
|
||||||
server_configuration: true,
|
|
||||||
selected_modules: Vec::new(),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
|
|
||||||
#[serde(rename_all = "snake_case")]
|
|
||||||
pub enum ConflictResolutionPolicy {
|
|
||||||
RemapCollidingGuids,
|
|
||||||
SkipCollidingGuids,
|
|
||||||
OverwriteExisting,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl Default for ConflictResolutionPolicy {
|
|
||||||
fn default() -> Self {
|
|
||||||
ConflictResolutionPolicy::RemapCollidingGuids
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
|
||||||
pub struct AdapterPlan {
|
|
||||||
pub module_id: String,
|
|
||||||
pub source_tables: Vec<String>,
|
|
||||||
pub dest_tables: Vec<String>,
|
|
||||||
pub data_loss_risks: Vec<String>,
|
|
||||||
pub requires_conversion: bool,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
|
||||||
pub struct MigrationPlan {
|
|
||||||
pub plan_id: String,
|
|
||||||
pub source_path: PathBuf,
|
|
||||||
pub dest_realm_path: PathBuf,
|
|
||||||
pub source_report: SourceInspectionReport,
|
|
||||||
pub scope: MigrationScope,
|
|
||||||
pub conflict_policy: ConflictResolutionPolicy,
|
|
||||||
pub adapters: Vec<AdapterPlan>,
|
|
||||||
pub tables_to_migrate: Vec<String>,
|
|
||||||
pub quarantined_tables: Vec<String>,
|
|
||||||
pub estimated_disk_mb: u64,
|
|
||||||
pub warnings: Vec<String>,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
|
||||||
pub struct MigrationExecutionReport {
|
|
||||||
pub success: bool,
|
|
||||||
pub backup_path: Option<PathBuf>,
|
|
||||||
pub accounts_transferred: usize,
|
|
||||||
pub characters_transferred: usize,
|
|
||||||
pub items_transferred: usize,
|
|
||||||
pub modules_migrated: Vec<String>,
|
|
||||||
pub tables_migrated: Vec<String>,
|
|
||||||
pub quarantined_tables: Vec<String>,
|
|
||||||
pub warnings: Vec<String>,
|
|
||||||
pub errors: Vec<String>,
|
|
||||||
pub duration_ms: u64,
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Trait implemented by versioned module migration adapters.
|
|
||||||
pub trait ModuleMigrationAdapter: Send + Sync {
|
|
||||||
fn module_id(&self) -> &str;
|
|
||||||
fn source_module_id(&self) -> &str;
|
|
||||||
fn destination_module_id(&self) -> &str;
|
|
||||||
fn owned_tables(&self) -> &[&str];
|
|
||||||
fn plan(&self, source_tables: &[String]) -> AdapterPlan;
|
|
||||||
fn execute(&self, source: &Path, dest: &Path, remap_map: &BTreeMap<u64, u64>) -> Result<Vec<String>>;
|
|
||||||
}
|
|
||||||
|
|
||||||
// ---------------- Built-in Module Adapters ----------------
|
|
||||||
|
|
||||||
pub struct CompanionsAdapter;
|
|
||||||
impl ModuleMigrationAdapter for CompanionsAdapter {
|
|
||||||
fn module_id(&self) -> &str { "companions" }
|
|
||||||
fn source_module_id(&self) -> &str { "mod-coa-playerbots" }
|
|
||||||
fn destination_module_id(&self) -> &str { "companions" }
|
|
||||||
fn owned_tables(&self) -> &[&str] {
|
|
||||||
&["mod_coa_playerbots_saved_bots", "mod_coa_playerbots_talents", "mod_coa_playerbots_equipment"]
|
|
||||||
}
|
|
||||||
fn plan(&self, source_tables: &[String]) -> AdapterPlan {
|
|
||||||
let matching: Vec<String> = source_tables.iter()
|
|
||||||
.filter(|t| self.owned_tables().iter().any(|ot| ot == t))
|
|
||||||
.cloned()
|
|
||||||
.collect();
|
|
||||||
AdapterPlan {
|
|
||||||
module_id: "companions".into(),
|
|
||||||
source_tables: matching.clone(),
|
|
||||||
dest_tables: matching,
|
|
||||||
data_loss_risks: vec!["Bot owner character GUIDs will be remapped to target realm GUIDs".into()],
|
|
||||||
requires_conversion: true,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
fn execute(&self, _source: &Path, _dest: &Path, _remap_map: &BTreeMap<u64, u64>) -> Result<Vec<String>> {
|
|
||||||
Ok(vec!["mod_coa_playerbots_saved_bots".into()])
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
pub struct SquidPlayerbotsAdapter;
|
|
||||||
impl ModuleMigrationAdapter for SquidPlayerbotsAdapter {
|
|
||||||
fn module_id(&self) -> &str { "playerbots" }
|
|
||||||
fn source_module_id(&self) -> &str { "mod-playerbots" }
|
|
||||||
fn destination_module_id(&self) -> &str { "squid_playerbots" }
|
|
||||||
fn owned_tables(&self) -> &[&str] {
|
|
||||||
&["playerbots_rnd_bots", "playerbots_rnd_spells", "playerbots_custom_strategy"]
|
|
||||||
}
|
|
||||||
fn plan(&self, source_tables: &[String]) -> AdapterPlan {
|
|
||||||
let matching: Vec<String> = source_tables.iter()
|
|
||||||
.filter(|t| self.owned_tables().iter().any(|ot| ot == t))
|
|
||||||
.cloned()
|
|
||||||
.collect();
|
|
||||||
AdapterPlan {
|
|
||||||
module_id: "playerbots".into(),
|
|
||||||
source_tables: matching.clone(),
|
|
||||||
dest_tables: matching,
|
|
||||||
data_loss_risks: vec![],
|
|
||||||
requires_conversion: false,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
fn execute(&self, _source: &Path, _dest: &Path, _remap_map: &BTreeMap<u64, u64>) -> Result<Vec<String>> {
|
|
||||||
Ok(vec!["playerbots_rnd_bots".into()])
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
pub struct ContentScalingAdapter;
|
|
||||||
impl ModuleMigrationAdapter for ContentScalingAdapter {
|
|
||||||
fn module_id(&self) -> &str { "content-scaling" }
|
|
||||||
fn source_module_id(&self) -> &str { "mod-coa-content-scaling" }
|
|
||||||
fn destination_module_id(&self) -> &str { "content_scaling" }
|
|
||||||
fn owned_tables(&self) -> &[&str] {
|
|
||||||
&["mod_content_scaling_creatures", "mod_content_scaling_maps"]
|
|
||||||
}
|
|
||||||
fn plan(&self, source_tables: &[String]) -> AdapterPlan {
|
|
||||||
let matching: Vec<String> = source_tables.iter()
|
|
||||||
.filter(|t| self.owned_tables().iter().any(|ot| ot == t))
|
|
||||||
.cloned()
|
|
||||||
.collect();
|
|
||||||
AdapterPlan {
|
|
||||||
module_id: "content-scaling".into(),
|
|
||||||
source_tables: matching.clone(),
|
|
||||||
dest_tables: matching,
|
|
||||||
data_loss_risks: vec![],
|
|
||||||
requires_conversion: false,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
fn execute(&self, _source: &Path, _dest: &Path, _remap_map: &BTreeMap<u64, u64>) -> Result<Vec<String>> {
|
|
||||||
Ok(vec!["mod_content_scaling_creatures".into()])
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
pub struct AuctionHouseBotAdapter;
|
|
||||||
impl ModuleMigrationAdapter for AuctionHouseBotAdapter {
|
|
||||||
fn module_id(&self) -> &str { "ah-bot" }
|
|
||||||
fn source_module_id(&self) -> &str { "mod-auctionhousebot" }
|
|
||||||
fn destination_module_id(&self) -> &str { "ah-bot" }
|
|
||||||
fn owned_tables(&self) -> &[&str] {
|
|
||||||
&["mod_auctionhousebot_buyer", "mod_auctionhousebot_seller"]
|
|
||||||
}
|
|
||||||
fn plan(&self, source_tables: &[String]) -> AdapterPlan {
|
|
||||||
let matching: Vec<String> = source_tables.iter()
|
|
||||||
.filter(|t| self.owned_tables().iter().any(|ot| ot == t))
|
|
||||||
.cloned()
|
|
||||||
.collect();
|
|
||||||
AdapterPlan {
|
|
||||||
module_id: "ah-bot".into(),
|
|
||||||
source_tables: matching.clone(),
|
|
||||||
dest_tables: matching,
|
|
||||||
data_loss_risks: vec!["Active temporary auctions will be refreshed by bot".into()],
|
|
||||||
requires_conversion: false,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
fn execute(&self, _source: &Path, _dest: &Path, _remap_map: &BTreeMap<u64, u64>) -> Result<Vec<String>> {
|
|
||||||
Ok(vec!["mod_auctionhousebot_buyer".into()])
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
pub struct NpcEnchanterAdapter;
|
|
||||||
impl ModuleMigrationAdapter for NpcEnchanterAdapter {
|
|
||||||
fn module_id(&self) -> &str { "npc-enchanter" }
|
|
||||||
fn source_module_id(&self) -> &str { "mod-npc-enchanter" }
|
|
||||||
fn destination_module_id(&self) -> &str { "npc-enchanter" }
|
|
||||||
fn owned_tables(&self) -> &[&str] {
|
|
||||||
&["mod_npc_enchanter_item_cost"]
|
|
||||||
}
|
|
||||||
fn plan(&self, source_tables: &[String]) -> AdapterPlan {
|
|
||||||
let matching: Vec<String> = source_tables.iter()
|
|
||||||
.filter(|t| self.owned_tables().iter().any(|ot| ot == t))
|
|
||||||
.cloned()
|
|
||||||
.collect();
|
|
||||||
AdapterPlan {
|
|
||||||
module_id: "npc-enchanter".into(),
|
|
||||||
source_tables: matching.clone(),
|
|
||||||
dest_tables: matching,
|
|
||||||
data_loss_risks: vec![],
|
|
||||||
requires_conversion: false,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
fn execute(&self, _source: &Path, _dest: &Path, _remap_map: &BTreeMap<u64, u64>) -> Result<Vec<String>> {
|
|
||||||
Ok(vec!["mod_npc_enchanter_item_cost".into()])
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// ---------------- Core Migration Functions ----------------
|
|
||||||
|
|
||||||
/// Gets the registry of all built-in module migration adapters.
|
|
||||||
pub fn get_adapters() -> Vec<Box<dyn ModuleMigrationAdapter>> {
|
|
||||||
vec![
|
|
||||||
Box::new(CompanionsAdapter),
|
|
||||||
Box::new(SquidPlayerbotsAdapter),
|
|
||||||
Box::new(ContentScalingAdapter),
|
|
||||||
Box::new(AuctionHouseBotAdapter),
|
|
||||||
Box::new(NpcEnchanterAdapter),
|
|
||||||
]
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Discovers and inspects a source server non-destructively (read-only).
|
|
||||||
pub fn inspect_source(source_path: &Path) -> Result<SourceInspectionReport> {
|
|
||||||
if !source_path.is_dir() {
|
|
||||||
return Err(Error::Invalid(format!(
|
|
||||||
"Source path is not a directory: {}",
|
|
||||||
source_path.display()
|
|
||||||
)));
|
|
||||||
}
|
|
||||||
|
|
||||||
let mut notes = Vec::new();
|
|
||||||
|
|
||||||
// 1. Classify source
|
|
||||||
let has_csm_metadata = source_path.join(".manager").is_dir() || source_path.join("metadata").is_dir();
|
|
||||||
let has_worldserver = source_path.join("worldserver.exe").is_file() || source_path.join("bin/worldserver").is_file();
|
|
||||||
let has_coa_config = source_path.join("configs/modules/coa.conf").is_file()
|
|
||||||
|| source_path.join("configs/modules/coa.conf.dist").is_file()
|
|
||||||
|| source_path.join("etc/coa.conf").is_file();
|
|
||||||
|
|
||||||
let source_type = if has_csm_metadata && has_coa_config {
|
|
||||||
SourceClassification::CsmManagedCoa
|
|
||||||
} else if has_coa_config {
|
|
||||||
SourceClassification::LegacyEmbeddedCoa
|
|
||||||
} else if has_worldserver {
|
|
||||||
SourceClassification::StandardAzerothCore
|
|
||||||
} else {
|
|
||||||
SourceClassification::UnknownCustom
|
|
||||||
};
|
|
||||||
|
|
||||||
if source_type == SourceClassification::UnknownCustom {
|
|
||||||
notes.push("Source directory does not match standard CoA or AzerothCore server layout. Migration will be conservative.".into());
|
|
||||||
}
|
|
||||||
|
|
||||||
// 2. Discover installed modules and configurations
|
|
||||||
let mut detected_modules = Vec::new();
|
|
||||||
let mut module_tables = BTreeMap::new();
|
|
||||||
|
|
||||||
let conf_dirs = [
|
|
||||||
source_path.join("configs/modules"),
|
|
||||||
source_path.join("etc/modules"),
|
|
||||||
source_path.join("configs"),
|
|
||||||
];
|
|
||||||
|
|
||||||
let mut found_confs = BTreeSet::new();
|
|
||||||
for d in &conf_dirs {
|
|
||||||
if let Ok(entries) = fs::read_dir(d) {
|
|
||||||
for entry in entries.flatten() {
|
|
||||||
let name = entry.file_name().to_string_lossy().into_owned();
|
|
||||||
if name.ends_with(".conf") || name.ends_with(".conf.dist") {
|
|
||||||
found_confs.insert(name);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
let adapters = get_adapters();
|
|
||||||
for adapter in &adapters {
|
|
||||||
let mid = adapter.module_id();
|
|
||||||
let src_id = adapter.source_module_id();
|
|
||||||
let has_conf = found_confs.iter().any(|c| {
|
|
||||||
c.contains(&mid.replace('-', "_")) || c.contains(mid)
|
|
||||||
|| c.contains(&src_id.replace('-', "_")) || c.contains(src_id)
|
|
||||||
});
|
|
||||||
let tables: Vec<String> = adapter.owned_tables().iter().map(|s| s.to_string()).collect();
|
|
||||||
module_tables.insert(mid.to_string(), tables.clone());
|
|
||||||
|
|
||||||
if has_conf {
|
|
||||||
detected_modules.push(DetectedModule {
|
|
||||||
id: mid.to_string(),
|
|
||||||
name: match mid {
|
|
||||||
"companions" => "CoA Companions",
|
|
||||||
"playerbots" => "SQUID Playerbots",
|
|
||||||
"content-scaling" => "Content Scaling",
|
|
||||||
"ah-bot" => "Auction House Bot",
|
|
||||||
"npc-enchanter" => "NPC Enchanter",
|
|
||||||
_ => mid,
|
|
||||||
}.into(),
|
|
||||||
detected_via: "configuration".into(),
|
|
||||||
version: None,
|
|
||||||
has_database_data: true,
|
|
||||||
is_supported_by_preview: true,
|
|
||||||
});
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// 3. Inspect accounts and characters counts from SQLite / DB snapshot if available, or simulate from metadata
|
|
||||||
let mut accounts_count = 0;
|
|
||||||
let mut characters_count = 0;
|
|
||||||
|
|
||||||
let characters_json = source_path.join(".manager/characters.json");
|
|
||||||
if characters_json.is_file() {
|
|
||||||
if let Ok(val) = fsx::read_json::<serde_json::Value>(&characters_json) {
|
|
||||||
if let Some(arr) = val.as_array() {
|
|
||||||
characters_count = arr.len();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
// Fallback inspection: check sqlite or backup files
|
|
||||||
let dump_files = [
|
|
||||||
source_path.join("backups/characters.sql"),
|
|
||||||
source_path.join("data/sql/characters.sql"),
|
|
||||||
];
|
|
||||||
for f in &dump_files {
|
|
||||||
if f.is_file() {
|
|
||||||
characters_count = 1;
|
|
||||||
accounts_count = 1;
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
let custom_race_support = source_path.join("Data/patch-Z.mpq").is_file()
|
|
||||||
|| source_path.join("configs/modules/mod_custom_races.conf").is_file();
|
|
||||||
|
|
||||||
Ok(SourceInspectionReport {
|
|
||||||
source_path: source_path.to_path_buf(),
|
|
||||||
source_type,
|
|
||||||
core_version: Some("0.6.12-coa".into()),
|
|
||||||
schema_version: Some("2026_10_28_00".into()),
|
|
||||||
accounts_count,
|
|
||||||
characters_count,
|
|
||||||
detected_modules,
|
|
||||||
module_tables,
|
|
||||||
custom_race_support,
|
|
||||||
compatibility_notes: notes,
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Creates a migration plan from an inspection report and user-chosen scopes.
|
|
||||||
pub fn plan_migration(
|
|
||||||
report: &SourceInspectionReport,
|
|
||||||
dest_realm_path: &Path,
|
|
||||||
scope: MigrationScope,
|
|
||||||
conflict_policy: ConflictResolutionPolicy,
|
|
||||||
) -> Result<MigrationPlan> {
|
|
||||||
let mut adapter_plans = Vec::new();
|
|
||||||
let mut tables_to_migrate = Vec::new();
|
|
||||||
let quarantined_tables = Vec::new();
|
|
||||||
let mut warnings = Vec::new();
|
|
||||||
|
|
||||||
let adapters = get_adapters();
|
|
||||||
for adapter in &adapters {
|
|
||||||
if scope.selected_modules.is_empty() || scope.selected_modules.iter().any(|m| m == adapter.module_id()) {
|
|
||||||
let owned: Vec<String> = adapter.owned_tables().iter().map(|s| s.to_string()).collect();
|
|
||||||
let p = adapter.plan(&owned);
|
|
||||||
tables_to_migrate.extend(p.dest_tables.clone());
|
|
||||||
adapter_plans.push(p);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if scope.accounts_and_characters {
|
|
||||||
tables_to_migrate.push("account".into());
|
|
||||||
tables_to_migrate.push("characters".into());
|
|
||||||
tables_to_migrate.push("character_inventory".into());
|
|
||||||
tables_to_migrate.push("character_spell".into());
|
|
||||||
tables_to_migrate.push("character_talent".into());
|
|
||||||
tables_to_migrate.push("character_skills".into());
|
|
||||||
}
|
|
||||||
|
|
||||||
if conflict_policy == ConflictResolutionPolicy::RemapCollidingGuids {
|
|
||||||
warnings.push("Deterministic ID remapping will be applied to prevent GUID collisions in target realm.".into());
|
|
||||||
} else if conflict_policy == ConflictResolutionPolicy::OverwriteExisting {
|
|
||||||
warnings.push("CAUTION: Overwrite policy will replace conflicting characters in the target realm.".into());
|
|
||||||
}
|
|
||||||
|
|
||||||
let plan_id = format!("mig-{}", uuid::Uuid::new_v4().to_string().chars().take(8).collect::<String>());
|
|
||||||
|
|
||||||
Ok(MigrationPlan {
|
|
||||||
plan_id,
|
|
||||||
source_path: report.source_path.clone(),
|
|
||||||
dest_realm_path: dest_realm_path.to_path_buf(),
|
|
||||||
source_report: report.clone(),
|
|
||||||
scope,
|
|
||||||
conflict_policy,
|
|
||||||
adapters: adapter_plans,
|
|
||||||
tables_to_migrate,
|
|
||||||
quarantined_tables,
|
|
||||||
estimated_disk_mb: 50,
|
|
||||||
warnings,
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Executes a migration plan non-destructively:
|
|
||||||
/// Backup -> Transfer -> Remap -> Validate -> Commit.
|
|
||||||
pub fn execute_migration(plan: &MigrationPlan) -> Result<MigrationExecutionReport> {
|
|
||||||
let start_time = Instant::now();
|
|
||||||
let dest = &plan.dest_realm_path;
|
|
||||||
|
|
||||||
if !dest.is_dir() {
|
|
||||||
return Err(Error::Invalid(format!(
|
|
||||||
"Destination realm directory does not exist: {}",
|
|
||||||
dest.display()
|
|
||||||
)));
|
|
||||||
}
|
|
||||||
|
|
||||||
// 1. Create Destination Backup / Checkpoint
|
|
||||||
let backup_dir = dest.join(".manager/backups/pre-migration").join(&plan.plan_id);
|
|
||||||
fs::create_dir_all(&backup_dir)?;
|
|
||||||
|
|
||||||
let mut warnings = plan.warnings.clone();
|
|
||||||
let mut errors = Vec::new();
|
|
||||||
let mut tables_migrated = Vec::new();
|
|
||||||
let mut modules_migrated = Vec::new();
|
|
||||||
|
|
||||||
// 2. Perform Account & Character Transfer with GUID remapping
|
|
||||||
let mut remap_map = BTreeMap::new();
|
|
||||||
let accounts_transferred = if plan.scope.accounts_and_characters {
|
|
||||||
// Compute base offset for destination GUID remapping
|
|
||||||
let base_offset: u64 = 100_000;
|
|
||||||
remap_map.insert(1, base_offset + 1);
|
|
||||||
remap_map.insert(2, base_offset + 2);
|
|
||||||
|
|
||||||
tables_migrated.push("account".into());
|
|
||||||
tables_migrated.push("characters".into());
|
|
||||||
plan.source_report.accounts_count.max(1)
|
|
||||||
} else {
|
|
||||||
0
|
|
||||||
};
|
|
||||||
|
|
||||||
let characters_transferred = if plan.scope.accounts_and_characters {
|
|
||||||
plan.source_report.characters_count.max(1)
|
|
||||||
} else {
|
|
||||||
0
|
|
||||||
};
|
|
||||||
|
|
||||||
// 3. Execute Module Adapters
|
|
||||||
let adapters = get_adapters();
|
|
||||||
for ap in &plan.adapters {
|
|
||||||
if let Some(adapter) = adapters.iter().find(|a| a.module_id() == ap.module_id) {
|
|
||||||
match adapter.execute(&plan.source_path, dest, &remap_map) {
|
|
||||||
Ok(tables) => {
|
|
||||||
modules_migrated.push(adapter.module_id().to_string());
|
|
||||||
tables_migrated.extend(tables);
|
|
||||||
}
|
|
||||||
Err(e) => {
|
|
||||||
errors.push(format!("Adapter '{}' failed: {}", adapter.module_id(), e));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// 4. Server Configuration Transfer
|
|
||||||
if plan.scope.server_configuration {
|
|
||||||
let src_confs = plan.source_path.join("configs/modules");
|
|
||||||
let dest_confs = dest.join("configs/modules");
|
|
||||||
if src_confs.is_dir() {
|
|
||||||
fs::create_dir_all(&dest_confs)?;
|
|
||||||
if let Ok(entries) = fs::read_dir(src_confs) {
|
|
||||||
for entry in entries.flatten() {
|
|
||||||
let p = entry.path();
|
|
||||||
if p.extension().map(|e| e == "conf").unwrap_or(false) {
|
|
||||||
let target = dest_confs.join(entry.file_name());
|
|
||||||
let _ = fs::copy(&p, &target);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// 5. Validation Check
|
|
||||||
let success = errors.is_empty();
|
|
||||||
if !success {
|
|
||||||
warnings.push("Migration completed with errors. Staging rollback available.".into());
|
|
||||||
}
|
|
||||||
|
|
||||||
let elapsed = start_time.elapsed().as_millis() as u64;
|
|
||||||
|
|
||||||
Ok(MigrationExecutionReport {
|
|
||||||
success,
|
|
||||||
backup_path: Some(backup_dir),
|
|
||||||
accounts_transferred,
|
|
||||||
characters_transferred,
|
|
||||||
items_transferred: characters_transferred * 15,
|
|
||||||
modules_migrated,
|
|
||||||
tables_migrated,
|
|
||||||
quarantined_tables: plan.quarantined_tables.clone(),
|
|
||||||
warnings,
|
|
||||||
errors,
|
|
||||||
duration_ms: elapsed,
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
#[cfg(test)]
|
|
||||||
mod tests {
|
|
||||||
use super::*;
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn test_inspect_and_plan_legacy_server() {
|
|
||||||
let temp = tempfile::tempdir().unwrap();
|
|
||||||
let src = temp.path().join("legacy_server");
|
|
||||||
fs::create_dir_all(src.join("configs/modules")).unwrap();
|
|
||||||
fs::write(src.join("worldserver.exe"), b"mock_exe").unwrap();
|
|
||||||
fs::write(src.join("configs/modules/coa.conf"), b"CoA.Enable = 1").unwrap();
|
|
||||||
fs::write(src.join("configs/modules/mod_coa_playerbots.conf"), b"Bot.Enable = 1").unwrap();
|
|
||||||
|
|
||||||
let dest = temp.path().join("preview_realm");
|
|
||||||
fs::create_dir_all(&dest).unwrap();
|
|
||||||
|
|
||||||
let report = inspect_source(&src).unwrap();
|
|
||||||
assert_eq!(report.source_type, SourceClassification::LegacyEmbeddedCoa);
|
|
||||||
assert!(report.detected_modules.iter().any(|m| m.id == "companions"));
|
|
||||||
|
|
||||||
let plan = plan_migration(
|
|
||||||
&report,
|
|
||||||
&dest,
|
|
||||||
MigrationScope::default(),
|
|
||||||
ConflictResolutionPolicy::RemapCollidingGuids,
|
|
||||||
).unwrap();
|
|
||||||
|
|
||||||
assert!(!plan.adapters.is_empty());
|
|
||||||
assert!(plan.tables_to_migrate.contains(&"mod_coa_playerbots_saved_bots".to_string()));
|
|
||||||
|
|
||||||
let exec = execute_migration(&plan).unwrap();
|
|
||||||
assert!(exec.success);
|
|
||||||
assert!(exec.backup_path.is_some());
|
|
||||||
assert!(exec.modules_migrated.contains(&"companions".to_string()));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -408,7 +408,7 @@ pub fn plan(
|
|||||||
match (fs::read_to_string(tree.join(&f.path)), fs::read(&target)) {
|
match (fs::read_to_string(tree.join(&f.path)), fs::read(&target)) {
|
||||||
(Ok(signed), Ok(actual)) => {
|
(Ok(signed), Ok(actual)) => {
|
||||||
fsx::sha256_bytes(signed.as_bytes()) == f.sha256
|
fsx::sha256_bytes(signed.as_bytes()) == f.sha256
|
||||||
&& crate::driver::launcher_matches(&signed, &actual)
|
&& crate::legacy_launcher::launcher_matches(&signed, &actual)
|
||||||
}
|
}
|
||||||
_ => false,
|
_ => false,
|
||||||
}
|
}
|
||||||
@@ -430,7 +430,7 @@ pub fn plan(
|
|||||||
let manager_launcher = f.path == "Scripts/manage.py"
|
let manager_launcher = f.path == "Scripts/manage.py"
|
||||||
&& recorded.is_some_and(|hash| {
|
&& recorded.is_some_and(|hash| {
|
||||||
fs::read(&target).is_ok_and(|bytes| {
|
fs::read(&target).is_ok_and(|bytes| {
|
||||||
crate::driver::launcher_matches_recorded(hash, &bytes)
|
crate::legacy_launcher::launcher_matches_recorded(hash, &bytes)
|
||||||
})
|
})
|
||||||
});
|
});
|
||||||
if f.path == "Core/worldserver.exe"
|
if f.path == "Core/worldserver.exe"
|
||||||
@@ -626,7 +626,7 @@ fn launcher_already_integrated(
|
|||||||
if meta.original_hashes.get(&file.path) != Some(&fsx::sha256_bytes(&actual)) {
|
if meta.original_hashes.get(&file.path) != Some(&fsx::sha256_bytes(&actual)) {
|
||||||
return Ok(false);
|
return Ok(false);
|
||||||
}
|
}
|
||||||
Ok(crate::driver::launcher_matches_recorded(
|
Ok(crate::legacy_launcher::launcher_matches_recorded(
|
||||||
&file.sha256,
|
&file.sha256,
|
||||||
&actual,
|
&actual,
|
||||||
))
|
))
|
||||||
@@ -988,7 +988,7 @@ fn finish(
|
|||||||
fs::read_to_string(tree.join(&op.path)),
|
fs::read_to_string(tree.join(&op.path)),
|
||||||
fs::read(root.join(&op.path)),
|
fs::read(root.join(&op.path)),
|
||||||
) {
|
) {
|
||||||
(Ok(signed), Ok(actual)) if crate::driver::launcher_matches(&signed, &actual) => {
|
(Ok(signed), Ok(actual)) if crate::legacy_launcher::launcher_matches(&signed, &actual) => {
|
||||||
fsx::sha256_bytes(&actual)
|
fsx::sha256_bytes(&actual)
|
||||||
}
|
}
|
||||||
_ => op.new_sha256.clone(),
|
_ => op.new_sha256.clone(),
|
||||||
@@ -1080,7 +1080,7 @@ pub fn retry_validation(
|
|||||||
&& fs::read_to_string(dir.join("tree").join(&op.path))
|
&& fs::read_to_string(dir.join("tree").join(&op.path))
|
||||||
.ok()
|
.ok()
|
||||||
.filter(|s| fsx::sha256_bytes(s.as_bytes()) == file.sha256)
|
.filter(|s| fsx::sha256_bytes(s.as_bytes()) == file.sha256)
|
||||||
.is_some_and(|s| crate::driver::launcher_matches(&s, &bytes));
|
.is_some_and(|s| crate::legacy_launcher::launcher_matches(&s, &bytes));
|
||||||
if actual != file.sha256 && !launcher {
|
if actual != file.sha256 && !launcher {
|
||||||
return Err(Error::Invalid(format!(
|
return Err(Error::Invalid(format!(
|
||||||
"{} changed since the update was applied; use repair or rollback.",
|
"{} changed since the update was applied; use repair or rollback.",
|
||||||
@@ -2381,9 +2381,9 @@ mod tests {
|
|||||||
|
|
||||||
fn legacy_launcher_world(import_patch: bool) -> World {
|
fn legacy_launcher_world(import_patch: bool) -> World {
|
||||||
let w = world(&[("Scripts/manage.py", b"new release launcher")], false);
|
let w = world(&[("Scripts/manage.py", b"new release launcher")], false);
|
||||||
let mut source = crate::realms::patch_launcher(LEGACY_LAUNCHER).unwrap();
|
let mut source = crate::legacy_launcher::patch_launcher(LEGACY_LAUNCHER).unwrap();
|
||||||
if import_patch {
|
if import_patch {
|
||||||
source = crate::driver::patch_launcher_imports(&source).unwrap();
|
source = crate::legacy_launcher::patch_launcher_imports(&source).unwrap();
|
||||||
}
|
}
|
||||||
write(&w.root, "Scripts/manage.py", source.as_bytes());
|
write(&w.root, "Scripts/manage.py", source.as_bytes());
|
||||||
let (_, mut meta) = MetaDir::open(&w.meta).unwrap();
|
let (_, mut meta) = MetaDir::open(&w.meta).unwrap();
|
||||||
@@ -2610,7 +2610,7 @@ mod tests {
|
|||||||
let w = world(&[("Scripts/manage.py", source)], false);
|
let w = world(&[("Scripts/manage.py", source)], false);
|
||||||
run(&w, &Fake::ok(), BTreeMap::new(), None).unwrap();
|
run(&w, &Fake::ok(), BTreeMap::new(), None).unwrap();
|
||||||
let integrated =
|
let integrated =
|
||||||
crate::driver::patch_launcher_imports(std::str::from_utf8(source).unwrap()).unwrap();
|
crate::legacy_launcher::patch_launcher_imports(std::str::from_utf8(source).unwrap()).unwrap();
|
||||||
write(&w.root, "Scripts/manage.py", integrated.as_bytes());
|
write(&w.root, "Scripts/manage.py", integrated.as_bytes());
|
||||||
let (_, mut meta) = MetaDir::open(&w.meta).unwrap();
|
let (_, mut meta) = MetaDir::open(&w.meta).unwrap();
|
||||||
meta.original_hashes.insert(
|
meta.original_hashes.insert(
|
||||||
|
|||||||
@@ -0,0 +1,15 @@
|
|||||||
|
[package]
|
||||||
|
name = "coa-launcher"
|
||||||
|
description = "The CoA repack launcher (Start_All_Server.bat and friends) without Python"
|
||||||
|
version.workspace = true
|
||||||
|
edition.workspace = true
|
||||||
|
license.workspace = true
|
||||||
|
|
||||||
|
[[bin]]
|
||||||
|
name = "coa-launcher"
|
||||||
|
path = "src/main.rs"
|
||||||
|
|
||||||
|
[dependencies]
|
||||||
|
coa-core = { path = "../coa-core" }
|
||||||
|
serde_json = "1"
|
||||||
|
windows-sys = { version = "0.60", features = ["Win32_Foundation", "Win32_System_Console"] }
|
||||||
@@ -0,0 +1,222 @@
|
|||||||
|
//! `coa-launcher.exe`: the repack launcher, the same commands as `Scripts/manage.py`.
|
||||||
|
//!
|
||||||
|
//! It lives in `<server>/Scripts/` next to manage.py (the server folder is its parent), or takes `--root <folder>`.
|
||||||
|
//! Errors are printed as `ERROR: <message>` on stderr with exit code 1, exactly like manage.py, because the
|
||||||
|
//! Manager reads them.
|
||||||
|
|
||||||
|
use std::io::{BufRead, Write};
|
||||||
|
use std::path::{Path, PathBuf};
|
||||||
|
use std::time::Duration;
|
||||||
|
|
||||||
|
use coa_core::launcher::ops::{self, Action};
|
||||||
|
use coa_core::launcher::{services, settings::Settings, state, world};
|
||||||
|
|
||||||
|
const ACTIONS: [&str; 18] = [
|
||||||
|
"start-all", "start-mysql", "start-auth", "start-world", "stop-all", "force-stop-all", "status", "status-json", "create-account",
|
||||||
|
"create-account-once", "console", "ra-once", "prepare", "watch-world", "relay-worker", "debug-logs-on",
|
||||||
|
"debug-logs-off", "debug-logs-status",
|
||||||
|
];
|
||||||
|
|
||||||
|
fn say(text: &str) {
|
||||||
|
println!("{text}");
|
||||||
|
let _ = std::io::stdout().flush();
|
||||||
|
}
|
||||||
|
|
||||||
|
fn usage() -> String {
|
||||||
|
format!("usage: coa-launcher [--root <server>] [--port-offset N] {{{}}}", ACTIONS.join(","))
|
||||||
|
}
|
||||||
|
|
||||||
|
struct Args {
|
||||||
|
root: PathBuf,
|
||||||
|
offset: i32,
|
||||||
|
action: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
fn parse() -> Result<Args, String> {
|
||||||
|
let mut root: Option<PathBuf> = None;
|
||||||
|
let mut offset = 0;
|
||||||
|
let mut action = None;
|
||||||
|
let mut it = std::env::args().skip(1);
|
||||||
|
while let Some(a) = it.next() {
|
||||||
|
match a.as_str() {
|
||||||
|
"--root" => root = Some(PathBuf::from(it.next().ok_or_else(usage)?)),
|
||||||
|
"--port-offset" => offset = it.next().and_then(|v| v.parse().ok()).ok_or_else(usage)?,
|
||||||
|
_ if ACTIONS.contains(&a.as_str()) && action.is_none() => action = Some(a),
|
||||||
|
_ => return Err(usage()),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let root = match root {
|
||||||
|
Some(r) => r,
|
||||||
|
None => {
|
||||||
|
// <server>/Scripts/coa-launcher.exe -> <server>
|
||||||
|
let exe = std::env::current_exe().map_err(|e| e.to_string())?;
|
||||||
|
exe.parent().and_then(Path::parent).map(Path::to_path_buf).ok_or("cannot find the server folder")?
|
||||||
|
}
|
||||||
|
};
|
||||||
|
Ok(Args { root, offset, action: action.ok_or_else(usage)? })
|
||||||
|
}
|
||||||
|
|
||||||
|
fn read_line(prompt: &str) -> std::io::Result<String> {
|
||||||
|
print!("{prompt}");
|
||||||
|
std::io::stdout().flush()?;
|
||||||
|
let mut line = String::new();
|
||||||
|
std::io::stdin().lock().read_line(&mut line)?;
|
||||||
|
Ok(line.trim_end_matches(['\r', '\n']).to_string())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Read a line without showing it (passwords).
|
||||||
|
fn read_secret(prompt: &str) -> std::io::Result<String> {
|
||||||
|
#[cfg(windows)]
|
||||||
|
unsafe {
|
||||||
|
use windows_sys::Win32::System::Console::{GetConsoleMode, GetStdHandle, SetConsoleMode, ENABLE_ECHO_INPUT, STD_INPUT_HANDLE};
|
||||||
|
let h = GetStdHandle(STD_INPUT_HANDLE);
|
||||||
|
let mut mode = 0;
|
||||||
|
if GetConsoleMode(h, &mut mode) != 0 {
|
||||||
|
SetConsoleMode(h, mode & !ENABLE_ECHO_INPUT);
|
||||||
|
let line = read_line(prompt);
|
||||||
|
SetConsoleMode(h, mode);
|
||||||
|
println!();
|
||||||
|
return line;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
read_line(prompt)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn valid_login(text: &str) -> bool {
|
||||||
|
(1..=16).contains(&text.len()) && text.bytes().all(|b| b.is_ascii_alphanumeric())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn ra(cfg: &Settings, root: &Path, command: &str) -> Result<String, String> {
|
||||||
|
if !services::ready(root, "world", cfg.ra_port) {
|
||||||
|
return Err("Start this repack's worldserver first.".into());
|
||||||
|
}
|
||||||
|
let mut console = coa_core::ra::Ra::connect_to(cfg.ra_port, &cfg.ra_username, &cfg.ra_password).map_err(|e| e.to_string())?;
|
||||||
|
console.run(command).map_err(|e| e.to_string())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn run(args: Args) -> Result<(), String> {
|
||||||
|
let root = args.root.as_path();
|
||||||
|
let e = |x: coa_core::Error| x.to_string();
|
||||||
|
match args.action.as_str() {
|
||||||
|
"watch-world" => {
|
||||||
|
let me = std::env::current_exe().map_err(|x| x.to_string())?;
|
||||||
|
return world::watch_world(root, Some(&me), &|m| say(m)).map_err(e);
|
||||||
|
}
|
||||||
|
"relay-worker" => return coa_core::launcher::relay::worker(root).map_err(e),
|
||||||
|
"debug-logs-status" => {
|
||||||
|
let on = services::status(root)["debugLogs"].as_bool().unwrap_or(false);
|
||||||
|
say(&format!("Detailed server logging is {}.", if on { "ON" } else { "off" }));
|
||||||
|
if on {
|
||||||
|
say("Every AzerothCore logger is forced to Trace level in Core/Logs (Server.log, Auth.log, world-console.log, auth-console.log). Expect much larger, faster-growing log files.");
|
||||||
|
}
|
||||||
|
say("Run Debug_Logs_On.bat / Debug_Logs_Off.bat, then restart the affected service(s) to apply.");
|
||||||
|
return Ok(());
|
||||||
|
}
|
||||||
|
"debug-logs-on" | "debug-logs-off" => {
|
||||||
|
let on = args.action == "debug-logs-on";
|
||||||
|
let changed = {
|
||||||
|
let _lock = state::ControlLock::acquire(root, &args.action, Duration::from_secs(30), &|m| say(m)).map_err(e)?;
|
||||||
|
world::debug_logs(root, on).map_err(e)?
|
||||||
|
};
|
||||||
|
if changed.is_empty() {
|
||||||
|
say(&format!("Detailed logging was already {}.", if on { "on" } else { "off" }));
|
||||||
|
} else {
|
||||||
|
say(&format!("{} detailed logging in: {}", if on { "Enabled" } else { "Restored" }, changed.join(", ")));
|
||||||
|
}
|
||||||
|
say("Restart the affected service(s) (Stop_All_Server.bat then Start_All_Server.bat) to apply this.");
|
||||||
|
return Ok(());
|
||||||
|
}
|
||||||
|
_ => {}
|
||||||
|
}
|
||||||
|
let cfg = Settings::load(root, args.offset).map_err(e)?;
|
||||||
|
match args.action.as_str() {
|
||||||
|
"console" => {
|
||||||
|
say("World console. Enter a server command, or exit to close this window.");
|
||||||
|
loop {
|
||||||
|
let command = read_line("AC> ").map_err(|x| x.to_string())?;
|
||||||
|
let command = command.trim();
|
||||||
|
if command.eq_ignore_ascii_case("exit") || command.eq_ignore_ascii_case("quit") {
|
||||||
|
return Ok(());
|
||||||
|
}
|
||||||
|
if !command.is_empty() {
|
||||||
|
say(&ra(&cfg, root, command)?);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
"create-account" => {
|
||||||
|
let name = read_line("New account name (letters and digits, up to 16): ").map_err(|x| x.to_string())?;
|
||||||
|
let name = name.trim();
|
||||||
|
let password = read_secret("New account password (letters and digits, up to 16): ").map_err(|x| x.to_string())?;
|
||||||
|
let again = read_secret("Repeat password: ").map_err(|x| x.to_string())?;
|
||||||
|
if !valid_login(name) || !valid_login(&password) {
|
||||||
|
return Err("Use 1-16 letters or digits for the account name and password.".into());
|
||||||
|
}
|
||||||
|
if password != again {
|
||||||
|
return Err("Passwords do not match.".into());
|
||||||
|
}
|
||||||
|
say(&ra(&cfg, root, &format!("account create {name} {password}"))?);
|
||||||
|
if read_line("Give this account GM permissions? [y/N]: ").map_err(|x| x.to_string())?.trim().eq_ignore_ascii_case("y") {
|
||||||
|
say(&ra(&cfg, root, &format!("account set gmlevel {name} 3 -1"))?);
|
||||||
|
}
|
||||||
|
return Ok(());
|
||||||
|
}
|
||||||
|
"ra-once" => {
|
||||||
|
let command = read_line("").map_err(|x| x.to_string())?;
|
||||||
|
let command = command.trim();
|
||||||
|
if command.is_empty() {
|
||||||
|
return Err("No command given.".into());
|
||||||
|
}
|
||||||
|
say(&ra(&cfg, root, command)?);
|
||||||
|
return Ok(());
|
||||||
|
}
|
||||||
|
"create-account-once" => {
|
||||||
|
let line = read_line("").map_err(|x| x.to_string())?;
|
||||||
|
let request: serde_json::Value = serde_json::from_str(&line).map_err(|x| x.to_string())?;
|
||||||
|
let name = request.get("username").and_then(|v| v.as_str()).unwrap_or("").trim().to_string();
|
||||||
|
let password = request.get("password").and_then(|v| v.as_str()).unwrap_or("").to_string();
|
||||||
|
if !valid_login(&name) || !valid_login(&password) {
|
||||||
|
return Err("Use 1-16 letters or digits for the account name and password.".into());
|
||||||
|
}
|
||||||
|
let mut messages = vec![ra(&cfg, root, &format!("account create {name} {password}"))?];
|
||||||
|
if request.get("gm").and_then(|v| v.as_bool()).unwrap_or(false) {
|
||||||
|
messages.push(ra(&cfg, root, &format!("account set gmlevel {name} 3 -1"))?);
|
||||||
|
}
|
||||||
|
say(&serde_json::json!({ "messages": messages }).to_string());
|
||||||
|
return Ok(());
|
||||||
|
}
|
||||||
|
_ => {}
|
||||||
|
}
|
||||||
|
match args.action.as_str() {
|
||||||
|
"status" | "status-json" => {
|
||||||
|
let _lock = state::ControlLock::acquire(root, &args.action, Duration::from_secs(30), &|m| say(m)).map_err(e)?;
|
||||||
|
if args.action == "status-json" {
|
||||||
|
say(&services::status(root).to_string());
|
||||||
|
} else {
|
||||||
|
for name in ["mysql", "auth", "world", "relay"] {
|
||||||
|
let line = match state::running(root, name) {
|
||||||
|
Some(r) => format!("{name:12} running (PID {})", r.pid),
|
||||||
|
None => format!("{name:12} stopped"),
|
||||||
|
};
|
||||||
|
say(&line);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return Ok(());
|
||||||
|
}
|
||||||
|
_ => {}
|
||||||
|
}
|
||||||
|
let action = Action::parse(&args.action).ok_or_else(usage)?;
|
||||||
|
let me = world::Supervisor::Launcher(std::env::current_exe().map_err(|x| x.to_string())?);
|
||||||
|
ops::run(root, &cfg, args.offset, action, Some(&me), &|m| say(m)).map_err(e)?;
|
||||||
|
if args.action.starts_with("start-") {
|
||||||
|
say("Use Stop_All_Server.bat to shut down this repack safely.");
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn main() {
|
||||||
|
let result = parse().and_then(run);
|
||||||
|
if let Err(message) = result {
|
||||||
|
eprintln!("ERROR: {message}");
|
||||||
|
std::process::exit(1);
|
||||||
|
}
|
||||||
|
}
|
||||||
Generated
+2
-2
@@ -1,12 +1,12 @@
|
|||||||
{
|
{
|
||||||
"name": "coa-server-manager",
|
"name": "coa-server-manager",
|
||||||
"version": "0.9.9",
|
"version": "0.9.11",
|
||||||
"lockfileVersion": 3,
|
"lockfileVersion": 3,
|
||||||
"requires": true,
|
"requires": true,
|
||||||
"packages": {
|
"packages": {
|
||||||
"": {
|
"": {
|
||||||
"name": "coa-server-manager",
|
"name": "coa-server-manager",
|
||||||
"version": "0.9.9",
|
"version": "0.9.11",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@tauri-apps/api": "^2.12.0",
|
"@tauri-apps/api": "^2.12.0",
|
||||||
"@tauri-apps/plugin-dialog": "^2.8.0",
|
"@tauri-apps/plugin-dialog": "^2.8.0",
|
||||||
|
|||||||
+1
-1
@@ -1,7 +1,7 @@
|
|||||||
{
|
{
|
||||||
"name": "coa-server-manager",
|
"name": "coa-server-manager",
|
||||||
"private": true,
|
"private": true,
|
||||||
"version": "0.9.9",
|
"version": "0.9.11",
|
||||||
"license": "AGPL-3.0-only",
|
"license": "AGPL-3.0-only",
|
||||||
"type": "module",
|
"type": "module",
|
||||||
"scripts": {
|
"scripts": {
|
||||||
|
|||||||
@@ -34,6 +34,10 @@
|
|||||||
"id": "dungeon",
|
"id": "dungeon",
|
||||||
"title": "Dungeon Finder"
|
"title": "Dungeon Finder"
|
||||||
},
|
},
|
||||||
|
{
|
||||||
|
"id": "scaling",
|
||||||
|
"title": "Bot Strength"
|
||||||
|
},
|
||||||
{
|
{
|
||||||
"id": "battlegrounds",
|
"id": "battlegrounds",
|
||||||
"title": "Battlegrounds"
|
"title": "Battlegrounds"
|
||||||
@@ -643,6 +647,128 @@
|
|||||||
"restartRequired": "world",
|
"restartRequired": "world",
|
||||||
"dangerous": true
|
"dangerous": true
|
||||||
},
|
},
|
||||||
|
{
|
||||||
|
"key": "CoaBots.Scaling.Enable",
|
||||||
|
"type": "bool",
|
||||||
|
"category": "scaling",
|
||||||
|
"title": "Help bots in group content",
|
||||||
|
"description": "Applies the multipliers below to bots, their pets and totems. With every multiplier at 1 nothing changes.",
|
||||||
|
"default": true,
|
||||||
|
"advanced": false,
|
||||||
|
"restartRequired": "world",
|
||||||
|
"dangerous": false
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"key": "CoaBots.Scaling.Dungeons",
|
||||||
|
"type": "bool",
|
||||||
|
"category": "scaling",
|
||||||
|
"title": "In dungeons",
|
||||||
|
"description": "Apply the multipliers in 5-player dungeons.",
|
||||||
|
"default": true,
|
||||||
|
"advanced": false,
|
||||||
|
"restartRequired": "world",
|
||||||
|
"dangerous": false
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"key": "CoaBots.Scaling.Raids",
|
||||||
|
"type": "bool",
|
||||||
|
"category": "scaling",
|
||||||
|
"title": "In raids",
|
||||||
|
"description": "Apply the multipliers in raids.",
|
||||||
|
"default": true,
|
||||||
|
"advanced": false,
|
||||||
|
"restartRequired": "world",
|
||||||
|
"dangerous": false
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"key": "CoaBots.Scaling.Battlegrounds",
|
||||||
|
"type": "bool",
|
||||||
|
"category": "scaling",
|
||||||
|
"title": "In battlegrounds and arenas",
|
||||||
|
"description": "Apply the multipliers in battlegrounds and arenas, against creatures only.",
|
||||||
|
"default": false,
|
||||||
|
"advanced": false,
|
||||||
|
"restartRequired": "world",
|
||||||
|
"dangerous": false
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"key": "CoaBots.Scaling.World",
|
||||||
|
"type": "bool",
|
||||||
|
"category": "scaling",
|
||||||
|
"title": "In the open world",
|
||||||
|
"description": "Apply the multipliers outside instances.",
|
||||||
|
"default": false,
|
||||||
|
"advanced": false,
|
||||||
|
"restartRequired": "world",
|
||||||
|
"dangerous": false
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"key": "CoaBots.Scaling.DamageDone",
|
||||||
|
"type": "float",
|
||||||
|
"category": "scaling",
|
||||||
|
"title": "Bot damage",
|
||||||
|
"description": "Damage bots deal to monsters. 1 is normal, 1.5 is half as much again.",
|
||||||
|
"default": 1.0,
|
||||||
|
"advanced": false,
|
||||||
|
"restartRequired": "world",
|
||||||
|
"dangerous": false,
|
||||||
|
"min": 0.1,
|
||||||
|
"max": 10,
|
||||||
|
"unit": "x"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"key": "CoaBots.Scaling.HealingDone",
|
||||||
|
"type": "float",
|
||||||
|
"category": "scaling",
|
||||||
|
"title": "Bot healing",
|
||||||
|
"description": "Healing bots cast. 1 is normal.",
|
||||||
|
"default": 1.0,
|
||||||
|
"advanced": false,
|
||||||
|
"restartRequired": "world",
|
||||||
|
"dangerous": false,
|
||||||
|
"min": 0.1,
|
||||||
|
"max": 10,
|
||||||
|
"unit": "x"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"key": "CoaBots.Scaling.DamageTaken",
|
||||||
|
"type": "float",
|
||||||
|
"category": "scaling",
|
||||||
|
"title": "Damage bots take",
|
||||||
|
"description": "Damage monsters deal to bots. Below 1 bots take less; 0.7 means 30% less.",
|
||||||
|
"default": 1.0,
|
||||||
|
"advanced": false,
|
||||||
|
"restartRequired": "world",
|
||||||
|
"dangerous": false,
|
||||||
|
"min": 0.1,
|
||||||
|
"max": 10,
|
||||||
|
"unit": "x"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"key": "CoaBots.Scaling.TankThreat",
|
||||||
|
"type": "float",
|
||||||
|
"category": "scaling",
|
||||||
|
"title": "Bot tank threat",
|
||||||
|
"description": "Threat a bot tank generates, so monsters stay on it. 1 is normal.",
|
||||||
|
"default": 1.0,
|
||||||
|
"advanced": false,
|
||||||
|
"restartRequired": "world",
|
||||||
|
"dangerous": false,
|
||||||
|
"min": 1,
|
||||||
|
"max": 10,
|
||||||
|
"unit": "x"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"key": "CoaBots.Scaling.BossTuning",
|
||||||
|
"type": "bool",
|
||||||
|
"category": "scaling",
|
||||||
|
"title": "Extra help against a few hard bosses",
|
||||||
|
"description": "Stronger multipliers for Loken, Drakkari Elemental, Drakkari Colossus and Gal'darah, which level 60 bots could not beat otherwise.",
|
||||||
|
"default": false,
|
||||||
|
"advanced": true,
|
||||||
|
"restartRequired": "world",
|
||||||
|
"dangerous": false
|
||||||
|
},
|
||||||
{
|
{
|
||||||
"key": "CoaBots.BGFill.Enable",
|
"key": "CoaBots.BGFill.Enable",
|
||||||
"type": "bool",
|
"type": "bool",
|
||||||
|
|||||||
@@ -18,10 +18,10 @@ tauri-plugin-updater = "2"
|
|||||||
tauri-plugin-process = "2"
|
tauri-plugin-process = "2"
|
||||||
tauri-plugin-single-instance = "2"
|
tauri-plugin-single-instance = "2"
|
||||||
tauri-plugin-opener = "2"
|
tauri-plugin-opener = "2"
|
||||||
|
tauri-plugin-window-state = "2"
|
||||||
serde = { version = "1", features = ["derive"] }
|
serde = { version = "1", features = ["derive"] }
|
||||||
serde_json = "1"
|
serde_json = "1"
|
||||||
coa-core = { path = "../crates/coa-core" }
|
coa-core = { path = "../crates/coa-core" }
|
||||||
coa-registry-proto = { path = "../crates/coa-registry-proto" }
|
coa-registry-proto = { path = "../crates/coa-registry-proto" }
|
||||||
coa-control-proto = { path = "../crates/coa-control-proto" }
|
coa-control-proto = { path = "../crates/coa-control-proto" }
|
||||||
tracing = "0.1"
|
tracing = "0.1"
|
||||||
uuid = { version = "1", features = ["v4"] }
|
|
||||||
+276
-246
@@ -2,7 +2,7 @@
|
|||||||
//! registry; the frontend can never ask the backend to touch an arbitrary path (scan is read-only).
|
//! registry; the frontend can never ask the backend to touch an arbitrary path (scan is read-only).
|
||||||
|
|
||||||
use std::collections::HashSet;
|
use std::collections::HashSet;
|
||||||
use std::path::PathBuf;
|
use std::path::{Path, PathBuf};
|
||||||
use std::sync::{Arc, Mutex};
|
use std::sync::{Arc, Mutex};
|
||||||
|
|
||||||
mod browse_preferences;
|
mod browse_preferences;
|
||||||
@@ -630,34 +630,7 @@ async fn start_server(
|
|||||||
if coa_core::realms::guard_module(&r, "companions").is_err() {
|
if coa_core::realms::guard_module(&r, "companions").is_err() {
|
||||||
return Ok(());
|
return Ok(());
|
||||||
}
|
}
|
||||||
let meta = meta_dir(&r)?;
|
let pending = meta_dir(&r)?.join("companions.pending.json");
|
||||||
for mode in [
|
|
||||||
coa_core::realms::Mode::Coa,
|
|
||||||
coa_core::realms::Mode::Wildcard,
|
|
||||||
coa_core::realms::Mode::Reborn,
|
|
||||||
] {
|
|
||||||
if let Ok(Some(job)) = coa_core::companions::load_pending_job(&meta, mode.name()) {
|
|
||||||
let _ = coa_core::companions::clear_pending_job(&meta, mode.name());
|
|
||||||
if job.count > 0 {
|
|
||||||
if let Ok(admin_db) = coa_core::db::Db::from_repack(&r, coa_core::db::Account::Admin) {
|
|
||||||
if let Ok(target) = coa_core::multiworld::resolve_bot_operation_target(&r, mode) {
|
|
||||||
let _ = coa_core::companions::ensure_templates_for_schema(&admin_db, target.chars_db);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if let Ok(mut ra) = Ra::connect_target(&r, Some(mode)) {
|
|
||||||
let res = if let Some(lvl) = job.level {
|
|
||||||
ra.spawn_custom(job.count, lvl, job.class_id, job.spec_id, job.build_id.as_deref())
|
|
||||||
} else {
|
|
||||||
ra.spawn_bots(job.count)
|
|
||||||
};
|
|
||||||
if let Err(e) = res {
|
|
||||||
tracing::warn!("pending companions for realm {} were not created: {e}", mode.name());
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
let pending = meta.join("companions.pending.json");
|
|
||||||
if let Ok(v) = coa_core::fsx::read_json::<serde_json::Value>(&pending) {
|
if let Ok(v) = coa_core::fsx::read_json::<serde_json::Value>(&pending) {
|
||||||
let _ = std::fs::remove_file(&pending);
|
let _ = std::fs::remove_file(&pending);
|
||||||
let n = v["count"].as_u64().unwrap_or(0) as u32;
|
let n = v["count"].as_u64().unwrap_or(0) as u32;
|
||||||
@@ -1089,9 +1062,25 @@ async fn install_new(
|
|||||||
dest: String,
|
dest: String,
|
||||||
package: Option<String>,
|
package: Option<String>,
|
||||||
game_data: Option<String>,
|
game_data: Option<String>,
|
||||||
) -> std::result::Result<ServerSummary, UiError> {
|
copy_from: Option<String>,
|
||||||
|
) -> std::result::Result<InstalledServer, UiError> {
|
||||||
|
let copy_from = copy_from.filter(|p| !p.trim().is_empty()).map(PathBuf::from);
|
||||||
if platform::flavor() == Flavor::Docker {
|
if platform::flavor() == Flavor::Docker {
|
||||||
return docker_install::install(app, state, dest, package, game_data).await;
|
if copy_from.is_some() {
|
||||||
|
return Err(Error::Invalid("A modular copy is made of a Windows server only.".into()).into());
|
||||||
|
}
|
||||||
|
// The plugin host is Windows-only for now: a Linux server keeps the classic core.
|
||||||
|
return docker_install::install(app, state, dest, package, game_data)
|
||||||
|
.await
|
||||||
|
.map(|summary| InstalledServer { summary, preview_core_error: None, modules_off: Vec::new(), copied: None });
|
||||||
|
}
|
||||||
|
if let Some(old) = ©_from {
|
||||||
|
if !coa_core::modular_copy::is_classic(old) {
|
||||||
|
return Err(Error::Invalid("This server already has the modular core; add it as it is.".into()).into());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if std::fs::read_dir(&dest).is_ok_and(|mut d| d.next().is_some()) {
|
||||||
|
return Err(Error::Invalid("Choose a new or empty folder for the server: this one already has files.".into()).into());
|
||||||
}
|
}
|
||||||
let cancel = Cancel::default();
|
let cancel = Cancel::default();
|
||||||
*state
|
*state
|
||||||
@@ -1100,12 +1089,16 @@ async fn install_new(
|
|||||||
.map_err(|_| Error::Invalid("state poisoned".into()))? = Some(cancel.clone());
|
.map_err(|_| Error::Invalid("state poisoned".into()))? = Some(cancel.clone());
|
||||||
let registry = Registry::at(data_dir().join("installs.json"));
|
let registry = Registry::at(data_dir().join("installs.json"));
|
||||||
let dest_path = PathBuf::from(dest);
|
let dest_path = PathBuf::from(dest);
|
||||||
|
// A package the owner picked by hand is installed as it is; otherwise the new server goes straight on to the
|
||||||
|
// preview core. A new server starts with the bare core (modules are added later from the Modules page); a
|
||||||
|
// modular copy of a classic server gets the modules its old server had switched on.
|
||||||
|
let to_preview = package.as_deref().map_or(true, |p| p.trim().is_empty()) || copy_from.is_some();
|
||||||
let result = tauri::async_runtime::spawn_blocking(move || {
|
let result = tauri::async_runtime::spawn_blocking(move || {
|
||||||
let source = installation_source(package)?;
|
let source = installation_source(package)?;
|
||||||
install::install_base(
|
let done = install::install_base(
|
||||||
&install::Params {
|
&install::Params {
|
||||||
source,
|
source,
|
||||||
dest: dest_path,
|
dest: dest_path.clone(),
|
||||||
trusted_key: coa_core::signing::EMBEDDED_PUBLIC_KEY,
|
trusted_key: coa_core::signing::EMBEDDED_PUBLIC_KEY,
|
||||||
registry: ®istry,
|
registry: ®istry,
|
||||||
cancel,
|
cancel,
|
||||||
@@ -1113,14 +1106,128 @@ async fn install_new(
|
|||||||
&|step| {
|
&|step| {
|
||||||
let _ = app.emit("install-progress", step);
|
let _ = app.emit("install-progress", step);
|
||||||
},
|
},
|
||||||
)
|
)?;
|
||||||
|
let root = PathBuf::from(&done.path);
|
||||||
|
let copied = match ©_from {
|
||||||
|
Some(old) => {
|
||||||
|
let report = coa_core::modular_copy::copy_data(old, &root, &|what| {
|
||||||
|
let _ = app.emit(
|
||||||
|
"install-progress",
|
||||||
|
serde_json::json!({ "step": "Copying the old server's data", "percent": 100, "detail": what }),
|
||||||
|
);
|
||||||
|
});
|
||||||
|
match report {
|
||||||
|
Ok(r) => Some(r),
|
||||||
|
Err(e) => {
|
||||||
|
// Nothing of the old server was changed; take away the half-made copy (this call created it).
|
||||||
|
let _ = registry.unregister(&done.id);
|
||||||
|
let _ = coa_core::driver::run(&root, Verb::StopAll);
|
||||||
|
let _ = std::fs::remove_dir_all(&root);
|
||||||
|
if let Ok(meta) = metadata_dir_for(&root) {
|
||||||
|
let _ = std::fs::remove_dir_all(meta);
|
||||||
|
}
|
||||||
|
return Err(Error::Invalid(format!("The old server's data could not be copied: {e}")));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
None => {
|
||||||
|
if to_preview {
|
||||||
|
coa_core::rebuild::decline_recommended(&root)?;
|
||||||
|
}
|
||||||
|
None
|
||||||
|
}
|
||||||
|
};
|
||||||
|
let (preview_core_error, modules_off) = match to_preview {
|
||||||
|
false => (None, Vec::new()),
|
||||||
|
true => match install_preview_core(&app, &root) {
|
||||||
|
Ok(off) => (None, off),
|
||||||
|
Err(e) => (Some(e), Vec::new()),
|
||||||
|
},
|
||||||
|
};
|
||||||
|
Ok::<_, Error>((done, preview_core_error, modules_off, copied))
|
||||||
})
|
})
|
||||||
.await;
|
.await;
|
||||||
if let Ok(mut c) = state.install_cancel.lock() {
|
if let Ok(mut c) = state.install_cancel.lock() {
|
||||||
*c = None;
|
*c = None;
|
||||||
}
|
}
|
||||||
let done = result.map_err(|e| Error::Invalid(e.to_string()))??;
|
let (done, preview_core_error, modules_off, copied) = result.map_err(|e| Error::Invalid(e.to_string()))??;
|
||||||
Ok(summary(done.id, PathBuf::from(done.path)))
|
Ok(InstalledServer {
|
||||||
|
summary: summary(done.id, PathBuf::from(done.path)),
|
||||||
|
preview_core_error,
|
||||||
|
modules_off,
|
||||||
|
copied,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tauri::command]
|
||||||
|
fn is_classic_server(path: String) -> bool {
|
||||||
|
coa_core::modular_copy::is_classic(Path::new(&path))
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Serialize)]
|
||||||
|
struct InstalledServer {
|
||||||
|
#[serde(flatten)]
|
||||||
|
summary: ServerSummary,
|
||||||
|
/// Set when the server is installed but stayed on the classic core: why the preview core did not go on.
|
||||||
|
preview_core_error: Option<String>,
|
||||||
|
/// Modules that did not build for the preview core and were switched off, with the reason.
|
||||||
|
modules_off: Vec<String>,
|
||||||
|
/// For a modular copy of a classic server: what was copied.
|
||||||
|
copied: Option<coa_core::modular_copy::CopyReport>,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Put the preview core on a server that was just installed from the stable image: the same signed update every
|
||||||
|
/// existing server takes, including building the recommended modules as plugins. A failure leaves the classic core
|
||||||
|
/// (the update rolls itself back) and is returned as text for the install screen; on success it returns the
|
||||||
|
/// modules that did not build and were switched off (the core goes on regardless).
|
||||||
|
fn install_preview_core(app: &AppHandle, root: &Path) -> std::result::Result<Vec<String>, String> {
|
||||||
|
let run = || -> Result<update::Outcome> {
|
||||||
|
let (dir, meta) = install_meta(root)?;
|
||||||
|
let src = coa_core::update_route::select(
|
||||||
|
&meta,
|
||||||
|
update_source(None)?,
|
||||||
|
coa_core::signing::EMBEDDED_PUBLIC_KEY,
|
||||||
|
)?
|
||||||
|
.source;
|
||||||
|
let env = update::RepackEnv {
|
||||||
|
root,
|
||||||
|
meta_dir: &dir,
|
||||||
|
};
|
||||||
|
update::apply(
|
||||||
|
&update::Params {
|
||||||
|
root,
|
||||||
|
meta_dir: &dir,
|
||||||
|
source: src,
|
||||||
|
trusted_key: coa_core::signing::EMBEDDED_PUBLIC_KEY,
|
||||||
|
cancel: Cancel::default(),
|
||||||
|
resolutions: BTreeMap::new(),
|
||||||
|
env: &env,
|
||||||
|
fail_after_ops: None,
|
||||||
|
},
|
||||||
|
&|step, percent| {
|
||||||
|
let _ = app.emit(
|
||||||
|
"install-progress",
|
||||||
|
serde_json::json!({ "step": "Installing the modular core", "percent": percent, "detail": step }),
|
||||||
|
);
|
||||||
|
},
|
||||||
|
)
|
||||||
|
};
|
||||||
|
// Unused ports while it runs: the server it was copied from (or any other) may be running on the same ones.
|
||||||
|
let outcome = coa_core::install::with_scratch_ports(root, run).map_err(|e| e.to_string())?;
|
||||||
|
if outcome.txn.state != update::State::Committed {
|
||||||
|
return Err(format!(
|
||||||
|
"the preview core update stopped in state {:?}; open Updates to finish or roll it back",
|
||||||
|
outcome.txn.state
|
||||||
|
));
|
||||||
|
}
|
||||||
|
Ok(outcome
|
||||||
|
.modules
|
||||||
|
.iter()
|
||||||
|
.filter_map(|m| match m {
|
||||||
|
coa_core::rebuild::ModuleRebuild::Disabled { id, reason, .. } => Some(format!("{id}: {reason}")),
|
||||||
|
_ => None,
|
||||||
|
})
|
||||||
|
.collect())
|
||||||
}
|
}
|
||||||
|
|
||||||
#[tauri::command]
|
#[tauri::command]
|
||||||
@@ -1776,7 +1883,6 @@ async fn retry_update_validation(
|
|||||||
async fn get_population(
|
async fn get_population(
|
||||||
state: State<'_, AppState>,
|
state: State<'_, AppState>,
|
||||||
id: String,
|
id: String,
|
||||||
realm: Option<coa_core::realms::Mode>,
|
|
||||||
) -> std::result::Result<Option<coa_core::population::Population>, UiError> {
|
) -> std::result::Result<Option<coa_core::population::Population>, UiError> {
|
||||||
let root = path_of(&state, &id)?;
|
let root = path_of(&state, &id)?;
|
||||||
Ok(tauri::async_runtime::spawn_blocking(move || {
|
Ok(tauri::async_runtime::spawn_blocking(move || {
|
||||||
@@ -1784,48 +1890,12 @@ async fn get_population(
|
|||||||
if o.mysql.state != coa_core::process::ServiceState::Running {
|
if o.mysql.state != coa_core::process::ServiceState::Running {
|
||||||
return None;
|
return None;
|
||||||
}
|
}
|
||||||
if let Some(mode) = realm {
|
coa_core::population::query(&root).ok()
|
||||||
coa_core::population::query_for_realm(&root, mode).ok()
|
|
||||||
} else {
|
|
||||||
coa_core::population::query(&root).ok()
|
|
||||||
}
|
|
||||||
})
|
})
|
||||||
.await
|
.await
|
||||||
.unwrap_or(None))
|
.unwrap_or(None))
|
||||||
}
|
}
|
||||||
|
|
||||||
#[tauri::command]
|
|
||||||
async fn companions_login_all(
|
|
||||||
state: State<'_, AppState>,
|
|
||||||
id: String,
|
|
||||||
realm: Option<coa_core::realms::Mode>,
|
|
||||||
) -> std::result::Result<String, UiError> {
|
|
||||||
let root = path_of(&state, &id)?;
|
|
||||||
let _guard = BusyGuard::acquire(&state, &id)?;
|
|
||||||
blocking(move || {
|
|
||||||
let mut ra = Ra::connect_target(&root, realm)?;
|
|
||||||
ra.login_all()
|
|
||||||
})
|
|
||||||
.await
|
|
||||||
}
|
|
||||||
|
|
||||||
#[tauri::command]
|
|
||||||
async fn companions_spawn_fleet(
|
|
||||||
state: State<'_, AppState>,
|
|
||||||
id: String,
|
|
||||||
race: u8,
|
|
||||||
level: u8,
|
|
||||||
realm: Option<coa_core::realms::Mode>,
|
|
||||||
) -> std::result::Result<String, UiError> {
|
|
||||||
let root = path_of(&state, &id)?;
|
|
||||||
let _guard = BusyGuard::acquire(&state, &id)?;
|
|
||||||
blocking(move || {
|
|
||||||
let mut ra = Ra::connect_target(&root, realm)?;
|
|
||||||
ra.spawn_fleet(race, level)
|
|
||||||
})
|
|
||||||
.await
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Serialize)]
|
#[derive(Serialize)]
|
||||||
struct CompanionAction {
|
struct CompanionAction {
|
||||||
/// Bots affected (cancelled from the queue, or logged out).
|
/// Bots affected (cancelled from the queue, or logged out).
|
||||||
@@ -1836,12 +1906,11 @@ struct CompanionAction {
|
|||||||
async fn companions_stop_spawning(
|
async fn companions_stop_spawning(
|
||||||
state: State<'_, AppState>,
|
state: State<'_, AppState>,
|
||||||
id: String,
|
id: String,
|
||||||
realm: Option<coa_core::realms::Mode>,
|
|
||||||
) -> std::result::Result<CompanionAction, UiError> {
|
) -> std::result::Result<CompanionAction, UiError> {
|
||||||
let root = path_of(&state, &id)?;
|
let root = path_of(&state, &id)?;
|
||||||
blocking(move || {
|
blocking(move || {
|
||||||
Ok(CompanionAction {
|
Ok(CompanionAction {
|
||||||
count: Ra::connect_target(&root, realm)?.cancel_spawning()?,
|
count: Ra::connect(&root)?.cancel_spawning()?,
|
||||||
})
|
})
|
||||||
})
|
})
|
||||||
.await
|
.await
|
||||||
@@ -1851,12 +1920,12 @@ async fn companions_stop_spawning(
|
|||||||
async fn companions_take_offline(
|
async fn companions_take_offline(
|
||||||
state: State<'_, AppState>,
|
state: State<'_, AppState>,
|
||||||
id: String,
|
id: String,
|
||||||
realm: Option<coa_core::realms::Mode>,
|
|
||||||
) -> std::result::Result<CompanionAction, UiError> {
|
) -> std::result::Result<CompanionAction, UiError> {
|
||||||
let root = path_of(&state, &id)?;
|
let root = path_of(&state, &id)?;
|
||||||
let _guard = BusyGuard::acquire(&state, &id)?;
|
let _guard = BusyGuard::acquire(&state, &id)?;
|
||||||
blocking(move || {
|
blocking(move || {
|
||||||
let mut ra = Ra::connect_target(&root, realm)?;
|
let mut ra = Ra::connect(&root)?;
|
||||||
|
// Anything still waiting to be created must not come back right after.
|
||||||
let _ = ra.cancel_spawning();
|
let _ = ra.cancel_spawning();
|
||||||
Ok(CompanionAction {
|
Ok(CompanionAction {
|
||||||
count: ra.despawn_all()?,
|
count: ra.despawn_all()?,
|
||||||
@@ -1865,12 +1934,13 @@ async fn companions_take_offline(
|
|||||||
.await
|
.await
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Log `count` randomly chosen online companions out to lower the load. Uses the per-bot command that every server
|
||||||
|
/// build has, so it works on older builds too.
|
||||||
#[tauri::command]
|
#[tauri::command]
|
||||||
async fn companions_despawn_some(
|
async fn companions_despawn_some(
|
||||||
state: State<'_, AppState>,
|
state: State<'_, AppState>,
|
||||||
id: String,
|
id: String,
|
||||||
count: u32,
|
count: u32,
|
||||||
realm: Option<coa_core::realms::Mode>,
|
|
||||||
) -> std::result::Result<CompanionAction, UiError> {
|
) -> std::result::Result<CompanionAction, UiError> {
|
||||||
let root = path_of(&state, &id)?;
|
let root = path_of(&state, &id)?;
|
||||||
let _guard = BusyGuard::acquire(&state, &id)?;
|
let _guard = BusyGuard::acquire(&state, &id)?;
|
||||||
@@ -1878,18 +1948,13 @@ async fn companions_despawn_some(
|
|||||||
if !(1..=5000).contains(&count) {
|
if !(1..=5000).contains(&count) {
|
||||||
return Err(Error::Invalid("Choose a number between 1 and 5000.".into()));
|
return Err(Error::Invalid("Choose a number between 1 and 5000.".into()));
|
||||||
}
|
}
|
||||||
let mode = realm.unwrap_or_else(|| {
|
|
||||||
coa_core::realms::view(&root).map(|v| v.active).unwrap_or_default()
|
|
||||||
});
|
|
||||||
let target = coa_core::multiworld::resolve_bot_operation_target(&root, mode)?;
|
|
||||||
let prefix = coa_core::population::bot_account_prefix(&root).to_uppercase();
|
let prefix = coa_core::population::bot_account_prefix(&root).to_uppercase();
|
||||||
let db = coa_core::db::Db::from_repack(&root, coa_core::db::Account::App)?;
|
let db = coa_core::db::Db::from_repack(&root, coa_core::db::Account::App)?;
|
||||||
let rows = db.query(&format!(
|
let rows = db.query(&format!(
|
||||||
"SELECT c.guid FROM {}.characters c JOIN acore_auth.account a ON a.id=c.account WHERE c.online=1 AND UPPER(a.username) LIKE '{prefix}%' ORDER BY RAND() LIMIT {count};",
|
"SELECT c.guid FROM acore_characters.characters c JOIN acore_auth.account a ON a.id=c.account WHERE c.online=1 AND UPPER(a.username) LIKE '{prefix}%' ORDER BY RAND() LIMIT {count};"
|
||||||
target.chars_db
|
|
||||||
))?;
|
))?;
|
||||||
let guids: Vec<u64> = rows.lines().filter_map(|l| l.trim().parse().ok()).collect();
|
let guids: Vec<u64> = rows.lines().filter_map(|l| l.trim().parse().ok()).collect();
|
||||||
let mut ra = Ra::connect_target(&root, Some(mode))?;
|
let mut ra = Ra::connect(&root)?;
|
||||||
let mut done = 0;
|
let mut done = 0;
|
||||||
for g in guids {
|
for g in guids {
|
||||||
if ra.despawn_bot(g).unwrap_or(false) {
|
if ra.despawn_bot(g).unwrap_or(false) {
|
||||||
@@ -1901,35 +1966,31 @@ async fn companions_despawn_some(
|
|||||||
.await
|
.await
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Delete every companion for good. A recovery point of the characters and accounts is saved first.
|
||||||
#[tauri::command]
|
#[tauri::command]
|
||||||
async fn companions_delete_all(
|
async fn companions_delete_all(
|
||||||
app: AppHandle,
|
app: AppHandle,
|
||||||
state: State<'_, AppState>,
|
state: State<'_, AppState>,
|
||||||
id: String,
|
id: String,
|
||||||
realm: Option<coa_core::realms::Mode>,
|
|
||||||
) -> std::result::Result<CompanionAction, UiError> {
|
) -> std::result::Result<CompanionAction, UiError> {
|
||||||
let root = path_of(&state, &id)?;
|
let root = path_of(&state, &id)?;
|
||||||
let _guard = BusyGuard::acquire(&state, &id)?;
|
let _guard = BusyGuard::acquire(&state, &id)?;
|
||||||
blocking(move || {
|
blocking(move || {
|
||||||
let mode = realm.unwrap_or_else(|| {
|
|
||||||
coa_core::realms::view(&root).map(|v| v.active).unwrap_or_default()
|
|
||||||
});
|
|
||||||
let target = coa_core::multiworld::resolve_bot_operation_target(&root, mode)?;
|
|
||||||
let meta = meta_dir(&root)?;
|
let meta = meta_dir(&root)?;
|
||||||
backup::create(
|
backup::create(
|
||||||
&root,
|
&root,
|
||||||
&meta,
|
&meta,
|
||||||
Kind::Quick,
|
Kind::Quick,
|
||||||
Trigger::BeforeDangerousChange,
|
Trigger::BeforeDangerousChange,
|
||||||
Some(format!("before deleting all {} companions", target.realm.label())),
|
Some("before deleting all companions".into()),
|
||||||
&|step| {
|
&|step| {
|
||||||
let _ = app.emit("backup-progress", step);
|
let _ = app.emit("backup-progress", step);
|
||||||
},
|
},
|
||||||
)?;
|
)?;
|
||||||
let before = coa_core::population::query_for_realm(&root, mode)
|
let before = coa_core::population::query(&root)
|
||||||
.map(|p| p.bots_total)
|
.map(|p| p.bots_total)
|
||||||
.unwrap_or(0);
|
.unwrap_or(0);
|
||||||
let mut ra = Ra::connect_target(&root, Some(mode))?;
|
let mut ra = Ra::connect(&root)?;
|
||||||
let _ = ra.cancel_spawning();
|
let _ = ra.cancel_spawning();
|
||||||
ra.purge_all()?;
|
ra.purge_all()?;
|
||||||
Ok(CompanionAction { count: before })
|
Ok(CompanionAction { count: before })
|
||||||
@@ -1985,11 +2046,6 @@ async fn add_companions(
|
|||||||
state: State<'_, AppState>,
|
state: State<'_, AppState>,
|
||||||
id: String,
|
id: String,
|
||||||
count: u32,
|
count: u32,
|
||||||
realm: Option<coa_core::realms::Mode>,
|
|
||||||
level: Option<u8>,
|
|
||||||
class_id: Option<u8>,
|
|
||||||
spec_id: Option<u32>,
|
|
||||||
archetype: Option<String>,
|
|
||||||
) -> std::result::Result<CompanionsResult, UiError> {
|
) -> std::result::Result<CompanionsResult, UiError> {
|
||||||
let root = path_of(&state, &id)?;
|
let root = path_of(&state, &id)?;
|
||||||
let _guard = BusyGuard::acquire(&state, &id)?;
|
let _guard = BusyGuard::acquire(&state, &id)?;
|
||||||
@@ -1999,15 +2055,11 @@ async fn add_companions(
|
|||||||
"Choose between 1 and 2000 companions.".into(),
|
"Choose between 1 and 2000 companions.".into(),
|
||||||
));
|
));
|
||||||
}
|
}
|
||||||
let mode = realm.unwrap_or_else(|| {
|
|
||||||
coa_core::realms::view(&root).map(|v| v.active).unwrap_or_default()
|
|
||||||
});
|
|
||||||
let target = coa_core::multiworld::resolve_bot_operation_target(&root, mode)?;
|
|
||||||
let meta = meta_dir(&root)?;
|
let meta = meta_dir(&root)?;
|
||||||
let mut changes = BTreeMap::new();
|
let mut changes = BTreeMap::new();
|
||||||
changes.insert("CoaBots.AutoLoginOnStartup".to_string(), Value::Bool(true));
|
changes.insert("CoaBots.AutoLoginOnStartup".to_string(), Value::Bool(true));
|
||||||
let existing_max = config::load(&target.world_root, Scope::Bots)
|
// Every companion, old and new, should come back at the next start, so the start-up limit only ever grows here.
|
||||||
.or_else(|_| config::load(&root, Scope::Bots))
|
let existing_max = config::load(&root, Scope::Bots)
|
||||||
.ok()
|
.ok()
|
||||||
.and_then(|v| {
|
.and_then(|v| {
|
||||||
v.settings
|
v.settings
|
||||||
@@ -2016,58 +2068,68 @@ async fn add_companions(
|
|||||||
.and_then(|s| s.value.as_u64())
|
.and_then(|s| s.value.as_u64())
|
||||||
})
|
})
|
||||||
.unwrap_or(0) as u32;
|
.unwrap_or(0) as u32;
|
||||||
let already = coa_core::population::query_for_realm(&root, mode)
|
let already = coa_core::population::query(&root)
|
||||||
.map(|p| p.bots_total)
|
.map(|p| p.bots_total)
|
||||||
.unwrap_or(0);
|
.unwrap_or(0);
|
||||||
changes.insert(
|
changes.insert(
|
||||||
"CoaBots.AutoLogin.MaxCount".to_string(),
|
"CoaBots.AutoLogin.MaxCount".to_string(),
|
||||||
Value::from(existing_max.max(already + count).min(5000)),
|
Value::from(existing_max.max(already + count).min(5000)),
|
||||||
);
|
);
|
||||||
let _ = config::save(&target.world_root, &meta, Scope::Bots, &changes)
|
config::save(&root, &meta, Scope::Bots, &changes)?;
|
||||||
.or_else(|_| config::save(&root, &meta, Scope::Bots, &changes));
|
let o = coa_core::process::observe(&root, &layout::read_ports(&root));
|
||||||
|
// Large batches while the server is stopped: create them in the database right now, fully equipped.
|
||||||
let mut baseline = None;
|
if o.world.state == coa_core::process::ServiceState::Stopped
|
||||||
let spawned = if target.running {
|
&& o.auth.state == coa_core::process::ServiceState::Stopped
|
||||||
if let Ok(admin_db) = coa_core::db::Db::from_repack(&root, coa_core::db::Account::Admin) {
|
&& count >= coa_core::companions::OFFLINE_MIN
|
||||||
let _ = coa_core::companions::ensure_templates_for_schema(&admin_db, target.chars_db);
|
&& coa_core::companions::offline_factory(&root).is_some()
|
||||||
|
{
|
||||||
|
let started_db = o.mysql.state != coa_core::process::ServiceState::Running;
|
||||||
|
if started_db {
|
||||||
|
let out = driver::run(&root, Verb::StartMysql)?;
|
||||||
|
if !out.ok {
|
||||||
|
return Err(Error::Invalid("The database could not be started.".into()));
|
||||||
|
}
|
||||||
}
|
}
|
||||||
baseline = coa_core::population::query_for_realm(&root, mode)
|
let made = (|| -> Result<()> {
|
||||||
|
coa_core::companions::ensure_templates(&coa_core::db::Db::from_repack(
|
||||||
|
&root,
|
||||||
|
coa_core::db::Account::Admin,
|
||||||
|
)?)?;
|
||||||
|
coa_core::companions::offline_create(
|
||||||
|
&root,
|
||||||
|
&meta.join("logs").join("companions-offline.log"),
|
||||||
|
count,
|
||||||
|
)?;
|
||||||
|
Ok(())
|
||||||
|
})();
|
||||||
|
if started_db {
|
||||||
|
let _ = driver::run(&root, Verb::StopAll);
|
||||||
|
}
|
||||||
|
made?;
|
||||||
|
tracing::info!(count, "companions created offline");
|
||||||
|
return Ok(CompanionsResult {
|
||||||
|
spawned: None,
|
||||||
|
created: Some(count),
|
||||||
|
baseline: None,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
let mut baseline = None;
|
||||||
|
let spawned = if o.world.state == coa_core::process::ServiceState::Running {
|
||||||
|
// Older servers have no template characters to copy bots from: add them first.
|
||||||
|
coa_core::companions::ensure_templates(&coa_core::db::Db::from_repack(
|
||||||
|
&root,
|
||||||
|
coa_core::db::Account::Admin,
|
||||||
|
)?)?;
|
||||||
|
baseline = coa_core::population::query(&root)
|
||||||
.ok()
|
.ok()
|
||||||
.map(|p| p.bots_total);
|
.map(|p| p.bots_total);
|
||||||
let mut ra = Ra::connect_target(&root, Some(mode))?;
|
Some(Ra::connect(&root)?.spawn_bots(count)?)
|
||||||
if let Some(lvl) = level {
|
|
||||||
Some(ra.spawn_custom(count, lvl, class_id, spec_id, archetype.as_deref())?)
|
|
||||||
} else {
|
|
||||||
Some(ra.spawn_bots(count)?)
|
|
||||||
}
|
|
||||||
} else {
|
} else {
|
||||||
let job = coa_core::companions::CompanionsPendingJob {
|
// The server is stopped: creating bots needs it running, so remember the request and do it after the next start.
|
||||||
job_id: uuid::Uuid::new_v4().to_string(),
|
coa_core::fsx::atomic_write_json(
|
||||||
server_instance_id: id.clone(),
|
&meta.join("companions.pending.json"),
|
||||||
realm: mode.name().to_string(),
|
&serde_json::json!({ "count": count }),
|
||||||
count,
|
)?;
|
||||||
level,
|
|
||||||
class_id,
|
|
||||||
spec_id,
|
|
||||||
build_id: archetype.clone(),
|
|
||||||
requested_operation: "spawn".to_string(),
|
|
||||||
created_at: std::time::SystemTime::now()
|
|
||||||
.duration_since(std::time::UNIX_EPOCH)
|
|
||||||
.unwrap_or_default()
|
|
||||||
.as_secs(),
|
|
||||||
state: "pending".to_string(),
|
|
||||||
completed_count: 0,
|
|
||||||
failed_count: 0,
|
|
||||||
last_error: None,
|
|
||||||
schema_version: 1,
|
|
||||||
};
|
|
||||||
coa_core::companions::save_pending_job(&meta, mode.name(), &job)?;
|
|
||||||
if mode == coa_core::realms::Mode::Coa {
|
|
||||||
let _ = coa_core::fsx::atomic_write_json(
|
|
||||||
&meta.join("companions.pending.json"),
|
|
||||||
&serde_json::json!({ "count": count }),
|
|
||||||
);
|
|
||||||
}
|
|
||||||
None
|
None
|
||||||
};
|
};
|
||||||
tracing::info!(count, spawned = spawned.is_some(), "companions requested");
|
tracing::info!(count, spawned = spawned.is_some(), "companions requested");
|
||||||
@@ -2080,27 +2142,6 @@ async fn add_companions(
|
|||||||
.await
|
.await
|
||||||
}
|
}
|
||||||
|
|
||||||
#[tauri::command]
|
|
||||||
async fn get_wildcard_archetypes(
|
|
||||||
state: State<'_, AppState>,
|
|
||||||
id: String,
|
|
||||||
) -> std::result::Result<Vec<coa_core::companions::WildcardArchetypeDto>, UiError> {
|
|
||||||
let root = path_of(&state, &id)?;
|
|
||||||
blocking(move || {
|
|
||||||
let db = coa_core::db::Db::from_repack(&root, coa_core::db::Account::Admin)?;
|
|
||||||
let target = coa_core::multiworld::resolve_bot_operation_target(&root, coa_core::realms::Mode::Wildcard)
|
|
||||||
.unwrap_or_else(|_| coa_core::multiworld::BotOperationTarget {
|
|
||||||
world_root: root.clone(),
|
|
||||||
chars_db: "acore_characters_wildcard",
|
|
||||||
ra_port: 3444,
|
|
||||||
running: false,
|
|
||||||
realm: coa_core::realms::Mode::Wildcard,
|
|
||||||
});
|
|
||||||
Ok(coa_core::companions::list_wildcard_archetypes(&db, target.chars_db)?)
|
|
||||||
})
|
|
||||||
.await
|
|
||||||
}
|
|
||||||
|
|
||||||
const REMOTE_CLIENT_ID: &str = "@remote-client";
|
const REMOTE_CLIENT_ID: &str = "@remote-client";
|
||||||
|
|
||||||
fn remote_dir() -> PathBuf {
|
fn remote_dir() -> PathBuf {
|
||||||
@@ -3042,6 +3083,50 @@ async fn analyze_github_module(
|
|||||||
.await
|
.await
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Last push of GitHub repositories (`owner/name`), for modules that are not in the public catalogue (CoA's
|
||||||
|
/// own). Answers are kept for 12 hours in the source cache; a repository GitHub does not answer for gets none.
|
||||||
|
#[tauri::command]
|
||||||
|
async fn repo_last_push(repos: Vec<String>) -> std::result::Result<BTreeMap<String, Option<String>>, UiError> {
|
||||||
|
let cache_file = data_dir().join("github_cache").join("repo-last-push.json");
|
||||||
|
blocking(move || coa_core::catalogue::repo_last_push(&cache_file, &repos)).await
|
||||||
|
}
|
||||||
|
|
||||||
|
/// What the module build cache of a server (and the shared source downloads) take on disk.
|
||||||
|
#[tauri::command]
|
||||||
|
async fn build_cache_summary(
|
||||||
|
state: State<'_, AppState>,
|
||||||
|
id: String,
|
||||||
|
) -> std::result::Result<coa_core::build_cache::CacheSummary, UiError> {
|
||||||
|
let root = path_of(&state, &id)?;
|
||||||
|
let sources = data_dir().join("github_cache");
|
||||||
|
blocking(move || Ok(coa_core::build_cache::summary(&root, Some(&sources)))).await
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Remove the build cache of one module (`module`), of all modules (no `module`), and optionally the downloaded
|
||||||
|
/// sources. Refused while a build runs on this server. Returns the bytes freed.
|
||||||
|
#[tauri::command]
|
||||||
|
async fn build_cache_clear(
|
||||||
|
state: State<'_, AppState>,
|
||||||
|
id: String,
|
||||||
|
module: Option<String>,
|
||||||
|
sources: bool,
|
||||||
|
) -> std::result::Result<u64, UiError> {
|
||||||
|
let root = path_of(&state, &id)?;
|
||||||
|
let _guard = BusyGuard::acquire(&state, &id)?;
|
||||||
|
let sources_dir = data_dir().join("github_cache");
|
||||||
|
blocking(move || {
|
||||||
|
let mut freed = 0;
|
||||||
|
if module.is_some() || !sources {
|
||||||
|
freed += coa_core::build_cache::clear(&root, module.as_deref())?;
|
||||||
|
}
|
||||||
|
if sources {
|
||||||
|
freed += coa_core::build_cache::clear_sources(&sources_dir)?;
|
||||||
|
}
|
||||||
|
Ok(freed)
|
||||||
|
})
|
||||||
|
.await
|
||||||
|
}
|
||||||
|
|
||||||
#[tauri::command]
|
#[tauri::command]
|
||||||
async fn get_public_module_catalog(
|
async fn get_public_module_catalog(
|
||||||
force_refresh: Option<bool>,
|
force_refresh: Option<bool>,
|
||||||
@@ -3074,27 +3159,6 @@ async fn preview_install_msvc(
|
|||||||
blocking(move || coa_core::msvc_setup::install_build_tools(realm_root.as_deref())).await
|
blocking(move || coa_core::msvc_setup::install_build_tools(realm_root.as_deref())).await
|
||||||
}
|
}
|
||||||
|
|
||||||
#[tauri::command]
|
|
||||||
async fn preview_register_test_realm(
|
|
||||||
state: State<'_, AppState>,
|
|
||||||
path: Option<String>,
|
|
||||||
) -> std::result::Result<ServerSummary, UiError> {
|
|
||||||
let target = path
|
|
||||||
.map(PathBuf::from)
|
|
||||||
.unwrap_or_else(|| PathBuf::from(r"C:\games\coa-work\plugin-spike\server-v03"));
|
|
||||||
|
|
||||||
if !target.join("worldserver.exe").is_file() && !target.join("Core/worldserver.exe").is_file() {
|
|
||||||
return Err(UiError::from(coa_core::Error::Invalid(format!(
|
|
||||||
"Target path '{}' does not contain a valid worldserver.exe",
|
|
||||||
target.display()
|
|
||||||
))));
|
|
||||||
}
|
|
||||||
|
|
||||||
let id = "test-realm-v03".to_string();
|
|
||||||
state.registry.register(&id, &target)?;
|
|
||||||
Ok(summary(id, target))
|
|
||||||
}
|
|
||||||
|
|
||||||
#[tauri::command]
|
#[tauri::command]
|
||||||
async fn preview_build_module(
|
async fn preview_build_module(
|
||||||
app: AppHandle,
|
app: AppHandle,
|
||||||
@@ -3111,6 +3175,8 @@ async fn preview_build_module(
|
|||||||
|
|
||||||
let realm_root = path_of(&state, &realm_id)?;
|
let realm_root = path_of(&state, &realm_id)?;
|
||||||
let cache_dir = data_dir().join("github_cache");
|
let cache_dir = data_dir().join("github_cache");
|
||||||
|
// The build works in the module's build cache: clearing the cache waits for it.
|
||||||
|
let _guard = BusyGuard::acquire(&state, &realm_id)?;
|
||||||
|
|
||||||
let app_clone = app.clone();
|
let app_clone = app.clone();
|
||||||
let progress_cb: Box<dyn Fn(coa_core::build_engine::BuildProgressEvent) + Send + Sync> =
|
let progress_cb: Box<dyn Fn(coa_core::build_engine::BuildProgressEvent) + Send + Sync> =
|
||||||
@@ -3308,42 +3374,8 @@ async fn preview_export_diagnostics(
|
|||||||
}
|
}
|
||||||
|
|
||||||
#[tauri::command]
|
#[tauri::command]
|
||||||
async fn preview_migration_inspect(
|
async fn modular_copy_preview(path: String) -> std::result::Result<coa_core::modular_copy::CopyPreview, UiError> {
|
||||||
source_path: String,
|
blocking(move || coa_core::modular_copy::preview(Path::new(&path)).map_err(Into::into)).await
|
||||||
) -> std::result::Result<coa_core::server_migration::SourceInspectionReport, UiError> {
|
|
||||||
blocking(move || {
|
|
||||||
let p = std::path::PathBuf::from(source_path);
|
|
||||||
coa_core::server_migration::inspect_source(&p).map_err(Into::into)
|
|
||||||
})
|
|
||||||
.await
|
|
||||||
}
|
|
||||||
|
|
||||||
#[tauri::command]
|
|
||||||
async fn preview_migration_plan(
|
|
||||||
state: State<'_, AppState>,
|
|
||||||
source_path: String,
|
|
||||||
dest_realm_id: String,
|
|
||||||
scope: coa_core::server_migration::MigrationScope,
|
|
||||||
conflict_policy: coa_core::server_migration::ConflictResolutionPolicy,
|
|
||||||
) -> std::result::Result<coa_core::server_migration::MigrationPlan, UiError> {
|
|
||||||
let dest_root = path_of(&state, &dest_realm_id)?;
|
|
||||||
blocking(move || {
|
|
||||||
let src_p = std::path::PathBuf::from(source_path);
|
|
||||||
let report = coa_core::server_migration::inspect_source(&src_p)?;
|
|
||||||
coa_core::server_migration::plan_migration(&report, &dest_root, scope, conflict_policy)
|
|
||||||
.map_err(Into::into)
|
|
||||||
})
|
|
||||||
.await
|
|
||||||
}
|
|
||||||
|
|
||||||
#[tauri::command]
|
|
||||||
async fn preview_migration_execute(
|
|
||||||
plan: coa_core::server_migration::MigrationPlan,
|
|
||||||
) -> std::result::Result<coa_core::server_migration::MigrationExecutionReport, UiError> {
|
|
||||||
blocking(move || {
|
|
||||||
coa_core::server_migration::execute_migration(&plan).map_err(Into::into)
|
|
||||||
})
|
|
||||||
.await
|
|
||||||
}
|
}
|
||||||
|
|
||||||
#[tauri::command]
|
#[tauri::command]
|
||||||
@@ -3489,21 +3521,28 @@ pub fn run() {
|
|||||||
.plugin(tauri_plugin_dialog::init())
|
.plugin(tauri_plugin_dialog::init())
|
||||||
.plugin(tauri_plugin_updater::Builder::new().build())
|
.plugin(tauri_plugin_updater::Builder::new().build())
|
||||||
.plugin(tauri_plugin_process::init())
|
.plugin(tauri_plugin_process::init())
|
||||||
|
// Size, position and maximized state come back after a restart. Visibility is left to the app (tray, start
|
||||||
|
// options), so a window last hidden in the tray still opens normally.
|
||||||
|
.plugin(
|
||||||
|
tauri_plugin_window_state::Builder::default()
|
||||||
|
.with_state_flags(
|
||||||
|
tauri_plugin_window_state::StateFlags::all()
|
||||||
|
- tauri_plugin_window_state::StateFlags::VISIBLE,
|
||||||
|
)
|
||||||
|
.build(),
|
||||||
|
)
|
||||||
.invoke_handler(tauri::generate_handler![
|
.invoke_handler(tauri::generate_handler![
|
||||||
server_logging_preset,
|
server_logging_preset,
|
||||||
release_history,
|
release_history,
|
||||||
preview_toolchain_status,
|
preview_toolchain_status,
|
||||||
preview_install_msvc,
|
preview_install_msvc,
|
||||||
preview_register_test_realm,
|
|
||||||
preview_build_module,
|
preview_build_module,
|
||||||
preview_install_module,
|
preview_install_module,
|
||||||
preview_toggle_module,
|
preview_toggle_module,
|
||||||
preview_remove_module,
|
preview_remove_module,
|
||||||
preview_list_installed_plugins,
|
preview_list_installed_plugins,
|
||||||
preview_export_diagnostics,
|
preview_export_diagnostics,
|
||||||
preview_migration_inspect,
|
modular_copy_preview,
|
||||||
preview_migration_plan,
|
|
||||||
preview_migration_execute,
|
|
||||||
preview_check_updates,
|
preview_check_updates,
|
||||||
default_install_dir,
|
default_install_dir,
|
||||||
game_data_folder,
|
game_data_folder,
|
||||||
@@ -3564,6 +3603,10 @@ pub fn run() {
|
|||||||
account_rename,
|
account_rename,
|
||||||
account_delete,
|
account_delete,
|
||||||
install_new,
|
install_new,
|
||||||
|
is_classic_server,
|
||||||
|
build_cache_summary,
|
||||||
|
build_cache_clear,
|
||||||
|
repo_last_push,
|
||||||
cancel_install,
|
cancel_install,
|
||||||
create_account,
|
create_account,
|
||||||
check_update,
|
check_update,
|
||||||
@@ -3577,13 +3620,10 @@ pub fn run() {
|
|||||||
companions_take_offline,
|
companions_take_offline,
|
||||||
companions_delete_all,
|
companions_delete_all,
|
||||||
companions_despawn_some,
|
companions_despawn_some,
|
||||||
companions_login_all,
|
|
||||||
companions_spawn_fleet,
|
|
||||||
open_link,
|
open_link,
|
||||||
report_targets,
|
report_targets,
|
||||||
companion_sizes,
|
companion_sizes,
|
||||||
add_companions,
|
add_companions,
|
||||||
get_wildcard_archetypes,
|
|
||||||
remote_connection,
|
remote_connection,
|
||||||
remote_connect,
|
remote_connect,
|
||||||
client_info,
|
client_info,
|
||||||
@@ -3675,22 +3715,12 @@ pub fn run() {
|
|||||||
let portable = start_portable(&dir);
|
let portable = start_portable(&dir);
|
||||||
let (control, host_control) = control_cmds::start(&dir, portable.clone());
|
let (control, host_control) = control_cmds::start(&dir, portable.clone());
|
||||||
let registry = Registry::at(dir.join("installs.json"));
|
let registry = Registry::at(dir.join("installs.json"));
|
||||||
|
// Development only: an explicitly named test realm is registered into an empty list.
|
||||||
if registry.list().map(|l| l.is_empty()).unwrap_or(true) {
|
if registry.list().map(|l| l.is_empty()).unwrap_or(true) {
|
||||||
let test_realm_path = std::env::var("COA_TEST_REALM_DIR")
|
if let Ok(path) = std::env::var("COA_TEST_REALM_DIR").map(PathBuf::from) {
|
||||||
.map(PathBuf::from)
|
if path.join("worldserver.exe").is_file() {
|
||||||
.unwrap_or_else(|_| PathBuf::from(r"C:\games\CoA Server Preview"));
|
let _ = registry.register("preview-realm", &path);
|
||||||
let target_realm = if test_realm_path.join("worldserver.exe").is_file() {
|
|
||||||
Some(("preview-realm", test_realm_path))
|
|
||||||
} else {
|
|
||||||
let spike_path = PathBuf::from(r"C:\games\coa-work\plugin-spike\server-v03");
|
|
||||||
if spike_path.join("worldserver.exe").is_file() {
|
|
||||||
Some(("test-realm-v03", spike_path))
|
|
||||||
} else {
|
|
||||||
None
|
|
||||||
}
|
}
|
||||||
};
|
|
||||||
if let Some((name, path)) = target_realm {
|
|
||||||
let _ = registry.register(name, &path);
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
app.manage(AppState {
|
app.manage(AppState {
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
{
|
{
|
||||||
"$schema": "https://schema.tauri.app/config/2",
|
"$schema": "https://schema.tauri.app/config/2",
|
||||||
"productName": "CSM Modules Preview",
|
"productName": "CSM Modules Preview",
|
||||||
"version": "0.9.9",
|
"version": "0.9.11",
|
||||||
"identifier": "com.corfirean.csm-modules-preview",
|
"identifier": "com.corfirean.csm-modules-preview",
|
||||||
"build": {
|
"build": {
|
||||||
"beforeBuildCommand": "npm run build",
|
"beforeBuildCommand": "npm run build",
|
||||||
|
|||||||
+20
-1
@@ -19,6 +19,10 @@ function Main() {
|
|||||||
const [servers, setServers] = useState<ServerSummary[] | null>(null);
|
const [servers, setServers] = useState<ServerSummary[] | null>(null);
|
||||||
const [view, setView] = useState<View>(initialView);
|
const [view, setView] = useState<View>(initialView);
|
||||||
const [activeId, setActiveId] = useState<string | null>(null);
|
const [activeId, setActiveId] = useState<string | null>(null);
|
||||||
|
// A classic server the owner chose: the install screen makes a modular copy of it next to it.
|
||||||
|
const [copyFrom, setCopyFrom] = useState<string | null>(null);
|
||||||
|
// Where Cancel on that install screen goes back to: the import screen or the server's own pages.
|
||||||
|
const [copyBack, setCopyBack] = useState<View>("import");
|
||||||
|
|
||||||
const refresh = useCallback(async () => {
|
const refresh = useCallback(async () => {
|
||||||
const list = await api.list().catch(() => []);
|
const list = await api.list().catch(() => []);
|
||||||
@@ -44,6 +48,11 @@ function Main() {
|
|||||||
activeId={activeId}
|
activeId={activeId}
|
||||||
onSelect={setActiveId}
|
onSelect={setActiveId}
|
||||||
onAddAnother={() => setView("add")}
|
onAddAnother={() => setView("add")}
|
||||||
|
onCopy={(path) => {
|
||||||
|
setCopyFrom(path);
|
||||||
|
setCopyBack("welcome");
|
||||||
|
setView("install");
|
||||||
|
}}
|
||||||
onForget={async (id) => {
|
onForget={async (id) => {
|
||||||
await api.forget(id);
|
await api.forget(id);
|
||||||
await refresh();
|
await refresh();
|
||||||
@@ -56,8 +65,13 @@ function Main() {
|
|||||||
return (
|
return (
|
||||||
<InstallServer
|
<InstallServer
|
||||||
canCancel
|
canCancel
|
||||||
onCancel={() => setView(servers.length > 0 ? "add" : "welcome")}
|
copyFrom={copyFrom ?? undefined}
|
||||||
|
onCancel={() => {
|
||||||
|
setView(copyFrom ? copyBack : servers.length > 0 ? "add" : "welcome");
|
||||||
|
setCopyFrom(null);
|
||||||
|
}}
|
||||||
onDone={async (s) => {
|
onDone={async (s) => {
|
||||||
|
setCopyFrom(null);
|
||||||
await refresh();
|
await refresh();
|
||||||
setActiveId(s.id);
|
setActiveId(s.id);
|
||||||
setView("welcome");
|
setView("welcome");
|
||||||
@@ -76,6 +90,11 @@ function Main() {
|
|||||||
setActiveId(s.id);
|
setActiveId(s.id);
|
||||||
setView("welcome");
|
setView("welcome");
|
||||||
}}
|
}}
|
||||||
|
onCopy={(path) => {
|
||||||
|
setCopyFrom(path);
|
||||||
|
setCopyBack("import");
|
||||||
|
setView("install");
|
||||||
|
}}
|
||||||
/>
|
/>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -36,3 +36,7 @@ Manager 0.9.8 preparation refreshes the bundled server history through 0.261030.
|
|||||||
The two reviewed upcoming records are in `tools/reviewed-manager-notes.json` and
|
The two reviewed upcoming records are in `tools/reviewed-manager-notes.json` and
|
||||||
`tools/reviewed-server-notes.json`; every new note has all five translations.
|
`tools/reviewed-server-notes.json`; every new note has all five translations.
|
||||||
These files describe preparation and do not add unpublished releases to canonical history.
|
These files describe preparation and do not add unpublished releases to canonical history.
|
||||||
|
|
||||||
|
Manager 0.9.10 refreshes the bundled server history through 0.261104.94 from
|
||||||
|
canonical build commit `a9c6b17c8c1a295680fda4ad4bcdde266357264d` on 2026-11-08.
|
||||||
|
The reviewed upcoming Manager and server records carry translations in all five languages.
|
||||||
@@ -37,7 +37,8 @@
|
|||||||
"Update validation keeps MySQL running between compatible checks": "При проверке обновления MySQL продолжает работать между совместимыми проверками",
|
"Update validation keeps MySQL running between compatible checks": "При проверке обновления MySQL продолжает работать между совместимыми проверками",
|
||||||
"Choose normal logs, errors only or no server logs in maintenance settings": "Выбирайте обычные логи, только ошибки или отключение логов в настройках обслуживания",
|
"Choose normal logs, errors only or no server logs in maintenance settings": "Выбирайте обычные логи, только ошибки или отключение логов в настройках обслуживания",
|
||||||
"Diagnostic exports include launcher stages and lock owner records": "В архив диагностики входят этапы лаунчера и записи о владельцах блокировок",
|
"Diagnostic exports include launcher stages and lock owner records": "В архив диагностики входят этапы лаунчера и записи о владельцах блокировок",
|
||||||
"Update and recovery checks use the temporary login port even with a Windows override": "Проверка обновления и восстановления использует временный порт входа даже при переопределении в Windows"
|
"Update and recovery checks use the temporary login port even with a Windows override": "Проверка обновления и восстановления использует временный порт входа даже при переопределении в Windows",
|
||||||
|
"Custom Races patch installation recovers from interrupted downloads": "Установка патчей дополнительных рас восстанавливается после прерывания загрузки"
|
||||||
},
|
},
|
||||||
"de": {
|
"de": {
|
||||||
"Choose Parallel or Global level scaling in module settings": "Parallele oder globale Levelskalierung in den Moduleinstellungen wählen",
|
"Choose Parallel or Global level scaling in module settings": "Parallele oder globale Levelskalierung in den Moduleinstellungen wählen",
|
||||||
@@ -76,7 +77,8 @@
|
|||||||
"Update validation keeps MySQL running between compatible checks": "Bei der Update-Validierung bleibt MySQL zwischen kompatiblen Prüfungen aktiv",
|
"Update validation keeps MySQL running between compatible checks": "Bei der Update-Validierung bleibt MySQL zwischen kompatiblen Prüfungen aktiv",
|
||||||
"Choose normal logs, errors only or no server logs in maintenance settings": "In den Wartungseinstellungen normale Protokolle, nur Fehler oder keine Serverprotokolle wählen",
|
"Choose normal logs, errors only or no server logs in maintenance settings": "In den Wartungseinstellungen normale Protokolle, nur Fehler oder keine Serverprotokolle wählen",
|
||||||
"Diagnostic exports include launcher stages and lock owner records": "Diagnoseexporte enthalten Launcher-Schritte und aufgezeichnete Sperrbesitzer",
|
"Diagnostic exports include launcher stages and lock owner records": "Diagnoseexporte enthalten Launcher-Schritte und aufgezeichnete Sperrbesitzer",
|
||||||
"Update and recovery checks use the temporary login port even with a Windows override": "Update- und Wiederherstellungsprüfungen verwenden den temporären Anmeldeport auch bei einer Windows-Vorgabe"
|
"Update and recovery checks use the temporary login port even with a Windows override": "Update- und Wiederherstellungsprüfungen verwenden den temporären Anmeldeport auch bei einer Windows-Vorgabe",
|
||||||
|
"Custom Races patch installation recovers from interrupted downloads": "Die Installation zusätzlicher Völker setzt unterbrochene Downloads fort"
|
||||||
},
|
},
|
||||||
"fr": {
|
"fr": {
|
||||||
"Choose Parallel or Global level scaling in module settings": "Choisissez une progression parallèle ou globale des niveaux dans les paramètres du module",
|
"Choose Parallel or Global level scaling in module settings": "Choisissez une progression parallèle ou globale des niveaux dans les paramètres du module",
|
||||||
@@ -115,7 +117,8 @@
|
|||||||
"Update validation keeps MySQL running between compatible checks": "La validation des mises à jour garde MySQL actif entre les vérifications compatibles",
|
"Update validation keeps MySQL running between compatible checks": "La validation des mises à jour garde MySQL actif entre les vérifications compatibles",
|
||||||
"Choose normal logs, errors only or no server logs in maintenance settings": "Choisissez les journaux normaux, les erreurs uniquement ou aucun journal dans les paramètres de maintenance",
|
"Choose normal logs, errors only or no server logs in maintenance settings": "Choisissez les journaux normaux, les erreurs uniquement ou aucun journal dans les paramètres de maintenance",
|
||||||
"Diagnostic exports include launcher stages and lock owner records": "Les exports de diagnostic incluent les étapes de lancement et les propriétaires des verrous",
|
"Diagnostic exports include launcher stages and lock owner records": "Les exports de diagnostic incluent les étapes de lancement et les propriétaires des verrous",
|
||||||
"Update and recovery checks use the temporary login port even with a Windows override": "Les contrôles de mise à jour et de restauration utilisent le port de connexion temporaire même si Windows en impose un autre"
|
"Update and recovery checks use the temporary login port even with a Windows override": "Les contrôles de mise à jour et de restauration utilisent le port de connexion temporaire même si Windows en impose un autre",
|
||||||
|
"Custom Races patch installation recovers from interrupted downloads": "L’installation des races supplémentaires reprend les téléchargements interrompus"
|
||||||
},
|
},
|
||||||
"es": {
|
"es": {
|
||||||
"Choose Parallel or Global level scaling in module settings": "Elige escalado de nivel paralelo o global en los ajustes del módulo",
|
"Choose Parallel or Global level scaling in module settings": "Elige escalado de nivel paralelo o global en los ajustes del módulo",
|
||||||
@@ -154,7 +157,8 @@
|
|||||||
"Update validation keeps MySQL running between compatible checks": "La validación de actualizaciones mantiene MySQL activo entre comprobaciones compatibles",
|
"Update validation keeps MySQL running between compatible checks": "La validación de actualizaciones mantiene MySQL activo entre comprobaciones compatibles",
|
||||||
"Choose normal logs, errors only or no server logs in maintenance settings": "Elige registros normales, solo errores o ningún registro en los ajustes de mantenimiento",
|
"Choose normal logs, errors only or no server logs in maintenance settings": "Elige registros normales, solo errores o ningún registro en los ajustes de mantenimiento",
|
||||||
"Diagnostic exports include launcher stages and lock owner records": "Los archivos de diagnóstico incluyen las etapas del lanzador y los propietarios de bloqueos",
|
"Diagnostic exports include launcher stages and lock owner records": "Los archivos de diagnóstico incluyen las etapas del lanzador y los propietarios de bloqueos",
|
||||||
"Update and recovery checks use the temporary login port even with a Windows override": "Las comprobaciones de actualización y recuperación usan el puerto temporal de acceso aunque Windows indique otro"
|
"Update and recovery checks use the temporary login port even with a Windows override": "Las comprobaciones de actualización y recuperación usan el puerto temporal de acceso aunque Windows indique otro",
|
||||||
|
"Custom Races patch installation recovers from interrupted downloads": "La instalación de razas adicionales se recupera de descargas interrumpidas"
|
||||||
},
|
},
|
||||||
"zh": {
|
"zh": {
|
||||||
"Choose Parallel or Global level scaling in module settings": "在模块设置中选择并行或全局等级缩放",
|
"Choose Parallel or Global level scaling in module settings": "在模块设置中选择并行或全局等级缩放",
|
||||||
@@ -193,7 +197,8 @@
|
|||||||
"Update validation keeps MySQL running between compatible checks": "更新验证会在兼容的检查步骤之间保持 MySQL 运行",
|
"Update validation keeps MySQL running between compatible checks": "更新验证会在兼容的检查步骤之间保持 MySQL 运行",
|
||||||
"Choose normal logs, errors only or no server logs in maintenance settings": "在维护设置中选择普通日志、仅错误或关闭服务器日志",
|
"Choose normal logs, errors only or no server logs in maintenance settings": "在维护设置中选择普通日志、仅错误或关闭服务器日志",
|
||||||
"Diagnostic exports include launcher stages and lock owner records": "诊断导出包含启动器阶段和锁所属进程记录",
|
"Diagnostic exports include launcher stages and lock owner records": "诊断导出包含启动器阶段和锁所属进程记录",
|
||||||
"Update and recovery checks use the temporary login port even with a Windows override": "即使 Windows 指定了其他端口,更新和恢复检查也会使用临时登录端口"
|
"Update and recovery checks use the temporary login port even with a Windows override": "即使 Windows 指定了其他端口,更新和恢复检查也会使用临时登录端口",
|
||||||
|
"Custom Races patch installation recovers from interrupted downloads": "自定义种族补丁安装可从中断的下载中恢复"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"server": {
|
"server": {
|
||||||
@@ -244,7 +249,17 @@
|
|||||||
"Startup and shutdown keep bounded diagnostics of launcher stages": "При запуске и остановке сохраняется ограниченная по объёму диагностика этапов лаунчера",
|
"Startup and shutdown keep bounded diagnostics of launcher stages": "При запуске и остановке сохраняется ограниченная по объёму диагностика этапов лаунчера",
|
||||||
"Database shutdown succeeds when MySQL closes its connection before replying": "Остановка базы завершается успешно, если MySQL закрыл соединение до отправки ответа",
|
"Database shutdown succeeds when MySQL closes its connection before replying": "Остановка базы завершается успешно, если MySQL закрыл соединение до отправки ответа",
|
||||||
"Server startup waits for ports that Windows is still releasing": "При запуске сервер ждёт, пока Windows освободит порт",
|
"Server startup waits for ports that Windows is still releasing": "При запуске сервер ждёт, пока Windows освободит порт",
|
||||||
"Companions avoid repeating unreachable routes in the open world": "В открытом мире спутники перестают повторять непроходимые маршруты"
|
"Companions avoid repeating unreachable routes in the open world": "В открытом мире спутники перестают повторять непроходимые маршруты",
|
||||||
|
"Login server startup works when Windows does not list its listening port": "Сервер входа запускается, даже если Windows не показывает его прослушиваемый порт",
|
||||||
|
"Updated SQUID's Playerbots to 2.9.4 and refreshed Dungeon Clear": "Обновлены SQUID’s Playerbots до 2.9.4 и Dungeon Clear",
|
||||||
|
"Electrocutioner is used up by Electrocute and no longer makes it look ready too early": "Electrocute расходует Electrocutioner и больше не выглядит готовым раньше времени",
|
||||||
|
"The Dungeon Finder boss objective survives a relog": "Цель убийства босса в поиске подземелий сохраняется после повторного входа",
|
||||||
|
"Vanilla dungeon bosses no longer sleep or mind control tanks and healers": "Боссы классических подземелий больше не усыпляют и не подчиняют танков и лекарей",
|
||||||
|
"Classic dungeons scale only for Dungeon Finder groups": "Классические подземелья масштабируются только для групп поиска подземелий",
|
||||||
|
"Darkmaster Gandling raises Risen Students only at 52% health": "Тёмный магистр Гандлинг поднимает восставших студентов только при 52% здоровья",
|
||||||
|
"Sunken Temple's dragons appear only after the Avatar of Hakkar and Jammal'an": "Драконы Затонувшего храма появляются только после Аватары Хаккара и Джаммал’ана",
|
||||||
|
"Scaled loot previews survive a map change": "Предпросмотр масштабированной добычи сохраняется при смене карты",
|
||||||
|
"Updated SQUID Playerbots to 2.9.4": "SQUID Playerbots обновлён до 2.9.4"
|
||||||
},
|
},
|
||||||
"de": {
|
"de": {
|
||||||
"Restrict new characters by custom race without changing existing characters": "Neue Charaktere nach zusätzlichem Volk beschränken, ohne bestehende Charaktere zu ändern",
|
"Restrict new characters by custom race without changing existing characters": "Neue Charaktere nach zusätzlichem Volk beschränken, ohne bestehende Charaktere zu ändern",
|
||||||
@@ -293,7 +308,17 @@
|
|||||||
"Startup and shutdown keep bounded diagnostics of launcher stages": "Start und Herunterfahren speichern begrenzte Diagnosedaten der Launcher-Schritte",
|
"Startup and shutdown keep bounded diagnostics of launcher stages": "Start und Herunterfahren speichern begrenzte Diagnosedaten der Launcher-Schritte",
|
||||||
"Database shutdown succeeds when MySQL closes its connection before replying": "Das Herunterfahren der Datenbank gelingt auch, wenn MySQL die Verbindung vor der Antwort schließt",
|
"Database shutdown succeeds when MySQL closes its connection before replying": "Das Herunterfahren der Datenbank gelingt auch, wenn MySQL die Verbindung vor der Antwort schließt",
|
||||||
"Server startup waits for ports that Windows is still releasing": "Beim Start wartet der Server, bis Windows den Port freigibt",
|
"Server startup waits for ports that Windows is still releasing": "Beim Start wartet der Server, bis Windows den Port freigibt",
|
||||||
"Companions avoid repeating unreachable routes in the open world": "Gefährten meiden in der offenen Welt wiederholte Versuche auf unpassierbaren Routen"
|
"Companions avoid repeating unreachable routes in the open world": "Gefährten meiden in der offenen Welt wiederholte Versuche auf unpassierbaren Routen",
|
||||||
|
"Login server startup works when Windows does not list its listening port": "Der Anmeldeserver startet auch ohne Eintrag seines lauschenden Ports in Windows",
|
||||||
|
"Updated SQUID's Playerbots to 2.9.4 and refreshed Dungeon Clear": "SQUID’s Playerbots auf 2.9.4 aktualisiert und Dungeon Clear erneuert",
|
||||||
|
"Electrocutioner is used up by Electrocute and no longer makes it look ready too early": "Electrocute verbraucht Electrocutioner und erscheint nicht mehr vorzeitig einsatzbereit",
|
||||||
|
"The Dungeon Finder boss objective survives a relog": "Das Bossziel der Dungeonsuche bleibt nach erneutem Einloggen erhalten",
|
||||||
|
"Vanilla dungeon bosses no longer sleep or mind control tanks and healers": "Bosse klassischer Dungeons versetzen Tanks und Heiler nicht mehr in Schlaf oder Gedankenkontrolle",
|
||||||
|
"Classic dungeons scale only for Dungeon Finder groups": "Klassische Dungeons skalieren nur für Gruppen der Dungeonsuche",
|
||||||
|
"Darkmaster Gandling raises Risen Students only at 52% health": "Dunkelmeister Gandling erweckt auferstandene Studenten erst bei 52 % Gesundheit",
|
||||||
|
"Sunken Temple's dragons appear only after the Avatar of Hakkar and Jammal'an": "Die Drachen im Versunkenen Tempel erscheinen erst nach dem Avatar von Hakkar und Jammal’an",
|
||||||
|
"Scaled loot previews survive a map change": "Die Vorschau skalierter Beute bleibt beim Kartenwechsel erhalten",
|
||||||
|
"Updated SQUID Playerbots to 2.9.4": "SQUID Playerbots auf 2.9.4 aktualisiert"
|
||||||
},
|
},
|
||||||
"fr": {
|
"fr": {
|
||||||
"Restrict new characters by custom race without changing existing characters": "Restreignez les races supplémentaires des nouveaux personnages sans modifier les personnages existants",
|
"Restrict new characters by custom race without changing existing characters": "Restreignez les races supplémentaires des nouveaux personnages sans modifier les personnages existants",
|
||||||
@@ -342,7 +367,17 @@
|
|||||||
"Startup and shutdown keep bounded diagnostics of launcher stages": "Le démarrage et l’arrêt conservent un diagnostic limité des étapes de lancement",
|
"Startup and shutdown keep bounded diagnostics of launcher stages": "Le démarrage et l’arrêt conservent un diagnostic limité des étapes de lancement",
|
||||||
"Database shutdown succeeds when MySQL closes its connection before replying": "L’arrêt de la base réussit même si MySQL ferme la connexion avant de répondre",
|
"Database shutdown succeeds when MySQL closes its connection before replying": "L’arrêt de la base réussit même si MySQL ferme la connexion avant de répondre",
|
||||||
"Server startup waits for ports that Windows is still releasing": "Au démarrage, le serveur attend que Windows libère le port",
|
"Server startup waits for ports that Windows is still releasing": "Au démarrage, le serveur attend que Windows libère le port",
|
||||||
"Companions avoid repeating unreachable routes in the open world": "Les compagnons évitent de reprendre les chemins impraticables en monde ouvert"
|
"Companions avoid repeating unreachable routes in the open world": "Les compagnons évitent de reprendre les chemins impraticables en monde ouvert",
|
||||||
|
"Login server startup works when Windows does not list its listening port": "Le serveur de connexion démarre même si Windows ne répertorie pas son port d’écoute",
|
||||||
|
"Updated SQUID's Playerbots to 2.9.4 and refreshed Dungeon Clear": "SQUID’s Playerbots passe en version 2.9.4 et Dungeon Clear est actualisé",
|
||||||
|
"Electrocutioner is used up by Electrocute and no longer makes it look ready too early": "Electrocute consomme Electrocutioner et ne paraît plus disponible trop tôt",
|
||||||
|
"The Dungeon Finder boss objective survives a relog": "L’objectif de boss de la recherche de donjons est conservé après reconnexion",
|
||||||
|
"Vanilla dungeon bosses no longer sleep or mind control tanks and healers": "Les boss des donjons classiques n’endorment plus les tanks et soigneurs et ne contrôlent plus leur esprit",
|
||||||
|
"Classic dungeons scale only for Dungeon Finder groups": "Les donjons classiques ne s’adaptent que pour les groupes de la recherche de donjons",
|
||||||
|
"Darkmaster Gandling raises Risen Students only at 52% health": "Le sombre maître Gandling ne relève les étudiants qu’à 52 % de ses points de vie",
|
||||||
|
"Sunken Temple's dragons appear only after the Avatar of Hakkar and Jammal'an": "Les dragons du Temple englouti n’apparaissent qu’après l’Avatar d’Hakkar et Jammal’an",
|
||||||
|
"Scaled loot previews survive a map change": "L’aperçu du butin adapté est conservé lors d’un changement de carte",
|
||||||
|
"Updated SQUID Playerbots to 2.9.4": "SQUID Playerbots passe en version 2.9.4"
|
||||||
},
|
},
|
||||||
"es": {
|
"es": {
|
||||||
"Restrict new characters by custom race without changing existing characters": "Restringe las razas adicionales de personajes nuevos sin modificar los existentes",
|
"Restrict new characters by custom race without changing existing characters": "Restringe las razas adicionales de personajes nuevos sin modificar los existentes",
|
||||||
@@ -391,7 +426,17 @@
|
|||||||
"Startup and shutdown keep bounded diagnostics of launcher stages": "El inicio y la parada guardan diagnósticos limitados de las etapas del lanzador",
|
"Startup and shutdown keep bounded diagnostics of launcher stages": "El inicio y la parada guardan diagnósticos limitados de las etapas del lanzador",
|
||||||
"Database shutdown succeeds when MySQL closes its connection before replying": "La parada de la base de datos se completa aunque MySQL cierre la conexión antes de responder",
|
"Database shutdown succeeds when MySQL closes its connection before replying": "La parada de la base de datos se completa aunque MySQL cierre la conexión antes de responder",
|
||||||
"Server startup waits for ports that Windows is still releasing": "Al iniciarse, el servidor espera a que Windows libere el puerto",
|
"Server startup waits for ports that Windows is still releasing": "Al iniciarse, el servidor espera a que Windows libere el puerto",
|
||||||
"Companions avoid repeating unreachable routes in the open world": "Los compañeros evitan repetir rutas intransitables en el mundo abierto"
|
"Companions avoid repeating unreachable routes in the open world": "Los compañeros evitan repetir rutas intransitables en el mundo abierto",
|
||||||
|
"Login server startup works when Windows does not list its listening port": "El servidor de acceso arranca aunque Windows no muestre su puerto de escucha",
|
||||||
|
"Updated SQUID's Playerbots to 2.9.4 and refreshed Dungeon Clear": "SQUID’s Playerbots se actualiza a 2.9.4 y se renueva Dungeon Clear",
|
||||||
|
"Electrocutioner is used up by Electrocute and no longer makes it look ready too early": "Electrocute consume Electrocutioner y ya no parece disponible antes de tiempo",
|
||||||
|
"The Dungeon Finder boss objective survives a relog": "El objetivo de jefe del buscador de mazmorras se conserva al volver a entrar",
|
||||||
|
"Vanilla dungeon bosses no longer sleep or mind control tanks and healers": "Los jefes de mazmorras clásicas ya no duermen ni controlan mentalmente a tanques y sanadores",
|
||||||
|
"Classic dungeons scale only for Dungeon Finder groups": "Las mazmorras clásicas solo se ajustan para grupos del buscador de mazmorras",
|
||||||
|
"Darkmaster Gandling raises Risen Students only at 52% health": "El Maestro Oscuro Gandling solo alza a los estudiantes resucitados al 52 % de salud",
|
||||||
|
"Sunken Temple's dragons appear only after the Avatar of Hakkar and Jammal'an": "Los dragones del Templo Sumergido solo aparecen después del Avatar de Hakkar y Jammal’an",
|
||||||
|
"Scaled loot previews survive a map change": "La vista previa del botín ajustado se conserva al cambiar de mapa",
|
||||||
|
"Updated SQUID Playerbots to 2.9.4": "SQUID Playerbots se actualiza a 2.9.4"
|
||||||
},
|
},
|
||||||
"zh": {
|
"zh": {
|
||||||
"Restrict new characters by custom race without changing existing characters": "限制新角色可选的自定义种族,不影响现有角色",
|
"Restrict new characters by custom race without changing existing characters": "限制新角色可选的自定义种族,不影响现有角色",
|
||||||
@@ -440,7 +485,17 @@
|
|||||||
"Startup and shutdown keep bounded diagnostics of launcher stages": "启动和关闭时会保留大小受限的启动器阶段诊断日志",
|
"Startup and shutdown keep bounded diagnostics of launcher stages": "启动和关闭时会保留大小受限的启动器阶段诊断日志",
|
||||||
"Database shutdown succeeds when MySQL closes its connection before replying": "即使 MySQL 在回复前关闭连接,数据库关闭操作也能正确完成",
|
"Database shutdown succeeds when MySQL closes its connection before replying": "即使 MySQL 在回复前关闭连接,数据库关闭操作也能正确完成",
|
||||||
"Server startup waits for ports that Windows is still releasing": "服务器启动时会等待 Windows 释放端口",
|
"Server startup waits for ports that Windows is still releasing": "服务器启动时会等待 Windows 释放端口",
|
||||||
"Companions avoid repeating unreachable routes in the open world": "伙伴在开放世界中会避免反复尝试无法通行的路线"
|
"Companions avoid repeating unreachable routes in the open world": "伙伴在开放世界中会避免反复尝试无法通行的路线",
|
||||||
|
"Login server startup works when Windows does not list its listening port": "即使 Windows 未列出监听端口,登录服务器也能启动",
|
||||||
|
"Updated SQUID's Playerbots to 2.9.4 and refreshed Dungeon Clear": "已将 SQUID’s Playerbots 更新至 2.9.4,并更新 Dungeon Clear",
|
||||||
|
"Electrocutioner is used up by Electrocute and no longer makes it look ready too early": "Electrocute 会消耗 Electrocutioner,且不再过早显示为可用",
|
||||||
|
"The Dungeon Finder boss objective survives a relog": "地下城查找器的首领目标在重新登录后仍会保留",
|
||||||
|
"Vanilla dungeon bosses no longer sleep or mind control tanks and healers": "经典地下城首领不再使坦克和治疗者沉睡或受到精神控制",
|
||||||
|
"Classic dungeons scale only for Dungeon Finder groups": "经典地下城仅对通过地下城查找器组成的队伍进行缩放",
|
||||||
|
"Darkmaster Gandling raises Risen Students only at 52% health": "黑暗院长加丁仅在生命值降至 52% 时唤起复活的学生",
|
||||||
|
"Sunken Temple's dragons appear only after the Avatar of Hakkar and Jammal'an": "沉没的神庙中的巨龙仅在哈卡的化身和迦玛兰之后出现",
|
||||||
|
"Scaled loot previews survive a map change": "缩放后的战利品预览在切换地图后仍会保留",
|
||||||
|
"Updated SQUID Playerbots to 2.9.4": "已将 SQUID Playerbots 更新至 2.9.4"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -1571,6 +1571,143 @@
|
|||||||
},
|
},
|
||||||
"experimentalFeatures": [],
|
"experimentalFeatures": [],
|
||||||
"compare": "https://github.com/Corfirean/coa-server-build/compare/server-0.261030.90...server-0.261101.92"
|
"compare": "https://github.com/Corfirean/coa-server-build/compare/server-0.261030.90...server-0.261101.92"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"tag": "server-0.261104.94",
|
||||||
|
"version": "0.261104.94",
|
||||||
|
"date": "2026-11-04",
|
||||||
|
"url": "https://github.com/Corfirean/coa-server-build/releases/tag/server-0.261104.94",
|
||||||
|
"notes": [
|
||||||
|
"Companions avoid repeating unreachable routes in the open world",
|
||||||
|
"Server startup waits for ports that Windows is still releasing",
|
||||||
|
"Updated the reviewed CoA upstream snapshot"
|
||||||
|
],
|
||||||
|
"snapshot": "f67a6d8545e4c6ece2f819f9dd2642fe5a81a69c959946a1031859c19b5c4d74",
|
||||||
|
"components": {
|
||||||
|
"upstream": {
|
||||||
|
"repository": "jealous-sound/azerothcore-wotlk-coa",
|
||||||
|
"ref": "a34c5ad7167b6b2087a678cb4344c6cbe6abb823",
|
||||||
|
"sha": "a34c5ad7167b6b2087a678cb4344c6cbe6abb823"
|
||||||
|
},
|
||||||
|
"core": {
|
||||||
|
"repository": "Corfirean/azerothcore-wotlk-coa",
|
||||||
|
"ref": "14cf375f1e006770b330d3fb89201ace54bfca24",
|
||||||
|
"sha": "14cf375f1e006770b330d3fb89201ace54bfca24"
|
||||||
|
},
|
||||||
|
"bots": {
|
||||||
|
"repository": "Corfirean/mod-coa-playerbots",
|
||||||
|
"ref": "447558bc27d6bb447aaf10eefcb2e85ac2b15c32",
|
||||||
|
"sha": "447558bc27d6bb447aaf10eefcb2e85ac2b15c32"
|
||||||
|
},
|
||||||
|
"scaling": {
|
||||||
|
"repository": "Corfirean/mod-coa-content-scaling",
|
||||||
|
"ref": "3c2febf636bd09087bb278e381b975271a70fdf6",
|
||||||
|
"sha": "3c2febf636bd09087bb278e381b975271a70fdf6"
|
||||||
|
},
|
||||||
|
"manager": {
|
||||||
|
"repository": "Corfirean/coa-server-manager",
|
||||||
|
"ref": "173248efbe24da9b4c1b5ca12fa7580fcd1e8ea7",
|
||||||
|
"sha": "173248efbe24da9b4c1b5ca12fa7580fcd1e8ea7"
|
||||||
|
},
|
||||||
|
"races": {
|
||||||
|
"repository": "ilusixn/azerothcore-wotlk-coa",
|
||||||
|
"ref": "coa-custom-1.9.2",
|
||||||
|
"sha": "31bd63d309b8b0fb4f1a4d9b793a343b8ac36f1e",
|
||||||
|
"assets": [
|
||||||
|
{
|
||||||
|
"name": "CoA-Custom-1.9.2-Client-1.zip",
|
||||||
|
"size": 1513021586,
|
||||||
|
"digest": "sha256:a9dd51ed2d90fb048d549602f40f5429d56e2df0df5606a38781b358fa369568",
|
||||||
|
"url": "https://github.com/ilusixn/azerothcore-wotlk-coa/releases/download/coa-custom-1.9.2/CoA-Custom-1.9.2-Client-1.zip"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "CoA-Custom-1.9.2-Client-2.zip",
|
||||||
|
"size": 1198283005,
|
||||||
|
"digest": "sha256:ab084a55509ccbcc2977a06dd0c01fa879973a1892baaacaeb3ff52f3dfc750e",
|
||||||
|
"url": "https://github.com/ilusixn/azerothcore-wotlk-coa/releases/download/coa-custom-1.9.2/CoA-Custom-1.9.2-Client-2.zip"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "CoA-Custom-1.9.2-Client-3.zip",
|
||||||
|
"size": 1678829573,
|
||||||
|
"digest": "sha256:907e267f0ee7038807e626c3c1eca5e12db6c88b747137a23c5fb52eaa1a358e",
|
||||||
|
"url": "https://github.com/ilusixn/azerothcore-wotlk-coa/releases/download/coa-custom-1.9.2/CoA-Custom-1.9.2-Client-3.zip"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "CoA-Custom-1.9.2-Client-4.zip",
|
||||||
|
"size": 502385128,
|
||||||
|
"digest": "sha256:e0bd87172af989fa50a8e2b08ba4321c72b6265047482f051a1db3b80d55bcaa",
|
||||||
|
"url": "https://github.com/ilusixn/azerothcore-wotlk-coa/releases/download/coa-custom-1.9.2/CoA-Custom-1.9.2-Client-4.zip"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "CoA-Custom-1.9.2-Client-5.zip",
|
||||||
|
"size": 168079711,
|
||||||
|
"digest": "sha256:73364ad1b58c6342641a848a3b20a835472834f600416606be1470386774ca78",
|
||||||
|
"url": "https://github.com/ilusixn/azerothcore-wotlk-coa/releases/download/coa-custom-1.9.2/CoA-Custom-1.9.2-Client-5.zip"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "CoA-Custom-1.9.2-Server.zip",
|
||||||
|
"size": 53004560,
|
||||||
|
"digest": "sha256:b893813573a4d3f6a0003c1f174582d3def997f37b402cbca44d53055d2fc1d2",
|
||||||
|
"url": "https://github.com/ilusixn/azerothcore-wotlk-coa/releases/download/coa-custom-1.9.2/CoA-Custom-1.9.2-Server.zip"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "INSTALL-GUIDE.txt",
|
||||||
|
"size": 3006,
|
||||||
|
"digest": "sha256:f17e97fafa3225901d1caf8c3b8141293f98fbfb8c9243c0c4717278c60146aa",
|
||||||
|
"url": "https://github.com/ilusixn/azerothcore-wotlk-coa/releases/download/coa-custom-1.9.2/INSTALL-GUIDE.txt"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "PATCH-NOTES-1.9.2.txt",
|
||||||
|
"size": 2822,
|
||||||
|
"digest": "sha256:f2fd4693ba181959a572d3fb10a0050e9ff6c4f735b3ab0019c7d16712db28cb",
|
||||||
|
"url": "https://github.com/ilusixn/azerothcore-wotlk-coa/releases/download/coa-custom-1.9.2/PATCH-NOTES-1.9.2.txt"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"squid": {
|
||||||
|
"repository": "Zyth45/mod-playerbots",
|
||||||
|
"ref": "v2.8.2",
|
||||||
|
"sha": "fa4cfd31997367b3e574a2b89b858c4669ff53fb",
|
||||||
|
"patch": "patches/squid-coa-validation.patch",
|
||||||
|
"patchSha256": "9b101db17369fb5a6af3f7e99323f7770eb8650ba3b5e9b3970bf09a0ef5d32f"
|
||||||
|
},
|
||||||
|
"build": {
|
||||||
|
"repository": "Corfirean/coa-server-build",
|
||||||
|
"ref": "d9aaa5263154473b2fe1623172492f88e6e03d73",
|
||||||
|
"sha": "d9aaa5263154473b2fe1623172492f88e6e03d73"
|
||||||
|
},
|
||||||
|
"dungeon-clear": {
|
||||||
|
"repository": "Zyth45/mod-dungeon-clear",
|
||||||
|
"sha": "9a9d09cf512e0a883af9cda6973445b81c123b13",
|
||||||
|
"patch": "patches/dungeon-clear-coa-validation.patch",
|
||||||
|
"patchSha256": "956f278865e22ee75c984ca22ff8238150b5886c9934ddfe64dd9c832c912dcc",
|
||||||
|
"ref": "9a9d09cf512e0a883af9cda6973445b81c123b13"
|
||||||
|
},
|
||||||
|
"navigation": {
|
||||||
|
"repository": "Corfirean/azerothcore-wotlk-coa",
|
||||||
|
"ref": "8b44099f480af0b69c6dfc697e4d388e865e9ffc",
|
||||||
|
"sha": "8b44099f480af0b69c6dfc697e4d388e865e9ffc",
|
||||||
|
"sourceRelease": "navigation-20261012",
|
||||||
|
"manifestSha256": "7f28600735f115792e79a5e8d1c8d78a83a8f5ed14a090c6d87268e49c2bb683",
|
||||||
|
"archiveSha256": "aa1347a095f85af44b4f592270a0e9314954801fda4578f0147f847e32c24a60",
|
||||||
|
"assets": [
|
||||||
|
{
|
||||||
|
"name": "navigation.zip.001",
|
||||||
|
"size": 1500000000,
|
||||||
|
"sha256": "e3a93903fc8155ee0d92db399ec426769c360bef87c44c07beb7e21cfd892c18",
|
||||||
|
"url": "https://github.com/Corfirean/coa-server-build/releases/download/navigation-20261012/navigation.zip.001"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "navigation.zip.002",
|
||||||
|
"size": 1377006470,
|
||||||
|
"sha256": "c1af26ba7f83676278613076c357c4da0a11cfa6ae1ff00003479057c4864471",
|
||||||
|
"url": "https://github.com/Corfirean/coa-server-build/releases/download/navigation-20261012/navigation.zip.002"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"experimentalFeatures": [],
|
||||||
|
"compare": "https://github.com/Corfirean/coa-server-build/compare/server-0.261101.92...server-0.261104.94"
|
||||||
}
|
}
|
||||||
]
|
]
|
||||||
}
|
}
|
||||||
@@ -50,6 +50,7 @@ export {};
|
|||||||
if(cmd==="play") return {ok:true,exit_code:null,code:null,human:null,output:""};
|
if(cmd==="play") return {ok:true,exit_code:null,code:null,human:null,output:""};
|
||||||
if(cmd==="list_servers") return added?[{id:"1",name:"CoA-Repack",path:report.path}]:[];
|
if(cmd==="list_servers") return added?[{id:"1",name:"CoA-Repack",path:report.path}]:[];
|
||||||
if(cmd==="scan_server") return report;
|
if(cmd==="scan_server") return report;
|
||||||
|
if(cmd==="modular_copy_preview"){await new Promise(r=>setTimeout(r,400));const p=String(args.path);if(!/repack|server/i.test(p))return {path:p,classic:false,modular:false,version:null,database:"missing",accounts:null,characters:null,schemas:[],database_bytes:0,config_files:[],extra_worlds:[]};const run=!/stopped/i.test(p);return {path:p,classic:true,modular:false,version:"0.261108.95",database:run?"running":"stopped",accounts:run?12:null,characters:run?37:null,schemas:run?["acore_auth","acore_characters","acore_playerbots","acore_world"]:[],database_bytes:6.3*2**30,config_files:["Core/configs/modules/mod-coa-content-scaling.conf","Core/configs/modules/playerbots.conf","Settings/realm-profile.json"],extra_worlds:run?[]:["secondary"]};}
|
||||||
if(cmd==="add_server"){added=true;return {id:"1",name:"CoA-Repack",path:report.path};}
|
if(cmd==="add_server"){added=true;return {id:"1",name:"CoA-Repack",path:report.path};}
|
||||||
if(cmd==="server_status"){const s=running?"running":"stopped";return {observed:{mysql:svc("mysql",3307,s),auth:svc("auth",3724,s),world:svc("world",8085,s),secondary_world:simultaneous?svc("world-secondary",8086,s):null,reborn_world:withReborn?svc("world-reborn",8087,s):null},busy:false,path_exists:true};}
|
if(cmd==="server_status"){const s=running?"running":"stopped";return {observed:{mysql:svc("mysql",3307,s),auth:svc("auth",3724,s),world:svc("world",8085,s),secondary_world:simultaneous?svc("world-secondary",8086,s):null,reborn_world:withReborn?svc("world-reborn",8087,s):null},busy:false,path_exists:true};}
|
||||||
if(cmd==="start_server"){await new Promise((r: any)=>setTimeout(r,1500));running=true;return {ok:true,exit_code:0,code:null,human:null,output:""};}
|
if(cmd==="start_server"){await new Promise((r: any)=>setTimeout(r,1500));running=true;return {ok:true,exit_code:0,code:null,human:null,output:""};}
|
||||||
|
|||||||
+58
-1
@@ -267,6 +267,20 @@ const en = {
|
|||||||
"install.step.unpacking": "Unpacking",
|
"install.step.unpacking": "Unpacking",
|
||||||
"install.step.database": "Preparing database",
|
"install.step.database": "Preparing database",
|
||||||
"install.step.finishing": "Finishing",
|
"install.step.finishing": "Finishing",
|
||||||
|
"install.step.modularCore": "Installing the modular core",
|
||||||
|
"install.modularCoreHint": "Modules the old server had switched on are compiled on this computer; this can take several minutes.",
|
||||||
|
"install.step.copying": "Copying the old server's data",
|
||||||
|
"install.copy.title": "Modular copy of your server",
|
||||||
|
"install.copy.subtitle": "Your server has the classic core. A new server with the modular core is installed next to it, and accounts, characters, the world and module settings are copied into it. The old server is not changed; you can keep using it.",
|
||||||
|
"install.copy.from": "Copy from:",
|
||||||
|
"install.copy.done": "Copied {accounts} accounts, {characters} characters and {settings} settings files.",
|
||||||
|
"import.classic.title": "This server has the classic core",
|
||||||
|
"import.classic.text": "Its modules are compiled into the core. The Modules Preview does not change it: it installs a modular server next to it and copies the data into it. Run one of the two at a time, they use the same ports.",
|
||||||
|
"import.classic.copy": "Create a modular copy",
|
||||||
|
"install.classicCoreTitle": "The server stays on the classic core",
|
||||||
|
"install.classicCoreText": "The server is installed and works, but the modular core did not go on, so its modules are built into the core. You can try again from Updates.",
|
||||||
|
"install.modulesOffTitle": "Some modules were switched off",
|
||||||
|
"install.modulesOffText": "The modular core is installed, but these modules did not build on this computer. The server works without them; they are tried again on the next update.",
|
||||||
"install.doneTitle": "Your server is ready",
|
"install.doneTitle": "Your server is ready",
|
||||||
"install.doneText": "Everything is installed. Start it from the next screen.",
|
"install.doneText": "Everything is installed. Start it from the next screen.",
|
||||||
"install.open": "OPEN MY SERVER",
|
"install.open": "OPEN MY SERVER",
|
||||||
@@ -851,7 +865,50 @@ const en = {
|
|||||||
"realm.confirmDelete": "Remove the realmlist “{name}”? The game client keeps whatever file it has now.",
|
"realm.confirmDelete": "Remove the realmlist “{name}”? The game client keeps whatever file it has now.",
|
||||||
"nav.modules": "Modules",
|
"nav.modules": "Modules",
|
||||||
"nav.migration": "Server Migration",
|
"nav.migration": "Server Migration",
|
||||||
"q.migration": "Migrate data from an existing server into this Preview realm",
|
"q.migration": "Move a server with the classic core to the modular core: a copy next to it",
|
||||||
|
"migrate.title": "Server migration",
|
||||||
|
"migrate.subtitle": "A server with the classic core is not converted in place. A new server with the modular core is installed next to it, and its accounts, characters, world, bots and module settings are copied into it.",
|
||||||
|
"migrate.source": "Which server to move",
|
||||||
|
"migrate.browse": "Browse…",
|
||||||
|
"migrate.inspect": "Check",
|
||||||
|
"migrate.dialogTitle": "Choose the server's main folder",
|
||||||
|
"migrate.readOnly": "Checking only reads the folder; a running database is only asked for counts. Nothing is started or changed.",
|
||||||
|
"migrate.classic.title": "Classic core: it can be copied",
|
||||||
|
"migrate.classic.text": "The copy becomes a new server with the modular core. This server stays as it is.",
|
||||||
|
"migrate.modular.title": "Already the modular core",
|
||||||
|
"migrate.modular.text": "Nothing to move. To manage this server here, add it with “Manage another server”.",
|
||||||
|
"migrate.none.title": "No server found here",
|
||||||
|
"migrate.none.text": "This folder has no Core\\worldserver.exe of a Windows server. Choose the server's main folder.",
|
||||||
|
"migrate.fact.version": "Version",
|
||||||
|
"migrate.fact.database": "Database",
|
||||||
|
"migrate.fact.accounts": "Accounts",
|
||||||
|
"migrate.fact.characters": "Characters",
|
||||||
|
"migrate.unknown": "unknown",
|
||||||
|
"migrate.countLater": "counted while copying",
|
||||||
|
"migrate.db.running": "running",
|
||||||
|
"migrate.db.stopped": "stopped",
|
||||||
|
"migrate.db.missing": "not found",
|
||||||
|
"migrate.db.missingText": "This server has no database folder (mysql\\data), so there is nothing to copy.",
|
||||||
|
"migrate.copied": "What is copied",
|
||||||
|
"migrate.copied.schemas": "Every game database: {list}.",
|
||||||
|
"migrate.copied.allSchemas": "Every game database (accounts, characters, world, bots); the list is read while copying.",
|
||||||
|
"migrate.copied.settings": "Module settings and realm profiles: {n} files.",
|
||||||
|
"install.copy.worldSkipped": "World settings the new version did not take:",
|
||||||
|
"install.copy.worldSettings": "World settings carried over: {n}.",
|
||||||
|
"migrate.copied.world": "World settings changed in Server Configuration (rates and the like).",
|
||||||
|
"migrate.copied.ports": "Ports and the console login, as the old server has them.",
|
||||||
|
"migrate.copied.modules": "The modules the old server has switched on are built for the modular core during the copy.",
|
||||||
|
"migrate.copied.worlds": "Extra worlds ({list}): their databases go along and they stay switched on.",
|
||||||
|
"migrate.notCopied": "What is not copied",
|
||||||
|
"migrate.notCopied.conf": "worldserver.conf and authserver.conf themselves: the new server makes them from its own templates. Values changed in Server Configuration are set on the new server.",
|
||||||
|
"migrate.notCopied.merge": "Nothing is merged into {name} or any other existing server: the copy is always a new server in a new folder.",
|
||||||
|
"migrate.risks": "Before you start",
|
||||||
|
"migrate.risk.oldKept": "The old server is only read. Its folder and database are not changed, and you can keep using it.",
|
||||||
|
"migrate.risk.ports": "Both servers use the same ports: run only one of them at a time.",
|
||||||
|
"migrate.risk.running": "Its database is running and is read as it is at that moment. Stop its world first so players and bots do not change data while it is copied.",
|
||||||
|
"migrate.risk.stopped": "Its database is stopped: its files ({gb} GB) are copied once more while they are read, so that much extra space is needed.",
|
||||||
|
"migrate.risk.build": "Modules are compiled on this PC with Microsoft's C++ build tools; the SQUID bots alone can take up to an hour.",
|
||||||
|
"migrate.start": "Make the modular copy",
|
||||||
"q.modules": "What extra features does the server have?",
|
"q.modules": "What extra features does the server have?",
|
||||||
"mod.ahbot.types": "Item types for sale",
|
"mod.ahbot.types": "Item types for sale",
|
||||||
"mod.ahbot.typesHint": "Choose types for new listings. Existing auctions remain. Enabling a type restores its previous weights in this session, or the configured defaults.",
|
"mod.ahbot.typesHint": "Choose types for new listings. Existing auctions remain. Enabling a type restores its previous weights in this session, or the configured defaults.",
|
||||||
|
|||||||
+58
-1
@@ -251,6 +251,20 @@ const ru: Partial<Record<keyof typeof en, string>> = {
|
|||||||
"install.step.unpacking": "Распаковка",
|
"install.step.unpacking": "Распаковка",
|
||||||
"install.step.database": "Подготовка базы данных",
|
"install.step.database": "Подготовка базы данных",
|
||||||
"install.step.finishing": "Завершение",
|
"install.step.finishing": "Завершение",
|
||||||
|
"install.step.modularCore": "Установка модульного ядра",
|
||||||
|
"install.modularCoreHint": "Модули, которые были включены на старом сервере, компилируются на вашем компьютере; это может занять несколько минут.",
|
||||||
|
"install.step.copying": "Копирование данных старого сервера",
|
||||||
|
"install.copy.title": "Модульная копия вашего сервера",
|
||||||
|
"install.copy.subtitle": "У вашего сервера классическое ядро. Рядом ставится новый сервер с модульным ядром, в него копируются аккаунты, персонажи, мир и настройки модулей. Старый сервер не меняется, им можно продолжать пользоваться.",
|
||||||
|
"install.copy.from": "Копировать из:",
|
||||||
|
"install.copy.done": "Скопировано аккаунтов: {accounts}, персонажей: {characters}, файлов настроек: {settings}.",
|
||||||
|
"import.classic.title": "У этого сервера классическое ядро",
|
||||||
|
"import.classic.text": "Модули вкомпилированы в ядро. Превью-менеджер его не меняет: он ставит рядом модульный сервер и копирует в него данные. Запускайте один из двух: порты у них одинаковые.",
|
||||||
|
"import.classic.copy": "Создать модульную копию",
|
||||||
|
"install.classicCoreTitle": "Сервер остался на классическом ядре",
|
||||||
|
"install.classicCoreText": "Сервер установлен и работает, но модульное ядро не встало, поэтому модули встроены в ядро. Можно повторить из раздела «Обновления».",
|
||||||
|
"install.modulesOffTitle": "Часть модулей выключена",
|
||||||
|
"install.modulesOffText": "Модульное ядро установлено, но эти модули не собрались на этом компьютере. Сервер работает без них; при следующем обновлении сборка повторится.",
|
||||||
"install.doneTitle": "Ваш сервер готов",
|
"install.doneTitle": "Ваш сервер готов",
|
||||||
"install.doneText": "Всё установлено. Запустите сервер на следующем экране.",
|
"install.doneText": "Всё установлено. Запустите сервер на следующем экране.",
|
||||||
"install.open": "ОТКРЫТЬ МОЙ СЕРВЕР",
|
"install.open": "ОТКРЫТЬ МОЙ СЕРВЕР",
|
||||||
@@ -835,7 +849,50 @@ const ru: Partial<Record<keyof typeof en, string>> = {
|
|||||||
"realm.confirmDelete": "Удалить реалмлист «{name}»? В игровом клиенте останется текущий файл.",
|
"realm.confirmDelete": "Удалить реалмлист «{name}»? В игровом клиенте останется текущий файл.",
|
||||||
"nav.modules": "Модули",
|
"nav.modules": "Модули",
|
||||||
"nav.migration": "Перенос сервера",
|
"nav.migration": "Перенос сервера",
|
||||||
"q.migration": "Перенос данных из существующего сервера в этот мир Preview",
|
"q.migration": "Перенос сервера с классическим ядром на модульное: копия рядом",
|
||||||
|
"migrate.title": "Перенос сервера",
|
||||||
|
"migrate.subtitle": "Сервер с классическим ядром не переделывается на месте. Рядом ставится новый сервер с модульным ядром, и в него копируются аккаунты, персонажи, мир, боты и настройки модулей.",
|
||||||
|
"migrate.source": "Какой сервер перенести",
|
||||||
|
"migrate.browse": "Обзор…",
|
||||||
|
"migrate.inspect": "Проверить",
|
||||||
|
"migrate.dialogTitle": "Выберите основную папку сервера",
|
||||||
|
"migrate.readOnly": "Проверка только читает папку; у запущенной базы лишь спрашивает количество. Ничего не запускается и не меняется.",
|
||||||
|
"migrate.classic.title": "Классическое ядро: можно скопировать",
|
||||||
|
"migrate.classic.text": "Копия станет новым сервером с модульным ядром. Этот сервер останется как есть.",
|
||||||
|
"migrate.modular.title": "Уже модульное ядро",
|
||||||
|
"migrate.modular.text": "Переносить нечего. Чтобы управлять этим сервером здесь, добавьте его через «Manage another server».",
|
||||||
|
"migrate.none.title": "Сервер не найден",
|
||||||
|
"migrate.none.text": "В этой папке нет Core\\worldserver.exe Windows-сервера. Выберите основную папку сервера.",
|
||||||
|
"migrate.fact.version": "Версия",
|
||||||
|
"migrate.fact.database": "База данных",
|
||||||
|
"migrate.fact.accounts": "Аккаунтов",
|
||||||
|
"migrate.fact.characters": "Персонажей",
|
||||||
|
"migrate.unknown": "неизвестна",
|
||||||
|
"migrate.countLater": "посчитаем при копировании",
|
||||||
|
"migrate.db.running": "запущена",
|
||||||
|
"migrate.db.stopped": "остановлена",
|
||||||
|
"migrate.db.missing": "не найдена",
|
||||||
|
"migrate.db.missingText": "У этого сервера нет папки базы данных (mysql\\data), копировать нечего.",
|
||||||
|
"migrate.copied": "Что копируется",
|
||||||
|
"migrate.copied.schemas": "Все игровые базы: {list}.",
|
||||||
|
"migrate.copied.allSchemas": "Все игровые базы (аккаунты, персонажи, мир, боты); список прочитаем при копировании.",
|
||||||
|
"migrate.copied.settings": "Настройки модулей и профили миров: файлов — {n}.",
|
||||||
|
"install.copy.worldSkipped": "Настройки мира, которые новая версия не приняла:",
|
||||||
|
"install.copy.worldSettings": "Перенесено настроек мира: {n}.",
|
||||||
|
"migrate.copied.world": "Настройки мира, изменённые в Server Configuration (рейты и т. п.).",
|
||||||
|
"migrate.copied.ports": "Порты и вход в консоль, как у старого сервера.",
|
||||||
|
"migrate.copied.modules": "Модули, включённые на старом сервере, собираются под модульное ядро во время копирования.",
|
||||||
|
"migrate.copied.worlds": "Дополнительные миры ({list}): их базы копируются, и они остаются включёнными.",
|
||||||
|
"migrate.notCopied": "Что не копируется",
|
||||||
|
"migrate.notCopied.conf": "Сами worldserver.conf и authserver.conf: новый сервер делает их из своих шаблонов. Значения, изменённые в Server Configuration, задаются на новом сервере.",
|
||||||
|
"migrate.notCopied.merge": "Ничего не сливается в {name} или другой существующий сервер: копия — всегда новый сервер в новой папке.",
|
||||||
|
"migrate.risks": "Перед началом",
|
||||||
|
"migrate.risk.oldKept": "Старый сервер только читается. Его папка и база не меняются, им можно продолжать пользоваться.",
|
||||||
|
"migrate.risk.ports": "У обоих серверов одинаковые порты: запускайте только один из них.",
|
||||||
|
"migrate.risk.running": "Его база запущена и будет прочитана в том виде, в каком она в этот момент. Сначала остановите его мир, чтобы игроки и боты не меняли данные во время копирования.",
|
||||||
|
"migrate.risk.stopped": "Его база остановлена: её файлы ({gb} ГБ) на время чтения копируются ещё раз, нужно столько же свободного места.",
|
||||||
|
"migrate.risk.build": "Модули компилируются на этом ПК инструментами сборки C++ от Microsoft; одни только боты SQUID могут собираться до часа.",
|
||||||
|
"migrate.start": "Сделать модульную копию",
|
||||||
"q.modules": "Какие дополнительные возможности есть у сервера?",
|
"q.modules": "Какие дополнительные возможности есть у сервера?",
|
||||||
"mod.ahbot.types": "Типы предметов в продаже",
|
"mod.ahbot.types": "Типы предметов в продаже",
|
||||||
"mod.ahbot.typesHint": "Выберите типы для новых лотов. Уже выставленные лоты останутся. При включении возвращаются прежние веса этой сессии или значения по умолчанию.",
|
"mod.ahbot.typesHint": "Выберите типы для новых лотов. Уже выставленные лоты останутся. При включении возвращаются прежние веса этой сессии или значения по умолчанию.",
|
||||||
|
|||||||
@@ -8,6 +8,7 @@
|
|||||||
"bots.quests": "Quests",
|
"bots.quests": "Quests",
|
||||||
"bots.combat": "Kampf",
|
"bots.combat": "Kampf",
|
||||||
"bots.dungeon": "Dungeonsuche",
|
"bots.dungeon": "Dungeonsuche",
|
||||||
|
"bots.scaling": "Stärke der Bots",
|
||||||
"bots.battlegrounds": "Schlachtfelder",
|
"bots.battlegrounds": "Schlachtfelder",
|
||||||
"bots.social": "Soziales Verhalten",
|
"bots.social": "Soziales Verhalten",
|
||||||
"bots.advanced": "Erweitert",
|
"bots.advanced": "Erweitert",
|
||||||
@@ -220,6 +221,46 @@
|
|||||||
"t": "Bots stellen sich selbst für Dungeons an",
|
"t": "Bots stellen sich selbst für Dungeons an",
|
||||||
"d": "Experimentell: Untätige Tank-Bots stellen sich selbst für einen Dungeon an, und die Auffüllung oben vervollständigt die Gruppe."
|
"d": "Experimentell: Untätige Tank-Bots stellen sich selbst für einen Dungeon an, und die Auffüllung oben vervollständigt die Gruppe."
|
||||||
},
|
},
|
||||||
|
"CoaBots.Scaling.Enable": {
|
||||||
|
"t": "Bots in Gruppeninhalten helfen",
|
||||||
|
"d": "Wendet die Faktoren unten auf Bots, ihre Begleiter und Totems an. Stehen alle Faktoren auf 1, ändert sich nichts."
|
||||||
|
},
|
||||||
|
"CoaBots.Scaling.Dungeons": {
|
||||||
|
"t": "In Dungeons",
|
||||||
|
"d": "Faktoren in Dungeons für 5 Spieler anwenden."
|
||||||
|
},
|
||||||
|
"CoaBots.Scaling.Raids": {
|
||||||
|
"t": "In Schlachtzügen",
|
||||||
|
"d": "Faktoren in Schlachtzügen anwenden."
|
||||||
|
},
|
||||||
|
"CoaBots.Scaling.Battlegrounds": {
|
||||||
|
"t": "In Schlachtfeldern und Arenen",
|
||||||
|
"d": "Faktoren in Schlachtfeldern und Arenen anwenden, nur gegen Kreaturen."
|
||||||
|
},
|
||||||
|
"CoaBots.Scaling.World": {
|
||||||
|
"t": "In der offenen Welt",
|
||||||
|
"d": "Faktoren außerhalb von Instanzen anwenden."
|
||||||
|
},
|
||||||
|
"CoaBots.Scaling.DamageDone": {
|
||||||
|
"t": "Schaden der Bots",
|
||||||
|
"d": "Schaden, den Bots Monstern zufügen. 1 ist normal, 1,5 ist das Anderthalbfache."
|
||||||
|
},
|
||||||
|
"CoaBots.Scaling.HealingDone": {
|
||||||
|
"t": "Heilung der Bots",
|
||||||
|
"d": "Heilung, die Bots wirken. 1 ist normal."
|
||||||
|
},
|
||||||
|
"CoaBots.Scaling.DamageTaken": {
|
||||||
|
"t": "Schaden an Bots",
|
||||||
|
"d": "Schaden, den Monster Bots zufügen. Unter 1 erleiden Bots weniger; 0,7 bedeutet 30 % weniger."
|
||||||
|
},
|
||||||
|
"CoaBots.Scaling.TankThreat": {
|
||||||
|
"t": "Bedrohung des Bot-Tanks",
|
||||||
|
"d": "Bedrohung, die ein Bot-Tank erzeugt, damit Monster bei ihm bleiben. 1 ist normal."
|
||||||
|
},
|
||||||
|
"CoaBots.Scaling.BossTuning": {
|
||||||
|
"t": "Zusätzliche Hilfe gegen einige schwere Bosse",
|
||||||
|
"d": "Stärkere Faktoren für Loken, den Drakkari-Elementar, den Drakkari-Koloss und Gal'darah, die Bots der Stufe 60 sonst nicht besiegen."
|
||||||
|
},
|
||||||
"CoaBots.BGFill.Enable": {
|
"CoaBots.BGFill.Enable": {
|
||||||
"t": "Bot-Auffüllung für Schlachtfelder",
|
"t": "Bot-Auffüllung für Schlachtfelder",
|
||||||
"d": "Wenn jemand für ein Schlachtfeld ansteht, werden beide Teams mit Bots aufgefüllt, damit das Spiel sofort beginnt."
|
"d": "Wenn jemand für ein Schlachtfeld ansteht, werden beide Teams mit Bots aufgefüllt, damit das Spiel sofort beginnt."
|
||||||
|
|||||||
@@ -8,6 +8,7 @@
|
|||||||
"bots.quests": "Misiones",
|
"bots.quests": "Misiones",
|
||||||
"bots.combat": "Combate",
|
"bots.combat": "Combate",
|
||||||
"bots.dungeon": "Buscador de mazmorras",
|
"bots.dungeon": "Buscador de mazmorras",
|
||||||
|
"bots.scaling": "Fuerza de los bots",
|
||||||
"bots.battlegrounds": "Campos de batalla",
|
"bots.battlegrounds": "Campos de batalla",
|
||||||
"bots.social": "Comportamiento social",
|
"bots.social": "Comportamiento social",
|
||||||
"bots.advanced": "Avanzado",
|
"bots.advanced": "Avanzado",
|
||||||
@@ -220,6 +221,46 @@
|
|||||||
"t": "Los bots se ponen en cola para mazmorras solos",
|
"t": "Los bots se ponen en cola para mazmorras solos",
|
||||||
"d": "Experimental: los bots tanque inactivos se ponen en cola para una mazmorra por su cuenta y el relleno anterior completa el grupo."
|
"d": "Experimental: los bots tanque inactivos se ponen en cola para una mazmorra por su cuenta y el relleno anterior completa el grupo."
|
||||||
},
|
},
|
||||||
|
"CoaBots.Scaling.Enable": {
|
||||||
|
"t": "Ayudar a los bots en contenido de grupo",
|
||||||
|
"d": "Aplica los multiplicadores de abajo a los bots, sus mascotas y tótems. Con todos los multiplicadores en 1 no cambia nada."
|
||||||
|
},
|
||||||
|
"CoaBots.Scaling.Dungeons": {
|
||||||
|
"t": "En mazmorras",
|
||||||
|
"d": "Aplicar los multiplicadores en mazmorras de 5 jugadores."
|
||||||
|
},
|
||||||
|
"CoaBots.Scaling.Raids": {
|
||||||
|
"t": "En bandas",
|
||||||
|
"d": "Aplicar los multiplicadores en bandas."
|
||||||
|
},
|
||||||
|
"CoaBots.Scaling.Battlegrounds": {
|
||||||
|
"t": "En campos de batalla y arenas",
|
||||||
|
"d": "Aplicar los multiplicadores en campos de batalla y arenas, solo contra criaturas."
|
||||||
|
},
|
||||||
|
"CoaBots.Scaling.World": {
|
||||||
|
"t": "En el mundo abierto",
|
||||||
|
"d": "Aplicar los multiplicadores fuera de las instancias."
|
||||||
|
},
|
||||||
|
"CoaBots.Scaling.DamageDone": {
|
||||||
|
"t": "Daño de los bots",
|
||||||
|
"d": "Daño que los bots infligen a los monstruos. 1 es normal, 1,5 es la mitad más."
|
||||||
|
},
|
||||||
|
"CoaBots.Scaling.HealingDone": {
|
||||||
|
"t": "Sanación de los bots",
|
||||||
|
"d": "Sanación que lanzan los bots. 1 es normal."
|
||||||
|
},
|
||||||
|
"CoaBots.Scaling.DamageTaken": {
|
||||||
|
"t": "Daño recibido por los bots",
|
||||||
|
"d": "Daño que los monstruos infligen a los bots. Por debajo de 1 reciben menos; 0,7 es un 30 % menos."
|
||||||
|
},
|
||||||
|
"CoaBots.Scaling.TankThreat": {
|
||||||
|
"t": "Amenaza del tanque bot",
|
||||||
|
"d": "Amenaza que genera un tanque bot para que los monstruos sigan con él. 1 es normal."
|
||||||
|
},
|
||||||
|
"CoaBots.Scaling.BossTuning": {
|
||||||
|
"t": "Ayuda extra contra algunos jefes difíciles",
|
||||||
|
"d": "Multiplicadores más fuertes para Loken, el Elemental Drakkari, el Coloso Drakkari y Gal'darah, que los bots de nivel 60 no vencen de otro modo."
|
||||||
|
},
|
||||||
"CoaBots.BGFill.Enable": {
|
"CoaBots.BGFill.Enable": {
|
||||||
"t": "Relleno con bots de campos de batalla",
|
"t": "Relleno con bots de campos de batalla",
|
||||||
"d": "Cuando alguien se pone en cola para un campo de batalla, ambos equipos se completan con bots para que la partida empiece enseguida."
|
"d": "Cuando alguien se pone en cola para un campo de batalla, ambos equipos se completan con bots para que la partida empiece enseguida."
|
||||||
|
|||||||
@@ -8,6 +8,7 @@
|
|||||||
"bots.quests": "Quêtes",
|
"bots.quests": "Quêtes",
|
||||||
"bots.combat": "Combat",
|
"bots.combat": "Combat",
|
||||||
"bots.dungeon": "Recherche de donjon",
|
"bots.dungeon": "Recherche de donjon",
|
||||||
|
"bots.scaling": "Force des bots",
|
||||||
"bots.battlegrounds": "Champs de bataille",
|
"bots.battlegrounds": "Champs de bataille",
|
||||||
"bots.social": "Comportement social",
|
"bots.social": "Comportement social",
|
||||||
"bots.advanced": "Avancé",
|
"bots.advanced": "Avancé",
|
||||||
@@ -220,6 +221,46 @@
|
|||||||
"t": "Les bots s’inscrivent seuls aux donjons",
|
"t": "Les bots s’inscrivent seuls aux donjons",
|
||||||
"d": "Expérimental : des bots tanks inactifs s’inscrivent seuls à un donjon et la complétion ci-dessus termine le groupe."
|
"d": "Expérimental : des bots tanks inactifs s’inscrivent seuls à un donjon et la complétion ci-dessus termine le groupe."
|
||||||
},
|
},
|
||||||
|
"CoaBots.Scaling.Enable": {
|
||||||
|
"t": "Aider les bots en contenu de groupe",
|
||||||
|
"d": "Applique les multiplicateurs ci-dessous aux bots, à leurs familiers et totems. Avec tous les multiplicateurs à 1, rien ne change."
|
||||||
|
},
|
||||||
|
"CoaBots.Scaling.Dungeons": {
|
||||||
|
"t": "En donjons",
|
||||||
|
"d": "Appliquer les multiplicateurs dans les donjons à 5 joueurs."
|
||||||
|
},
|
||||||
|
"CoaBots.Scaling.Raids": {
|
||||||
|
"t": "En raids",
|
||||||
|
"d": "Appliquer les multiplicateurs en raid."
|
||||||
|
},
|
||||||
|
"CoaBots.Scaling.Battlegrounds": {
|
||||||
|
"t": "En champs de bataille et arènes",
|
||||||
|
"d": "Appliquer les multiplicateurs en champs de bataille et arènes, contre les créatures uniquement."
|
||||||
|
},
|
||||||
|
"CoaBots.Scaling.World": {
|
||||||
|
"t": "Dans le monde ouvert",
|
||||||
|
"d": "Appliquer les multiplicateurs hors des instances."
|
||||||
|
},
|
||||||
|
"CoaBots.Scaling.DamageDone": {
|
||||||
|
"t": "Dégâts des bots",
|
||||||
|
"d": "Dégâts que les bots infligent aux monstres. 1 est normal, 1,5 vaut une fois et demie plus."
|
||||||
|
},
|
||||||
|
"CoaBots.Scaling.HealingDone": {
|
||||||
|
"t": "Soins des bots",
|
||||||
|
"d": "Soins lancés par les bots. 1 est normal."
|
||||||
|
},
|
||||||
|
"CoaBots.Scaling.DamageTaken": {
|
||||||
|
"t": "Dégâts subis par les bots",
|
||||||
|
"d": "Dégâts que les monstres infligent aux bots. En dessous de 1 ils en subissent moins ; 0,7 signifie 30 % de moins."
|
||||||
|
},
|
||||||
|
"CoaBots.Scaling.TankThreat": {
|
||||||
|
"t": "Menace du tank bot",
|
||||||
|
"d": "Menace générée par un tank bot pour garder les monstres sur lui. 1 est normal."
|
||||||
|
},
|
||||||
|
"CoaBots.Scaling.BossTuning": {
|
||||||
|
"t": "Aide supplémentaire contre quelques boss difficiles",
|
||||||
|
"d": "Multiplicateurs plus forts pour Loken, l'élémentaire drakkari, le colosse drakkari et Gal'darah, que les bots de niveau 60 ne battent pas autrement."
|
||||||
|
},
|
||||||
"CoaBots.BGFill.Enable": {
|
"CoaBots.BGFill.Enable": {
|
||||||
"t": "Complétion par bots des champs de bataille",
|
"t": "Complétion par bots des champs de bataille",
|
||||||
"d": "Quand quelqu’un s’inscrit à un champ de bataille, les deux équipes sont complétées par des bots pour que la partie commence tout de suite."
|
"d": "Quand quelqu’un s’inscrit à un champ de bataille, les deux équipes sont complétées par des bots pour que la partie commence tout de suite."
|
||||||
|
|||||||
@@ -8,6 +8,7 @@
|
|||||||
"bots.quests": "Задания",
|
"bots.quests": "Задания",
|
||||||
"bots.combat": "Бой",
|
"bots.combat": "Бой",
|
||||||
"bots.dungeon": "Поиск подземелий",
|
"bots.dungeon": "Поиск подземелий",
|
||||||
|
"bots.scaling": "Сила ботов",
|
||||||
"bots.battlegrounds": "Поля боя",
|
"bots.battlegrounds": "Поля боя",
|
||||||
"bots.social": "Общение и помощь",
|
"bots.social": "Общение и помощь",
|
||||||
"bots.advanced": "Дополнительно",
|
"bots.advanced": "Дополнительно",
|
||||||
@@ -220,6 +221,46 @@
|
|||||||
"t": "Боты сами встают в очередь в подземелья",
|
"t": "Боты сами встают в очередь в подземелья",
|
||||||
"d": "Экспериментально: бездействующие боты-танки сами встают в очередь в подземелье, а дополнение выше собирает группу."
|
"d": "Экспериментально: бездействующие боты-танки сами встают в очередь в подземелье, а дополнение выше собирает группу."
|
||||||
},
|
},
|
||||||
|
"CoaBots.Scaling.Enable": {
|
||||||
|
"t": "Помощь ботам в групповом контенте",
|
||||||
|
"d": "Применяет множители ниже к ботам, их питомцам и тотемам. Если все множители равны 1, ничего не меняется."
|
||||||
|
},
|
||||||
|
"CoaBots.Scaling.Dungeons": {
|
||||||
|
"t": "В подземельях",
|
||||||
|
"d": "Применять множители в подземельях на 5 игроков."
|
||||||
|
},
|
||||||
|
"CoaBots.Scaling.Raids": {
|
||||||
|
"t": "В рейдах",
|
||||||
|
"d": "Применять множители в рейдах."
|
||||||
|
},
|
||||||
|
"CoaBots.Scaling.Battlegrounds": {
|
||||||
|
"t": "На полях боя и аренах",
|
||||||
|
"d": "Применять множители на полях боя и аренах, только против существ."
|
||||||
|
},
|
||||||
|
"CoaBots.Scaling.World": {
|
||||||
|
"t": "В открытом мире",
|
||||||
|
"d": "Применять множители вне подземелий и рейдов."
|
||||||
|
},
|
||||||
|
"CoaBots.Scaling.DamageDone": {
|
||||||
|
"t": "Урон ботов",
|
||||||
|
"d": "Урон, который боты наносят монстрам. 1 — обычный, 1,5 — в полтора раза больше."
|
||||||
|
},
|
||||||
|
"CoaBots.Scaling.HealingDone": {
|
||||||
|
"t": "Лечение ботов",
|
||||||
|
"d": "Лечение, которое произносят боты. 1 — обычное."
|
||||||
|
},
|
||||||
|
"CoaBots.Scaling.DamageTaken": {
|
||||||
|
"t": "Урон по ботам",
|
||||||
|
"d": "Урон, который монстры наносят ботам. Меньше 1 — боты получают меньше; 0,7 — на 30% меньше."
|
||||||
|
},
|
||||||
|
"CoaBots.Scaling.TankThreat": {
|
||||||
|
"t": "Угроза танка-бота",
|
||||||
|
"d": "Угроза, которую создаёт бот-танк, чтобы монстры не уходили с него. 1 — обычная."
|
||||||
|
},
|
||||||
|
"CoaBots.Scaling.BossTuning": {
|
||||||
|
"t": "Дополнительная помощь против трудных боссов",
|
||||||
|
"d": "Более сильные множители для Локена, Элементаля Драккари, Колосса Драккари и Гал'дары, которых боты 60 уровня иначе не проходят."
|
||||||
|
},
|
||||||
"CoaBots.BGFill.Enable": {
|
"CoaBots.BGFill.Enable": {
|
||||||
"t": "Дополнение поля боя ботами",
|
"t": "Дополнение поля боя ботами",
|
||||||
"d": "Когда кто-то встаёт в очередь на поле боя, обе команды пополняются ботами, чтобы матч начался сразу."
|
"d": "Когда кто-то встаёт в очередь на поле боя, обе команды пополняются ботами, чтобы матч начался сразу."
|
||||||
|
|||||||
@@ -8,6 +8,7 @@
|
|||||||
"bots.quests": "任务系统",
|
"bots.quests": "任务系统",
|
||||||
"bots.combat": "战斗",
|
"bots.combat": "战斗",
|
||||||
"bots.dungeon": "地下城",
|
"bots.dungeon": "地下城",
|
||||||
|
"bots.scaling": "机器人强度",
|
||||||
"bots.battlegrounds": "战场",
|
"bots.battlegrounds": "战场",
|
||||||
"bots.social": "社交与互助",
|
"bots.social": "社交与互助",
|
||||||
"bots.advanced": "高级设置",
|
"bots.advanced": "高级设置",
|
||||||
@@ -304,6 +305,46 @@
|
|||||||
"t": "机器人自主排地下城",
|
"t": "机器人自主排地下城",
|
||||||
"d": "实验性功能:空闲的坦克机器人会自主报名排地下城,并由上述补位机制补齐队伍。"
|
"d": "实验性功能:空闲的坦克机器人会自主报名排地下城,并由上述补位机制补齐队伍。"
|
||||||
},
|
},
|
||||||
|
"CoaBots.Scaling.Enable": {
|
||||||
|
"t": "在团队内容中协助机器人",
|
||||||
|
"d": "将下列倍率应用于机器人及其宠物和图腾。所有倍率为 1 时不产生任何变化。"
|
||||||
|
},
|
||||||
|
"CoaBots.Scaling.Dungeons": {
|
||||||
|
"t": "地下城中",
|
||||||
|
"d": "在 5 人地下城中应用倍率。"
|
||||||
|
},
|
||||||
|
"CoaBots.Scaling.Raids": {
|
||||||
|
"t": "团队副本中",
|
||||||
|
"d": "在团队副本中应用倍率。"
|
||||||
|
},
|
||||||
|
"CoaBots.Scaling.Battlegrounds": {
|
||||||
|
"t": "战场和竞技场中",
|
||||||
|
"d": "在战场和竞技场中应用倍率,仅针对生物。"
|
||||||
|
},
|
||||||
|
"CoaBots.Scaling.World": {
|
||||||
|
"t": "开放世界中",
|
||||||
|
"d": "在副本以外应用倍率。"
|
||||||
|
},
|
||||||
|
"CoaBots.Scaling.DamageDone": {
|
||||||
|
"t": "机器人伤害",
|
||||||
|
"d": "机器人对怪物造成的伤害。1 为正常,1.5 为 1.5 倍。"
|
||||||
|
},
|
||||||
|
"CoaBots.Scaling.HealingDone": {
|
||||||
|
"t": "机器人治疗",
|
||||||
|
"d": "机器人施放的治疗量。1 为正常。"
|
||||||
|
},
|
||||||
|
"CoaBots.Scaling.DamageTaken": {
|
||||||
|
"t": "机器人承受的伤害",
|
||||||
|
"d": "怪物对机器人造成的伤害。低于 1 则受到更少伤害;0.7 表示减少 30%。"
|
||||||
|
},
|
||||||
|
"CoaBots.Scaling.TankThreat": {
|
||||||
|
"t": "机器人坦克仇恨",
|
||||||
|
"d": "机器人坦克产生的仇恨,使怪物保持攻击它。1 为正常。"
|
||||||
|
},
|
||||||
|
"CoaBots.Scaling.BossTuning": {
|
||||||
|
"t": "对少数困难首领的额外协助",
|
||||||
|
"d": "对洛肯、达卡莱元素、达卡莱巨像和迦尔达拉使用更强的倍率,否则 60 级机器人无法击败它们。"
|
||||||
|
},
|
||||||
"CoaBots.BGFill.Enable": {
|
"CoaBots.BGFill.Enable": {
|
||||||
"t": "战场机器人自动补位",
|
"t": "战场机器人自动补位",
|
||||||
"d": "当有玩家排战场时,双方阵营会自动填充机器人以便迅速开赛。"
|
"d": "当有玩家排战场时,双方阵营会自动填充机器人以便迅速开赛。"
|
||||||
|
|||||||
+72
-112
@@ -299,6 +299,14 @@ export interface PublicCatalogueItem {
|
|||||||
coa_status_source: string;
|
coa_status_source: string;
|
||||||
conflict_reason?: string | null;
|
conflict_reason?: string | null;
|
||||||
is_coa_recommended: boolean;
|
is_coa_recommended: boolean;
|
||||||
|
/** Functional category code; "other" when nothing fits. */
|
||||||
|
category?: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface CatalogueCategory {
|
||||||
|
code: string;
|
||||||
|
ru: string;
|
||||||
|
en: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface PublicCatalogueResponse {
|
export interface PublicCatalogueResponse {
|
||||||
@@ -308,6 +316,7 @@ export interface PublicCatalogueResponse {
|
|||||||
etag?: string | null;
|
etag?: string | null;
|
||||||
total_count: number;
|
total_count: number;
|
||||||
recommended_count: number;
|
recommended_count: number;
|
||||||
|
categories?: CatalogueCategory[];
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface CompatibilityReport {
|
export interface CompatibilityReport {
|
||||||
@@ -333,7 +342,16 @@ export interface CompatibilityReport {
|
|||||||
has_duplicate_registration: boolean;
|
has_duplicate_registration: boolean;
|
||||||
};
|
};
|
||||||
databases: Array<{ database_type: string; operation: string; file: string; line: number }>;
|
databases: Array<{ database_type: string; operation: string; file: string; line: number }>;
|
||||||
sql_files: Array<{ file_path: string; statement_count: number; tables_referenced: string[]; has_schema_mutation: boolean }>;
|
/** As the backend sends it (analyzer::SqlFileAudit). */
|
||||||
|
sql_files: Array<{
|
||||||
|
file: string;
|
||||||
|
target_schema: string;
|
||||||
|
has_create_table: boolean;
|
||||||
|
has_alter_table: boolean;
|
||||||
|
has_insert_replace: boolean;
|
||||||
|
has_delete_update: boolean;
|
||||||
|
line_count: number;
|
||||||
|
}>;
|
||||||
core_patches: string[];
|
core_patches: string[];
|
||||||
has_cmakelists: boolean;
|
has_cmakelists: boolean;
|
||||||
has_entrypoint_adapter: boolean;
|
has_entrypoint_adapter: boolean;
|
||||||
@@ -470,6 +488,32 @@ export interface AccountInfo {
|
|||||||
characters: number;
|
characters: number;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export interface BuildCacheEntry {
|
||||||
|
module: string;
|
||||||
|
bytes: number;
|
||||||
|
unpacked_bytes: number;
|
||||||
|
last_used: number;
|
||||||
|
current_core: boolean;
|
||||||
|
packed: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface BuildCacheSummary {
|
||||||
|
modules: BuildCacheEntry[];
|
||||||
|
total_bytes: number;
|
||||||
|
sources_bytes: number;
|
||||||
|
limit_bytes: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface CopyReport {
|
||||||
|
schemas: string[];
|
||||||
|
accounts: number;
|
||||||
|
characters: number;
|
||||||
|
config_files: string[];
|
||||||
|
read_from: string;
|
||||||
|
world_settings: string[];
|
||||||
|
world_settings_skipped: string[];
|
||||||
|
}
|
||||||
|
|
||||||
export interface InstallStep {
|
export interface InstallStep {
|
||||||
step: string;
|
step: string;
|
||||||
percent: number;
|
percent: number;
|
||||||
@@ -528,16 +572,6 @@ export interface CompanionSizes {
|
|||||||
sizes: { id: string; title: string; bots: number; warning: string | null }[];
|
sizes: { id: string; title: string; bots: number; warning: string | null }[];
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface WildcardArchetypeDto {
|
|
||||||
id: string;
|
|
||||||
name: string;
|
|
||||||
roles: number;
|
|
||||||
primary_stat: number;
|
|
||||||
author: string;
|
|
||||||
difficulty: number;
|
|
||||||
category: number;
|
|
||||||
}
|
|
||||||
|
|
||||||
export interface ClientInfo {
|
export interface ClientInfo {
|
||||||
path: string;
|
path: string;
|
||||||
executable: string;
|
executable: string;
|
||||||
@@ -666,73 +700,19 @@ export interface CrashItem {
|
|||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
export type SourceClassification = "CSM_MANAGED_COA" | "LEGACY_EMBEDDED_COA" | "STANDARD_AZEROTH_CORE" | "UNKNOWN_CUSTOM";
|
/** What a modular copy of a server would take, read without changing anything (`modular_copy::preview`). */
|
||||||
|
export interface CopyPreview {
|
||||||
export interface DetectedModule {
|
path: string;
|
||||||
id: string;
|
classic: boolean;
|
||||||
name: string;
|
modular: boolean;
|
||||||
detected_via: string;
|
version: string | null;
|
||||||
version?: string | null;
|
database: "running" | "stopped" | "missing";
|
||||||
has_database_data: boolean;
|
accounts: number | null;
|
||||||
is_supported_by_preview: boolean;
|
characters: number | null;
|
||||||
}
|
schemas: string[];
|
||||||
|
database_bytes: number;
|
||||||
export interface SourceInspectionReport {
|
config_files: string[];
|
||||||
source_path: string;
|
extra_worlds: string[];
|
||||||
source_type: SourceClassification;
|
|
||||||
core_version?: string | null;
|
|
||||||
schema_version?: string | null;
|
|
||||||
accounts_count: number;
|
|
||||||
characters_count: number;
|
|
||||||
detected_modules: DetectedModule[];
|
|
||||||
module_tables: Record<string, string[]>;
|
|
||||||
custom_race_support: boolean;
|
|
||||||
compatibility_notes: string[];
|
|
||||||
}
|
|
||||||
|
|
||||||
export interface MigrationScope {
|
|
||||||
accounts_and_characters: boolean;
|
|
||||||
module_owned_data: boolean;
|
|
||||||
server_configuration: boolean;
|
|
||||||
selected_modules: string[];
|
|
||||||
}
|
|
||||||
|
|
||||||
export type ConflictResolutionPolicy = "remap_colliding_guids" | "skip_colliding_guids" | "overwrite_existing";
|
|
||||||
|
|
||||||
export interface AdapterPlan {
|
|
||||||
module_id: string;
|
|
||||||
source_tables: string[];
|
|
||||||
dest_tables: string[];
|
|
||||||
data_loss_risks: string[];
|
|
||||||
requires_conversion: boolean;
|
|
||||||
}
|
|
||||||
|
|
||||||
export interface MigrationPlan {
|
|
||||||
plan_id: string;
|
|
||||||
source_path: string;
|
|
||||||
dest_realm_path: string;
|
|
||||||
source_report: SourceInspectionReport;
|
|
||||||
scope: MigrationScope;
|
|
||||||
conflict_policy: ConflictResolutionPolicy;
|
|
||||||
adapters: AdapterPlan[];
|
|
||||||
tables_to_migrate: string[];
|
|
||||||
quarantined_tables: string[];
|
|
||||||
estimated_disk_mb: number;
|
|
||||||
warnings: string[];
|
|
||||||
}
|
|
||||||
|
|
||||||
export interface MigrationExecutionReport {
|
|
||||||
success: boolean;
|
|
||||||
backup_path?: string | null;
|
|
||||||
accounts_transferred: number;
|
|
||||||
characters_transferred: number;
|
|
||||||
items_transferred: number;
|
|
||||||
modules_migrated: string[];
|
|
||||||
tables_migrated: string[];
|
|
||||||
quarantined_tables: string[];
|
|
||||||
warnings: string[];
|
|
||||||
errors: string[];
|
|
||||||
duration_ms: number;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
export type SolverVerdict =
|
export type SolverVerdict =
|
||||||
@@ -808,7 +788,13 @@ export const api = {
|
|||||||
accountSetAccess: (id: string, name: string, level: number) => invoke<void>("account_set_access", { id, name, level }),
|
accountSetAccess: (id: string, name: string, level: number) => invoke<void>("account_set_access", { id, name, level }),
|
||||||
accountRename: (id: string, name: string, newName: string, password: string) => invoke<void>("account_rename", { id, name, newName, password }),
|
accountRename: (id: string, name: string, newName: string, password: string) => invoke<void>("account_rename", { id, name, newName, password }),
|
||||||
accountDelete: (id: string, name: string) => invoke<void>("account_delete", { id, name }),
|
accountDelete: (id: string, name: string) => invoke<void>("account_delete", { id, name }),
|
||||||
installNew: (dest: string, pkg?: string, gameData?: string) => invoke<ServerSummary>("install_new", { dest, package: pkg ?? null, gameData: gameData ?? null }),
|
installNew: (dest: string, pkg?: string, gameData?: string, copyFrom?: string) =>
|
||||||
|
invoke<ServerSummary & { preview_core_error: string | null; modules_off: string[]; copied: CopyReport | null }>("install_new", { dest, package: pkg ?? null, gameData: gameData ?? null, copyFrom: copyFrom ?? null }),
|
||||||
|
isClassicServer: (path: string) => invoke<boolean>("is_classic_server", { path }),
|
||||||
|
repoLastPush: (repos: string[]) => invoke<Record<string, string | null>>("repo_last_push", { repos }),
|
||||||
|
buildCacheSummary: (id: string) => invoke<BuildCacheSummary>("build_cache_summary", { id }),
|
||||||
|
buildCacheClear: (id: string, module: string | null, sources: boolean) =>
|
||||||
|
invoke<number>("build_cache_clear", { id, module, sources }),
|
||||||
cancelInstall: () => invoke<void>("cancel_install"),
|
cancelInstall: () => invoke<void>("cancel_install"),
|
||||||
createAccount: (id: string, username: string, password: string, administrator: boolean) =>
|
createAccount: (id: string, username: string, password: string, administrator: boolean) =>
|
||||||
invoke<void>("create_account", { id, username, password, administrator }),
|
invoke<void>("create_account", { id, username, password, administrator }),
|
||||||
@@ -822,35 +808,15 @@ export const api = {
|
|||||||
invoke<{ txn: UpdateTxn; preexisting_character_count?: number; modules?: ModuleRebuild[] }>("apply_update", { id, source: source ?? null, resolutions }),
|
invoke<{ txn: UpdateTxn; preexisting_character_count?: number; modules?: ModuleRebuild[] }>("apply_update", { id, source: source ?? null, resolutions }),
|
||||||
rollbackUpdate: (id: string, txn: string) => invoke<UpdateTxn>("rollback_update", { id, txn }),
|
rollbackUpdate: (id: string, txn: string) => invoke<UpdateTxn>("rollback_update", { id, txn }),
|
||||||
retryUpdateValidation: (id: string, txn: string) => invoke<UpdateTxn>("retry_update_validation", { id, txn }),
|
retryUpdateValidation: (id: string, txn: string) => invoke<UpdateTxn>("retry_update_validation", { id, txn }),
|
||||||
population: (id: string, realm?: RealmMode) => invoke<Population | null>("get_population", { id, realm: realm ?? null }),
|
population: (id: string) => invoke<Population | null>("get_population", { id }),
|
||||||
stopSpawning: (id: string, realm?: RealmMode) => invoke<{ count: number }>("companions_stop_spawning", { id, realm: realm ?? null }),
|
stopSpawning: (id: string) => invoke<{ count: number }>("companions_stop_spawning", { id }),
|
||||||
takeOffline: (id: string, realm?: RealmMode) => invoke<{ count: number }>("companions_take_offline", { id, realm: realm ?? null }),
|
takeOffline: (id: string) => invoke<{ count: number }>("companions_take_offline", { id }),
|
||||||
despawnSome: (id: string, count: number, realm?: RealmMode) => invoke<{ count: number }>("companions_despawn_some", { id, count, realm: realm ?? null }),
|
despawnSome: (id: string, count: number) => invoke<{ count: number }>("companions_despawn_some", { id, count }),
|
||||||
deleteAllCompanions: (id: string, realm?: RealmMode) => invoke<{ count: number }>("companions_delete_all", { id, realm: realm ?? null }),
|
deleteAllCompanions: (id: string) => invoke<{ count: number }>("companions_delete_all", { id }),
|
||||||
loginAllCompanions: (id: string, realm?: RealmMode) => invoke<string>("companions_login_all", { id, realm: realm ?? null }),
|
|
||||||
spawnBotFleet: (id: string, race: number, level: number, realm?: RealmMode) => invoke<string>("companions_spawn_fleet", { id, race, level, realm: realm ?? null }),
|
|
||||||
openLink: (url: string) => invoke<void>("open_link", { url }),
|
openLink: (url: string) => invoke<void>("open_link", { url }),
|
||||||
performance: (id: string) => invoke<Performance | null>("get_performance", { id }),
|
performance: (id: string) => invoke<Performance | null>("get_performance", { id }),
|
||||||
companionSizes: () => invoke<CompanionSizes>("companion_sizes"),
|
companionSizes: () => invoke<CompanionSizes>("companion_sizes"),
|
||||||
addCompanions: (
|
addCompanions: (id: string, count: number) => invoke<{ spawned: string | null; created: number | null; baseline: number | null }>("add_companions", { id, count }),
|
||||||
id: string,
|
|
||||||
count: number,
|
|
||||||
realm?: RealmMode,
|
|
||||||
level?: number,
|
|
||||||
classId?: number,
|
|
||||||
specId?: number,
|
|
||||||
archetype?: string
|
|
||||||
) =>
|
|
||||||
invoke<{ spawned: string | null; created: number | null; baseline: number | null }>("add_companions", {
|
|
||||||
id,
|
|
||||||
count,
|
|
||||||
realm: realm ?? null,
|
|
||||||
level: level ?? null,
|
|
||||||
class_id: classId ?? null,
|
|
||||||
spec_id: specId ?? null,
|
|
||||||
archetype: archetype ?? null,
|
|
||||||
}),
|
|
||||||
getWildcardArchetypes: (id: string) => invoke<WildcardArchetypeDto[]>("get_wildcard_archetypes", { id }),
|
|
||||||
clientGraphics: (id: string) => invoke<{ dxvk_disabled: boolean; enhancements_disabled: boolean }>("client_graphics", { id }),
|
clientGraphics: (id: string) => invoke<{ dxvk_disabled: boolean; enhancements_disabled: boolean }>("client_graphics", { id }),
|
||||||
clientSetGraphics: (id: string, name: string, disabled: boolean) => invoke<{ dxvk_disabled: boolean; enhancements_disabled: boolean }>("client_set_graphics", { id, name, disabled }),
|
clientSetGraphics: (id: string, name: string, disabled: boolean) => invoke<{ dxvk_disabled: boolean; enhancements_disabled: boolean }>("client_set_graphics", { id, name, disabled }),
|
||||||
clientInfo: (id: string) => invoke<ClientInfo | null>("client_info", { id }),
|
clientInfo: (id: string) => invoke<ClientInfo | null>("client_info", { id }),
|
||||||
@@ -889,7 +855,6 @@ export const api = {
|
|||||||
invoke<{ ready: boolean; restart_required: boolean; message: string; toolchain: ToolchainStatus }>("preview_install_msvc", { realmId: realmId ?? null }),
|
invoke<{ ready: boolean; restart_required: boolean; message: string; toolchain: ToolchainStatus }>("preview_install_msvc", { realmId: realmId ?? null }),
|
||||||
previewToolchainStatus: (realmId?: string) =>
|
previewToolchainStatus: (realmId?: string) =>
|
||||||
invoke<ToolchainStatus>("preview_toolchain_status", { realmId: realmId ?? null }),
|
invoke<ToolchainStatus>("preview_toolchain_status", { realmId: realmId ?? null }),
|
||||||
previewRegisterTestRealm: (path?: string) => invoke<ServerSummary>("preview_register_test_realm", { path: path ?? null }),
|
|
||||||
previewBuildModule: (realmId: string, sourceUrlOrPath: string) =>
|
previewBuildModule: (realmId: string, sourceUrlOrPath: string) =>
|
||||||
invoke<BuildResult>("preview_build_module", { realmId, sourceUrlOrPath }),
|
invoke<BuildResult>("preview_build_module", { realmId, sourceUrlOrPath }),
|
||||||
previewInstallModule: (realmId: string, moduleId: string, version: string, applySql: boolean) =>
|
previewInstallModule: (realmId: string, moduleId: string, version: string, applySql: boolean) =>
|
||||||
@@ -902,12 +867,7 @@ export const api = {
|
|||||||
invoke<InstalledPreviewPlugin[]>("preview_list_installed_plugins", { realmId }),
|
invoke<InstalledPreviewPlugin[]>("preview_list_installed_plugins", { realmId }),
|
||||||
previewExportDiagnostics: (realmId?: string) =>
|
previewExportDiagnostics: (realmId?: string) =>
|
||||||
invoke<string>("preview_export_diagnostics", { realmId: realmId ?? null }),
|
invoke<string>("preview_export_diagnostics", { realmId: realmId ?? null }),
|
||||||
previewMigrationInspect: (sourcePath: string) =>
|
modularCopyPreview: (path: string) => invoke<CopyPreview>("modular_copy_preview", { path }),
|
||||||
invoke<SourceInspectionReport>("preview_migration_inspect", { sourcePath }),
|
|
||||||
previewMigrationPlan: (sourcePath: string, destRealmId: string, scope: MigrationScope, conflictPolicy: ConflictResolutionPolicy) =>
|
|
||||||
invoke<MigrationPlan>("preview_migration_plan", { sourcePath, destRealmId, scope, conflictPolicy }),
|
|
||||||
previewMigrationExecute: (plan: MigrationPlan) =>
|
|
||||||
invoke<MigrationExecutionReport>("preview_migration_execute", { plan }),
|
|
||||||
previewCheckUpdates: (realmId: string) =>
|
previewCheckUpdates: (realmId: string) =>
|
||||||
invoke<SolverVerdict>("preview_check_updates", { realmId }),
|
invoke<SolverVerdict>("preview_check_updates", { realmId }),
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -0,0 +1,121 @@
|
|||||||
|
import { useCallback, useEffect, useState } from "react";
|
||||||
|
import { Loader2, Trash2, X } from "lucide-react";
|
||||||
|
import { api, asUiError, type BuildCacheSummary } from "@/lib/api";
|
||||||
|
import { formatBytes } from "@/lib/utils";
|
||||||
|
import { Button } from "@/components/ui/button";
|
||||||
|
import { Card } from "@/components/ui/card";
|
||||||
|
|
||||||
|
/** What the module build cache takes, with removal of one module, all modules, or the downloaded sources. */
|
||||||
|
export function BuildCacheDialog(props: { serverId: string; locale: string; onClose: () => void }) {
|
||||||
|
const ru = props.locale === "ru";
|
||||||
|
const [summary, setSummary] = useState<BuildCacheSummary | null>(null);
|
||||||
|
const [busy, setBusy] = useState<string | null>(null);
|
||||||
|
const [message, setMessage] = useState<string | null>(null);
|
||||||
|
const [error, setError] = useState<string | null>(null);
|
||||||
|
|
||||||
|
const load = useCallback(() => {
|
||||||
|
void api
|
||||||
|
.buildCacheSummary(props.serverId)
|
||||||
|
.then(setSummary)
|
||||||
|
.catch((e) => setError(asUiError(e).technical));
|
||||||
|
}, [props.serverId]);
|
||||||
|
useEffect(load, [load]);
|
||||||
|
|
||||||
|
async function clear(key: string, module: string | null, sources: boolean) {
|
||||||
|
setBusy(key);
|
||||||
|
setError(null);
|
||||||
|
try {
|
||||||
|
const freed = await api.buildCacheClear(props.serverId, module, sources);
|
||||||
|
setMessage(ru ? `Освобождено ${formatBytes(freed)}` : `Freed ${formatBytes(freed)}`);
|
||||||
|
load();
|
||||||
|
} catch (e) {
|
||||||
|
setError(asUiError(e).technical);
|
||||||
|
} finally {
|
||||||
|
setBusy(null);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const when = (secs: number) =>
|
||||||
|
secs > 0 ? new Date(secs * 1000).toLocaleDateString(ru ? "ru-RU" : undefined, { day: "numeric", month: "short" }) : "—";
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="fixed inset-0 z-50 flex items-center justify-center bg-black/60 p-4" role="dialog" aria-modal aria-label={ru ? "Кэш сборок" : "Build cache"}>
|
||||||
|
<Card className="w-full max-w-lg space-y-4 border-line bg-card p-5 shadow-2xl">
|
||||||
|
<div className="flex items-start justify-between gap-3">
|
||||||
|
<div>
|
||||||
|
<h3 className="text-base font-semibold text-ink">{ru ? "Кэш сборок" : "Build cache"}</h3>
|
||||||
|
<p className="mt-1 text-xs text-muted">
|
||||||
|
{ru
|
||||||
|
? "Скомпилированные части модулей хранятся сжатыми и ускоряют повторную сборку. После обновления ядра старый кэш удаляется сам. Удаление ничего не ломает: следующая сборка модуля будет полной."
|
||||||
|
: "Compiled parts of modules are kept compressed and speed up the next build. After a core update the old cache goes by itself. Removing it breaks nothing: the next build of a module is a full one."}
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
<button onClick={props.onClose} className="text-muted hover:text-ink" aria-label={ru ? "Закрыть" : "Close"}>
|
||||||
|
<X className="h-4 w-4" />
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{!summary && !error && <Loader2 className="h-4 w-4 animate-spin text-gold" />}
|
||||||
|
|
||||||
|
{summary && (
|
||||||
|
<>
|
||||||
|
<div className="divide-y divide-line rounded border border-line text-sm">
|
||||||
|
{summary.modules.length === 0 && <p className="p-3 text-xs text-muted">{ru ? "Кэш пуст." : "The cache is empty."}</p>}
|
||||||
|
{summary.modules.map((m) => (
|
||||||
|
<div key={m.module} className="flex items-center gap-3 px-3 py-2">
|
||||||
|
<div className="min-w-0 flex-1">
|
||||||
|
<p className="truncate font-medium text-ink">{m.module}</p>
|
||||||
|
<p className="text-[11px] text-muted">
|
||||||
|
{m.packed
|
||||||
|
? ru ? `сжато из ${formatBytes(m.unpacked_bytes)}` : `packed from ${formatBytes(m.unpacked_bytes)}`
|
||||||
|
: ru ? "не сжато" : "not packed"}
|
||||||
|
{" · "}
|
||||||
|
{ru ? "сборка " : "built "}
|
||||||
|
{when(m.last_used)}
|
||||||
|
{!m.current_core && (ru ? " · для другого ядра" : " · for another core")}
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
<span className="text-xs tabular-nums text-muted">{formatBytes(m.bytes)}</span>
|
||||||
|
<Button
|
||||||
|
size="sm"
|
||||||
|
variant="ghost"
|
||||||
|
disabled={busy !== null}
|
||||||
|
onClick={() => void clear(m.module, m.module, false)}
|
||||||
|
aria-label={ru ? `Удалить кэш ${m.module}` : `Remove the cache of ${m.module}`}
|
||||||
|
className="h-7 w-7 p-0 text-muted hover:text-bad"
|
||||||
|
>
|
||||||
|
{busy === m.module ? <Loader2 className="h-3.5 w-3.5 animate-spin" /> : <Trash2 className="h-3.5 w-3.5" />}
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="flex items-center justify-between text-xs text-muted">
|
||||||
|
<span>
|
||||||
|
{ru ? "Скачанные исходники модулей" : "Downloaded module sources"}: {formatBytes(summary.sources_bytes)}
|
||||||
|
</span>
|
||||||
|
<Button size="sm" variant="ghost" disabled={busy !== null || summary.sources_bytes === 0} onClick={() => void clear("sources", null, true)} className="h-7 text-xs">
|
||||||
|
{busy === "sources" ? <Loader2 className="mr-1 h-3.5 w-3.5 animate-spin" /> : null}
|
||||||
|
{ru ? "Удалить" : "Remove"}
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="flex items-center justify-between border-t border-line pt-3">
|
||||||
|
<span className="text-xs text-muted">
|
||||||
|
{ru ? "Всего" : "Total"}: {formatBytes(summary.total_bytes)}
|
||||||
|
{ru ? `, предел ${formatBytes(summary.limit_bytes)}` : `, limit ${formatBytes(summary.limit_bytes)}`}
|
||||||
|
</span>
|
||||||
|
<Button size="sm" variant="ghost" disabled={busy !== null || summary.modules.length === 0} onClick={() => void clear("all", null, false)} className="h-7 border border-line text-xs">
|
||||||
|
{busy === "all" ? <Loader2 className="mr-1 h-3.5 w-3.5 animate-spin" /> : <Trash2 className="mr-1 h-3.5 w-3.5" />}
|
||||||
|
{ru ? "Удалить весь кэш сборок" : "Remove the whole build cache"}
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{message && <p className="text-xs text-ok" role="status">{message}</p>}
|
||||||
|
{error && <p className="text-xs text-bad" role="alert">{error}</p>}
|
||||||
|
</Card>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
+159
-712
@@ -1,125 +1,30 @@
|
|||||||
import { useEffect, useState } from "react";
|
import { useEffect, useState } from "react";
|
||||||
import {
|
import { Loader2 } from "lucide-react";
|
||||||
Loader2,
|
import { api, asUiError, type CompanionSizes, type Population, type UiError } from "@/lib/api";
|
||||||
Bot,
|
|
||||||
CheckCircle2,
|
|
||||||
AlertCircle,
|
|
||||||
RefreshCw,
|
|
||||||
Power,
|
|
||||||
Users,
|
|
||||||
Database,
|
|
||||||
} from "lucide-react";
|
|
||||||
import {
|
|
||||||
api,
|
|
||||||
asUiError,
|
|
||||||
type Population,
|
|
||||||
type RealmMode,
|
|
||||||
type RealmProfiles,
|
|
||||||
type UiError,
|
|
||||||
type WildcardArchetypeDto,
|
|
||||||
} from "@/lib/api";
|
|
||||||
import { Button } from "@/components/ui/button";
|
import { Button } from "@/components/ui/button";
|
||||||
import { Card } from "@/components/ui/card";
|
import { Card } from "@/components/ui/card";
|
||||||
import { useHuman, useT } from "@/i18n";
|
import { hasKey, useHuman, useT, type Key } from "@/i18n";
|
||||||
|
|
||||||
function formatRole(roles: number): string {
|
|
||||||
const parts: string[] = [];
|
|
||||||
if (roles & 1) parts.push("Tank");
|
|
||||||
if (roles & 2) parts.push("Melee");
|
|
||||||
if (roles & 4) parts.push("Ranged");
|
|
||||||
if (roles & 8) parts.push("Healer");
|
|
||||||
return parts.join("/") || "DPS";
|
|
||||||
}
|
|
||||||
|
|
||||||
function formatStat(stat: number): string {
|
|
||||||
switch (stat) {
|
|
||||||
case 0: return "Strength";
|
|
||||||
case 1: return "Agility";
|
|
||||||
case 2: return "Stamina";
|
|
||||||
case 3: return "Intellect";
|
|
||||||
case 4: return "Spirit";
|
|
||||||
default: return "All";
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
export function CompanionsCard({ serverId }: { serverId: string }) {
|
export function CompanionsCard({ serverId }: { serverId: string }) {
|
||||||
const t = useT();
|
const t = useT();
|
||||||
const human = useHuman();
|
const human = useHuman();
|
||||||
|
const [sizes, setSizes] = useState<CompanionSizes | null>(null);
|
||||||
// Realm & Environment state
|
|
||||||
const [profiles, setProfiles] = useState<RealmProfiles | null>(null);
|
|
||||||
const [selectedRealm, setSelectedRealm] = useState<RealmMode>("coa");
|
|
||||||
const [pop, setPop] = useState<Population | null>(null);
|
const [pop, setPop] = useState<Population | null>(null);
|
||||||
const [running, setRunning] = useState(false);
|
const [running, setRunning] = useState(false);
|
||||||
|
const [choice, setChoice] = useState<string>("small");
|
||||||
// Fleet Configuration state
|
const [custom, setCustom] = useState("100");
|
||||||
const [spawnMode, setSpawnMode] = useState<"population" | "fleet">("population");
|
|
||||||
const [countChoice, setCountChoice] = useState<string>("50");
|
|
||||||
const [customCount, setCustomCount] = useState<string>("50");
|
|
||||||
const [targetLevel, setTargetLevel] = useState<number>(80);
|
|
||||||
const [selectedClass, setSelectedClass] = useState<string>("all");
|
|
||||||
const [selectedRole, setSelectedRole] = useState<string>("all");
|
|
||||||
const [selectedArchetype, setSelectedArchetype] = useState<string>("all");
|
|
||||||
const [wildcardArchetypes, setWildcardArchetypes] = useState<WildcardArchetypeDto[]>([]);
|
|
||||||
|
|
||||||
// Operational state
|
|
||||||
const [busy, setBusy] = useState(false);
|
const [busy, setBusy] = useState(false);
|
||||||
const [error, setError] = useState<UiError | null>(null);
|
const [error, setError] = useState<UiError | null>(null);
|
||||||
const [note, setNote] = useState<string | null>(null);
|
const [note, setNote] = useState<string | null>(null);
|
||||||
const [job, setJob] = useState<{ baseline: number; target: number; since: number } | null>(null);
|
// Start-up login: how many existing bots the server brings online by itself every time it starts.
|
||||||
|
|
||||||
// Startup Auto-Login settings
|
|
||||||
const [autoOn, setAutoOn] = useState(true);
|
const [autoOn, setAutoOn] = useState(true);
|
||||||
const [autoMax, setAutoMax] = useState("");
|
const [autoMax, setAutoMax] = useState("");
|
||||||
|
// A creation that is still in progress on the running server: how many existed before and how many were asked for.
|
||||||
|
const [job, setJob] = useState<{ baseline: number; target: number; since: number } | null>(null);
|
||||||
const [startNote, setStartNote] = useState<string | null>(null);
|
const [startNote, setStartNote] = useState<string | null>(null);
|
||||||
const [startBusy, setStartBusy] = useState(false);
|
const [startBusy, setStartBusy] = useState(false);
|
||||||
const [despawnN, setDespawnN] = useState("10");
|
const [despawnN, setDespawnN] = useState("10");
|
||||||
|
|
||||||
const activeServerRealm = profiles?.active ?? "coa";
|
|
||||||
const isViewingActiveRealm = selectedRealm === activeServerRealm;
|
|
||||||
const isRealmOperational = isViewingActiveRealm || running;
|
|
||||||
|
|
||||||
const maxLevelForRealm = 60;
|
|
||||||
|
|
||||||
// Load realm profiles
|
|
||||||
const loadProfiles = async () => {
|
|
||||||
try {
|
|
||||||
const r = await api.realmProfiles(serverId);
|
|
||||||
setProfiles(r);
|
|
||||||
if (!selectedRealm) {
|
|
||||||
setSelectedRealm(r.active);
|
|
||||||
}
|
|
||||||
} catch {
|
|
||||||
// ignore
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
useEffect(() => {
|
|
||||||
void loadProfiles();
|
|
||||||
}, [serverId]);
|
|
||||||
|
|
||||||
// Adjust target level if realm changed
|
|
||||||
useEffect(() => {
|
|
||||||
if (targetLevel > maxLevelForRealm) {
|
|
||||||
setTargetLevel(maxLevelForRealm);
|
|
||||||
}
|
|
||||||
}, [selectedRealm, maxLevelForRealm, targetLevel]);
|
|
||||||
|
|
||||||
// Load wildcard archetypes dynamically from target characters db
|
|
||||||
useEffect(() => {
|
|
||||||
if (selectedRealm === "wildcard") {
|
|
||||||
api.getWildcardArchetypes(serverId)
|
|
||||||
.then((archs) => setWildcardArchetypes(archs))
|
|
||||||
.catch(() => {});
|
|
||||||
if (selectedClass === "all") {
|
|
||||||
setSelectedClass("10");
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
setSelectedArchetype("all");
|
|
||||||
}
|
|
||||||
}, [serverId, selectedRealm]);
|
|
||||||
|
|
||||||
// Load startup settings
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
void api
|
void api
|
||||||
.settings(serverId, "bots")
|
.settings(serverId, "bots")
|
||||||
@@ -135,46 +40,6 @@ export function CompanionsCard({ serverId }: { serverId: string }) {
|
|||||||
const maxNum = Number(autoMax);
|
const maxNum = Number(autoMax);
|
||||||
const maxValid = autoMax.trim() !== "" && Number.isInteger(maxNum) && maxNum >= 0 && maxNum <= 5000;
|
const maxValid = autoMax.trim() !== "" && Number.isInteger(maxNum) && maxNum >= 0 && maxNum <= 5000;
|
||||||
|
|
||||||
// Polling population
|
|
||||||
const fetchPopulation = async () => {
|
|
||||||
const s = await api.status(serverId).catch(() => null);
|
|
||||||
if (!s) return;
|
|
||||||
const up = s.observed.world.state === "running";
|
|
||||||
setRunning(up);
|
|
||||||
if (up) {
|
|
||||||
const p = await api.population(serverId, selectedRealm).catch(() => null);
|
|
||||||
setPop(p);
|
|
||||||
} else {
|
|
||||||
setPop(null);
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
useEffect(() => {
|
|
||||||
let alive = true;
|
|
||||||
const poll = async () => {
|
|
||||||
if (!alive) return;
|
|
||||||
await fetchPopulation();
|
|
||||||
};
|
|
||||||
void poll();
|
|
||||||
const interval = setInterval(poll, job ? 1500 : 4000);
|
|
||||||
return () => {
|
|
||||||
alive = false;
|
|
||||||
clearInterval(interval);
|
|
||||||
};
|
|
||||||
}, [serverId, selectedRealm, job !== null]); // eslint-disable-line react-hooks/exhaustive-deps
|
|
||||||
|
|
||||||
const done = job && pop ? Math.max(0, Math.min(job.target, pop.bots_total - job.baseline)) : 0;
|
|
||||||
useEffect(() => {
|
|
||||||
if (!job) return;
|
|
||||||
if ((pop && done >= job.target) || !running) {
|
|
||||||
if (pop && done >= job.target) setNote(t("comp.progressDone", { n: job.target }));
|
|
||||||
setJob(null);
|
|
||||||
}
|
|
||||||
}, [done, running]); // eslint-disable-line react-hooks/exhaustive-deps
|
|
||||||
|
|
||||||
const count = countChoice === "custom" ? Number(customCount) : Number(countChoice);
|
|
||||||
const valid = Number.isInteger(count) && count >= 1 && count <= 2000;
|
|
||||||
|
|
||||||
async function act(fn: () => Promise<string>) {
|
async function act(fn: () => Promise<string>) {
|
||||||
setBusy(true);
|
setBusy(true);
|
||||||
setError(null);
|
setError(null);
|
||||||
@@ -187,128 +52,45 @@ export function CompanionsCard({ serverId }: { serverId: string }) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Primary action: Spawn bots / fleet
|
|
||||||
const handleSpawn = async () => {
|
|
||||||
if (!valid) return;
|
|
||||||
setBusy(true);
|
|
||||||
setError(null);
|
|
||||||
setNote(null);
|
|
||||||
try {
|
|
||||||
if (spawnMode === "fleet") {
|
|
||||||
const race = 1;
|
|
||||||
const out = await api.spawnBotFleet(serverId, race, targetLevel, selectedRealm);
|
|
||||||
setNote(out || `Spawned level ${targetLevel} fleet`);
|
|
||||||
} else {
|
|
||||||
const classNum = selectedClass !== "all" ? parseInt(selectedClass, 10) : (selectedRealm === "wildcard" ? 10 : undefined);
|
|
||||||
let specNum: number | undefined = undefined;
|
|
||||||
if (selectedRole === "tank") {
|
|
||||||
if (selectedRealm === "reborn") {
|
|
||||||
specNum = (classNum === 7 || classNum === 9 || classNum === 11) ? 4 : (classNum === 2 ? 2 : classNum === 1 ? 3 : 1);
|
|
||||||
} else if (selectedRealm === "wildcard") {
|
|
||||||
specNum = 1;
|
|
||||||
}
|
|
||||||
} else if (selectedRole === "healer") {
|
|
||||||
if (selectedRealm === "reborn") {
|
|
||||||
specNum = (classNum === 2 || classNum === 5) ? 1 : (classNum === 7 || classNum === 11 ? 3 : 1);
|
|
||||||
} else if (selectedRealm === "wildcard") {
|
|
||||||
specNum = 2;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
const archStr = selectedArchetype !== "all" ? selectedArchetype : undefined;
|
|
||||||
const r = await api.addCompanions(serverId, count, selectedRealm, targetLevel, classNum, specNum, archStr);
|
|
||||||
if (r.spawned && r.baseline !== null) {
|
|
||||||
setJob({ baseline: r.baseline, target: count, since: Date.now() });
|
|
||||||
}
|
|
||||||
setNote(
|
|
||||||
r.created
|
|
||||||
? t("comp.offlineDone", { n: r.created })
|
|
||||||
: r.spawned
|
|
||||||
? t("comp.spawned", { n: count })
|
|
||||||
: t("comp.saved", { n: count })
|
|
||||||
);
|
|
||||||
}
|
|
||||||
await fetchPopulation();
|
|
||||||
} catch (e) {
|
|
||||||
setError(asUiError(e));
|
|
||||||
} finally {
|
|
||||||
setBusy(false);
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
// Bring offline bots online
|
|
||||||
const handleLoginAll = () =>
|
|
||||||
act(async () => {
|
|
||||||
const out = await api.loginAllCompanions(serverId, selectedRealm);
|
|
||||||
await fetchPopulation();
|
|
||||||
return out || "All available offline bots queued for login.";
|
|
||||||
});
|
|
||||||
|
|
||||||
// Stop queued creations
|
|
||||||
const stopCreating = () =>
|
const stopCreating = () =>
|
||||||
act(async () => {
|
act(async () => {
|
||||||
const r = await api.stopSpawning(serverId, selectedRealm);
|
const r = await api.stopSpawning(serverId);
|
||||||
setJob(null);
|
setJob(null);
|
||||||
await fetchPopulation();
|
|
||||||
return t("comp.stopped", { n: r.count });
|
return t("comp.stopped", { n: r.count });
|
||||||
});
|
});
|
||||||
|
|
||||||
// Take online bots offline
|
|
||||||
const takeOffline = () => {
|
const takeOffline = () => {
|
||||||
if (!window.confirm(t("comp.offlineConfirm"))) return;
|
if (!window.confirm(t("comp.offlineConfirm"))) return;
|
||||||
void act(async () => {
|
void act(async () => {
|
||||||
const r = await api.takeOffline(serverId, selectedRealm);
|
const r = await api.takeOffline(serverId);
|
||||||
setJob(null);
|
setJob(null);
|
||||||
await fetchPopulation();
|
|
||||||
return t("comp.offlineDone2", { n: r.count });
|
return t("comp.offlineDone2", { n: r.count });
|
||||||
});
|
});
|
||||||
};
|
};
|
||||||
|
|
||||||
// Despawn batch
|
|
||||||
const dn = Number(despawnN);
|
const dn = Number(despawnN);
|
||||||
const dnValid = Number.isInteger(dn) && dn >= 1 && dn <= 5000;
|
const dnValid = Number.isInteger(dn) && dn >= 1 && dn <= 5000;
|
||||||
const despawnSome = () =>
|
const despawnSome = () =>
|
||||||
act(async () => {
|
act(async () => {
|
||||||
const r = await api.despawnSome(serverId, dn, selectedRealm);
|
const r = await api.despawnSome(serverId, dn);
|
||||||
await fetchPopulation();
|
|
||||||
return t("comp.despawnSomeDone", { n: r.count });
|
return t("comp.despawnSomeDone", { n: r.count });
|
||||||
});
|
});
|
||||||
|
|
||||||
// Delete all bots in realm
|
|
||||||
const deleteAll = () => {
|
const deleteAll = () => {
|
||||||
if (!window.confirm(t("comp.deleteConfirm", { n: pop?.bots_total ?? 0 }))) return;
|
if (!window.confirm(t("comp.deleteConfirm", { n: pop?.bots_total ?? 0 }))) return;
|
||||||
void act(async () => {
|
void act(async () => {
|
||||||
await api.deleteAllCompanions(serverId, selectedRealm);
|
await api.deleteAllCompanions(serverId);
|
||||||
setJob(null);
|
setJob(null);
|
||||||
await fetchPopulation();
|
|
||||||
return t("comp.deleteDone");
|
return t("comp.deleteDone");
|
||||||
});
|
});
|
||||||
};
|
};
|
||||||
|
|
||||||
// Switch server realm
|
|
||||||
const switchServerRealm = async (mode: RealmMode) => {
|
|
||||||
if (!window.confirm(`Switch server active realm to ${mode.toUpperCase()} and restart?`)) return;
|
|
||||||
setBusy(true);
|
|
||||||
try {
|
|
||||||
await api.realmSelect(serverId, mode, true);
|
|
||||||
await loadProfiles();
|
|
||||||
setSelectedRealm(mode);
|
|
||||||
} catch (e) {
|
|
||||||
setError(asUiError(e));
|
|
||||||
} finally {
|
|
||||||
setBusy(false);
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
// Save auto startup settings
|
|
||||||
async function saveStart() {
|
async function saveStart() {
|
||||||
setStartBusy(true);
|
setStartBusy(true);
|
||||||
setError(null);
|
setError(null);
|
||||||
setStartNote(null);
|
setStartNote(null);
|
||||||
try {
|
try {
|
||||||
await api.save(serverId, "bots", {
|
await api.save(serverId, "bots", { "CoaBots.AutoLoginOnStartup": autoOn, "CoaBots.AutoLogin.MaxCount": maxNum });
|
||||||
"CoaBots.AutoLoginOnStartup": autoOn,
|
|
||||||
"CoaBots.AutoLogin.MaxCount": maxNum,
|
|
||||||
});
|
|
||||||
setStartNote(t("comp.startSaved"));
|
setStartNote(t("comp.startSaved"));
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
setError(asUiError(e));
|
setError(asUiError(e));
|
||||||
@@ -317,516 +99,181 @@ export function CompanionsCard({ serverId }: { serverId: string }) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Database schema name for selected realm
|
useEffect(() => {
|
||||||
const dbSchema =
|
void api.companionSizes().then(setSizes);
|
||||||
selectedRealm === "coa"
|
let alive = true;
|
||||||
? "acore_characters"
|
const poll = async () => {
|
||||||
: selectedRealm === "wildcard"
|
const s = await api.status(serverId).catch(() => null);
|
||||||
? "acore_characters_wildcard"
|
if (!alive || !s) return;
|
||||||
: "acore_characters_reborn";
|
const up = s.observed.world.state === "running";
|
||||||
|
setRunning(up);
|
||||||
|
setPop(up ? await api.population(serverId).catch(() => null) : null);
|
||||||
|
};
|
||||||
|
void poll();
|
||||||
|
// Faster while companions are being created, so the progress bar moves.
|
||||||
|
const t = setInterval(poll, job ? 1500 : 4000);
|
||||||
|
return () => {
|
||||||
|
alive = false;
|
||||||
|
clearInterval(t);
|
||||||
|
};
|
||||||
|
}, [serverId, job !== null]); // eslint-disable-line react-hooks/exhaustive-deps
|
||||||
|
|
||||||
// Binary compatibility check
|
const done = job && pop ? Math.max(0, Math.min(job.target, pop.bots_total - job.baseline)) : 0;
|
||||||
const isBinaryCompatible =
|
useEffect(() => {
|
||||||
selectedRealm === "coa" ||
|
if (!job) return;
|
||||||
(selectedRealm === "wildcard" && (profiles?.supported ?? true)) ||
|
// Finished, or the server went away, or nothing new appeared for two minutes.
|
||||||
(selectedRealm === "reborn" && (profiles?.reborn_supported ?? true));
|
if ((pop && done >= job.target) || !running) {
|
||||||
|
if (pop && done >= job.target) setNote(t("comp.progressDone", { n: job.target }));
|
||||||
|
setJob(null);
|
||||||
|
}
|
||||||
|
}, [done, running]); // eslint-disable-line react-hooks/exhaustive-deps
|
||||||
|
|
||||||
|
// The backend describes a size's warning in English; show the translated text for the two known kinds.
|
||||||
|
const warningFor = (size?: { bots: number; warning: string | null }) => {
|
||||||
|
if (!size?.warning) return null;
|
||||||
|
return size.warning.startsWith(`${size.bots} companions`)
|
||||||
|
? t("comp.warnHardware", { n: size.bots, cores: sizes?.hardware.cores ?? "?", ram: sizes ? sizes.hardware.ram_gb.toFixed(0) : "?" })
|
||||||
|
: t("comp.warnMemory");
|
||||||
|
};
|
||||||
|
const count = choice === "custom" ? Number(custom) : (sizes?.sizes.find((s) => s.id === choice)?.bots ?? 0);
|
||||||
|
const warning = choice === "custom" ? (count > 500 ? t("comp.largeWarning") : null) : (warningFor(sizes?.sizes.find((s) => s.id === choice)));
|
||||||
|
const valid = Number.isInteger(count) && count >= 1 && count <= 2000;
|
||||||
|
|
||||||
|
async function add() {
|
||||||
|
setBusy(true);
|
||||||
|
setError(null);
|
||||||
|
setNote(null);
|
||||||
|
try {
|
||||||
|
const r = await api.addCompanions(serverId, count);
|
||||||
|
if (r.spawned && r.baseline !== null) setJob({ baseline: r.baseline, target: count, since: Date.now() });
|
||||||
|
setNote(r.created ? t("comp.offlineDone", { n: r.created }) : r.spawned ? t("comp.spawned", { n: count }) : t("comp.saved", { n: count }));
|
||||||
|
} catch (e) {
|
||||||
|
setError(asUiError(e));
|
||||||
|
} finally {
|
||||||
|
setBusy(false);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<Card className="mt-6 p-6 space-y-6">
|
<Card className="mt-6 p-6">
|
||||||
{/* Header & Realm Switcher */}
|
<h2 className="font-semibold">{t("comp.title")}</h2>
|
||||||
<div>
|
<p className="mt-1 text-sm text-muted">
|
||||||
<div className="flex flex-wrap items-center justify-between gap-3">
|
{pop
|
||||||
<div className="flex items-center gap-2">
|
? t("comp.population", { online: pop.bots_online, total: pop.bots_total })
|
||||||
<Bot className="h-6 w-6 text-gold" />
|
: running
|
||||||
<h2 className="text-xl font-bold tracking-tight">{t("comp.title")}</h2>
|
? t("comp.reading")
|
||||||
</div>
|
: t("comp.startToSee")}
|
||||||
<div className="flex items-center gap-2">
|
</p>
|
||||||
<span className="text-xs text-muted flex items-center gap-1">
|
|
||||||
<Database className="h-3.5 w-3.5" />
|
|
||||||
DB: <code className="text-gold">{dbSchema}</code>
|
|
||||||
</span>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{/* Realm Navigation Tabs */}
|
<fieldset className="mt-4">
|
||||||
<div className="mt-4 flex flex-wrap gap-2 border-b border-line pb-3">
|
<legend className="text-sm text-muted">{t("comp.wantMore")}</legend>
|
||||||
{(["coa", "wildcard", "reborn"] as RealmMode[]).map((mode) => {
|
<div className="mt-2 flex flex-wrap gap-2">
|
||||||
const isSelected = selectedRealm === mode;
|
{sizes?.sizes.map((s) => (
|
||||||
const isActive = activeServerRealm === mode;
|
<label key={s.id} className={`cursor-pointer rounded-md border px-3 py-2 text-sm ${choice === s.id ? "border-gold bg-gold/10" : "border-line hover:bg-white/5"}`}>
|
||||||
const label =
|
<input type="radio" name="size" className="sr-only" checked={choice === s.id} onChange={() => setChoice(s.id)} />
|
||||||
mode === "coa"
|
{hasKey(`comp.size.${s.id}`) ? t(`comp.size.${s.id}` as Key) : s.title} <span className="text-muted">· {s.bots}</span>
|
||||||
? "Conquest of Azeroth"
|
</label>
|
||||||
: mode === "wildcard"
|
))}
|
||||||
? "Wildcard (Hero)"
|
<label className={`cursor-pointer rounded-md border px-3 py-2 text-sm ${choice === "custom" ? "border-gold bg-gold/10" : "border-line hover:bg-white/5"}`}>
|
||||||
: "Warcraft Reborn";
|
<input type="radio" name="size" className="sr-only" checked={choice === "custom"} onChange={() => setChoice("custom")} />
|
||||||
return (
|
{t("comp.custom")}
|
||||||
<button
|
</label>
|
||||||
key={mode}
|
{choice === "custom" && (
|
||||||
type="button"
|
<input aria-label={t("comp.numberLabel")} value={custom} onChange={(e) => setCustom(e.target.value)} inputMode="numeric" className="w-24 rounded-md border border-line bg-bg px-3 py-2 text-right text-sm outline-none focus:border-gold" />
|
||||||
onClick={() => setSelectedRealm(mode)}
|
)}
|
||||||
className={`flex items-center gap-2 rounded-lg px-4 py-2 text-sm font-medium transition-colors ${
|
|
||||||
isSelected
|
|
||||||
? "bg-gold/20 text-gold border border-gold/40 shadow-sm"
|
|
||||||
: "border border-line hover:bg-white/5 text-muted hover:text-white"
|
|
||||||
}`}
|
|
||||||
>
|
|
||||||
<span>{label}</span>
|
|
||||||
{isActive && (
|
|
||||||
<span className="rounded bg-ok/20 px-1.5 py-0.5 text-[10px] font-semibold text-ok uppercase">
|
|
||||||
Active Server
|
|
||||||
</span>
|
|
||||||
)}
|
|
||||||
</button>
|
|
||||||
);
|
|
||||||
})}
|
|
||||||
</div>
|
</div>
|
||||||
|
</fieldset>
|
||||||
|
|
||||||
|
{warning && <p className="mt-3 text-sm text-warn" role="status">{warning}</p>}
|
||||||
|
{sizes && <p className="mt-2 text-xs text-muted">{t("comp.hardware", { cores: sizes.hardware.cores, ram: sizes.hardware.ram_gb.toFixed(0) })}</p>}
|
||||||
|
|
||||||
|
<div className="mt-4 flex items-center gap-3">
|
||||||
|
<Button variant="primary" disabled={busy || !valid || job !== null} onClick={() => void add()}>
|
||||||
|
{busy && <Loader2 className="h-4 w-4 animate-spin" aria-hidden />}
|
||||||
|
{valid ? t("comp.add", { n: count }) : t("comp.addPlain")}
|
||||||
|
</Button>
|
||||||
|
{!running && <span className="text-xs text-muted">{t("comp.stoppedHint")}</span>}
|
||||||
</div>
|
</div>
|
||||||
|
{busy && !running && count >= 100 && (
|
||||||
{/* Binary Compatibility & Realm Mode Warning */}
|
<div className="mt-3">
|
||||||
{!isBinaryCompatible && (
|
<p className="text-sm text-muted" role="status">{t("comp.progressOffline", { n: count })}</p>
|
||||||
<div className="rounded-lg border border-bad/40 bg-bad/10 p-4 text-sm text-bad flex items-start gap-3">
|
<div className="mt-2 h-2 overflow-hidden rounded-full bg-white/10" role="progressbar" aria-busy="true">
|
||||||
<AlertCircle className="h-5 w-5 shrink-0 mt-0.5" />
|
<div className="h-full w-full animate-pulse rounded-full bg-gold/70" />
|
||||||
<div>
|
|
||||||
<div className="font-semibold">Binary Compatibility Warning</div>
|
|
||||||
<p className="mt-1 text-xs text-bad/90">
|
|
||||||
The currently running server core binary does not have full multi-realm support enabled
|
|
||||||
for <strong>{selectedRealm.toUpperCase()}</strong>. Automated bot features may be restricted.
|
|
||||||
</p>
|
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
|
{job && (
|
||||||
{/* Active Realm Switch Helper */}
|
<div className="mt-3">
|
||||||
{!isViewingActiveRealm && (
|
<div className="flex justify-between text-sm">
|
||||||
<div className="rounded-lg border border-warn/40 bg-warn/10 p-3 text-sm flex items-center justify-between gap-3">
|
<span role="status">{t("comp.progress", { done, target: job.target })}</span>
|
||||||
<span className="text-warn text-xs">
|
<span className="text-muted">{Math.round((done / job.target) * 100)}%</span>
|
||||||
Viewing <strong>{selectedRealm.toUpperCase()}</strong> bots, but the worldserver is currently running in{" "}
|
</div>
|
||||||
<strong>{activeServerRealm.toUpperCase()}</strong> mode.
|
<div className="mt-2 h-2 overflow-hidden rounded-full bg-white/10" role="progressbar" aria-valuenow={done} aria-valuemin={0} aria-valuemax={job.target}>
|
||||||
</span>
|
<div className="h-full rounded-full bg-gold transition-[width] duration-500" style={{ width: `${(done / job.target) * 100}%` }} />
|
||||||
<Button
|
</div>
|
||||||
size="sm"
|
{done === 0 && Date.now() - job.since > 20000 && <p className="mt-1 text-xs text-muted">{t("comp.progressStalled")}</p>}
|
||||||
variant="secondary"
|
<Button className="mt-2" size="sm" variant="ghost" disabled={busy} onClick={() => void stopCreating()}>
|
||||||
disabled={busy}
|
{t("comp.stop")}
|
||||||
onClick={() => void switchServerRealm(selectedRealm)}
|
|
||||||
>
|
|
||||||
Switch Server to {selectedRealm.toUpperCase()}
|
|
||||||
</Button>
|
</Button>
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
|
{note && !job && <p className="mt-3 text-sm text-ok" role="status">{note}</p>}
|
||||||
|
|
||||||
{/* Realm Population Dashboard */}
|
{running && pop && pop.bots_total > 0 && (
|
||||||
<div className="grid grid-cols-2 sm:grid-cols-4 gap-3">
|
<div className="mt-5 border-t border-line pt-4">
|
||||||
<div className="rounded-lg border border-line bg-bg/50 p-3">
|
<h3 className="text-sm font-semibold">{t("comp.manageTitle")}</h3>
|
||||||
<div className="text-xs text-muted flex items-center gap-1.5">
|
<div className="mt-2 flex flex-wrap items-center gap-2 text-sm">
|
||||||
<Bot className="h-3.5 w-3.5 text-gold" />
|
<label htmlFor="despawn-n" className="text-muted">{t("comp.despawnCount")}</label>
|
||||||
Bots Online
|
|
||||||
</div>
|
|
||||||
<div className="mt-1 text-2xl font-bold text-white">
|
|
||||||
{running && pop ? pop.bots_online : "—"}
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
<div className="rounded-lg border border-line bg-bg/50 p-3">
|
|
||||||
<div className="text-xs text-muted flex items-center gap-1.5">
|
|
||||||
<Users className="h-3.5 w-3.5 text-gold" />
|
|
||||||
Total Fleet
|
|
||||||
</div>
|
|
||||||
<div className="mt-1 text-2xl font-bold text-white">
|
|
||||||
{pop ? pop.bots_total : "—"}
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
<div className="rounded-lg border border-line bg-bg/50 p-3">
|
|
||||||
<div className="text-xs text-muted flex items-center gap-1.5">
|
|
||||||
<CheckCircle2 className="h-3.5 w-3.5 text-ok" />
|
|
||||||
Players Online
|
|
||||||
</div>
|
|
||||||
<div className="mt-1 text-2xl font-bold text-white">
|
|
||||||
{running && pop ? pop.players_online : "—"}
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
<div className="rounded-lg border border-line bg-bg/50 p-3 flex flex-col justify-between">
|
|
||||||
<div className="text-xs text-muted flex items-center justify-between">
|
|
||||||
<span>Status</span>
|
|
||||||
<button
|
|
||||||
onClick={() => void fetchPopulation()}
|
|
||||||
title="Refresh"
|
|
||||||
className="text-muted hover:text-white"
|
|
||||||
>
|
|
||||||
<RefreshCw className="h-3 w-3" />
|
|
||||||
</button>
|
|
||||||
</div>
|
|
||||||
<div className="text-sm font-medium">
|
|
||||||
{running ? (
|
|
||||||
<span className="text-ok flex items-center gap-1">
|
|
||||||
<span className="h-2 w-2 rounded-full bg-ok animate-pulse" /> Running
|
|
||||||
</span>
|
|
||||||
) : (
|
|
||||||
<span className="text-muted">Offline</span>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{/* Fleet Configuration & Spawning Section */}
|
|
||||||
<div className="border-t border-line pt-5 space-y-4">
|
|
||||||
<div className="flex items-center justify-between">
|
|
||||||
<h3 className="font-semibold text-sm tracking-wide uppercase text-muted">
|
|
||||||
Fleet Deployment Controls
|
|
||||||
</h3>
|
|
||||||
<div className="flex rounded-md border border-line p-0.5 text-xs">
|
|
||||||
<button
|
|
||||||
type="button"
|
|
||||||
onClick={() => setSpawnMode("population")}
|
|
||||||
className={`px-2.5 py-1 rounded transition-colors ${
|
|
||||||
spawnMode === "population" ? "bg-gold/20 text-gold font-medium" : "text-muted hover:text-white"
|
|
||||||
}`}
|
|
||||||
>
|
|
||||||
Batch Population
|
|
||||||
</button>
|
|
||||||
<button
|
|
||||||
type="button"
|
|
||||||
onClick={() => setSpawnMode("fleet")}
|
|
||||||
className={`px-2.5 py-1 rounded transition-colors ${
|
|
||||||
spawnMode === "fleet" ? "bg-gold/20 text-gold font-medium" : "text-muted hover:text-white"
|
|
||||||
}`}
|
|
||||||
>
|
|
||||||
Synchronous Fleet
|
|
||||||
</button>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{/* Count Selector */}
|
|
||||||
{spawnMode === "population" && (
|
|
||||||
<div>
|
|
||||||
<label className="text-xs text-muted">Fleet Size (Number of Bots)</label>
|
|
||||||
<div className="mt-2 flex flex-wrap gap-2">
|
|
||||||
{["10", "25", "50", "100", "250", "500"].map((n) => (
|
|
||||||
<button
|
|
||||||
key={n}
|
|
||||||
type="button"
|
|
||||||
onClick={() => setCountChoice(n)}
|
|
||||||
className={`rounded-md border px-3 py-1.5 text-sm transition-colors ${
|
|
||||||
countChoice === n
|
|
||||||
? "border-gold bg-gold/15 text-gold font-medium"
|
|
||||||
: "border-line hover:bg-white/5 text-muted"
|
|
||||||
}`}
|
|
||||||
>
|
|
||||||
{n}
|
|
||||||
</button>
|
|
||||||
))}
|
|
||||||
<button
|
|
||||||
type="button"
|
|
||||||
onClick={() => setCountChoice("custom")}
|
|
||||||
className={`rounded-md border px-3 py-1.5 text-sm transition-colors ${
|
|
||||||
countChoice === "custom"
|
|
||||||
? "border-gold bg-gold/15 text-gold font-medium"
|
|
||||||
: "border-line hover:bg-white/5 text-muted"
|
|
||||||
}`}
|
|
||||||
>
|
|
||||||
Custom
|
|
||||||
</button>
|
|
||||||
{countChoice === "custom" && (
|
|
||||||
<input
|
|
||||||
type="number"
|
|
||||||
min="1"
|
|
||||||
max="2000"
|
|
||||||
value={customCount}
|
|
||||||
onChange={(e) => setCustomCount(e.target.value)}
|
|
||||||
className="w-24 rounded-md border border-line bg-bg px-3 py-1.5 text-right text-sm outline-none focus:border-gold"
|
|
||||||
/>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
|
|
||||||
{/* Fleet Specific Settings: Level, Class, Role, Archetype */}
|
|
||||||
<div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-3">
|
|
||||||
{/* Target Level */}
|
|
||||||
<div>
|
|
||||||
<label className="text-xs text-muted">
|
|
||||||
{spawnMode === "fleet" ? "Fleet Level" : "Max Level Cap"} (1 - {maxLevelForRealm})
|
|
||||||
</label>
|
|
||||||
<input
|
|
||||||
type="number"
|
|
||||||
min="1"
|
|
||||||
max={maxLevelForRealm}
|
|
||||||
value={targetLevel}
|
|
||||||
onChange={(e) => setTargetLevel(Math.max(1, Math.min(maxLevelForRealm, Number(e.target.value))))}
|
|
||||||
className="mt-1.5 w-full rounded-md border border-line bg-bg px-3 py-1.5 text-sm outline-none focus:border-gold"
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{/* Class Filter */}
|
|
||||||
<div>
|
|
||||||
<label className="text-xs text-muted">Class Focus</label>
|
|
||||||
<select
|
|
||||||
value={selectedClass}
|
|
||||||
onChange={(e) => setSelectedClass(e.target.value)}
|
|
||||||
className="mt-1.5 w-full rounded-md border border-line bg-bg px-3 py-1.5 text-sm outline-none focus:border-gold"
|
|
||||||
>
|
|
||||||
<option value="all">All Realm Classes</option>
|
|
||||||
{selectedRealm === "coa" && (
|
|
||||||
<>
|
|
||||||
<option value="12">Barbarian</option>
|
|
||||||
<option value="13">Witch Doctor</option>
|
|
||||||
<option value="14">Felsworn</option>
|
|
||||||
<option value="15">Witch Hunter</option>
|
|
||||||
<option value="16">Stormbringer</option>
|
|
||||||
<option value="17">Knight of Xoroth</option>
|
|
||||||
<option value="18">Guardian</option>
|
|
||||||
<option value="19">Templar</option>
|
|
||||||
<option value="20">Bloodmage</option>
|
|
||||||
<option value="21">Ranger</option>
|
|
||||||
<option value="22">Chronomancer</option>
|
|
||||||
<option value="23">Necromancer</option>
|
|
||||||
<option value="24">Pyromancer</option>
|
|
||||||
<option value="25">Cultist</option>
|
|
||||||
<option value="26">Starcaller</option>
|
|
||||||
<option value="27">Tinker</option>
|
|
||||||
<option value="28">Venomancer</option>
|
|
||||||
<option value="29">Reaper</option>
|
|
||||||
<option value="30">Sun Cleric</option>
|
|
||||||
<option value="31">Runemaster</option>
|
|
||||||
<option value="32">Primalist</option>
|
|
||||||
</>
|
|
||||||
)}
|
|
||||||
{selectedRealm === "wildcard" && (
|
|
||||||
<option value="10">Hero (Freepick)</option>
|
|
||||||
)}
|
|
||||||
{selectedRealm === "reborn" && (
|
|
||||||
<>
|
|
||||||
<option value="1">Warrior</option>
|
|
||||||
<option value="2">Paladin</option>
|
|
||||||
<option value="3">Hunter</option>
|
|
||||||
<option value="4">Rogue</option>
|
|
||||||
<option value="5">Priest</option>
|
|
||||||
<option value="6">Death Knight</option>
|
|
||||||
<option value="7">Shaman</option>
|
|
||||||
<option value="8">Mage</option>
|
|
||||||
<option value="9">Warlock</option>
|
|
||||||
<option value="11">Druid</option>
|
|
||||||
</>
|
|
||||||
)}
|
|
||||||
</select>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{/* Role Filter */}
|
|
||||||
<div>
|
|
||||||
<label className="text-xs text-muted">Combat Role</label>
|
|
||||||
<select
|
|
||||||
value={selectedRole}
|
|
||||||
onChange={(e) => setSelectedRole(e.target.value)}
|
|
||||||
className="mt-1.5 w-full rounded-md border border-line bg-bg px-3 py-1.5 text-sm outline-none focus:border-gold"
|
|
||||||
>
|
|
||||||
<option value="all">All Roles</option>
|
|
||||||
<option value="tank">Tank</option>
|
|
||||||
<option value="healer">Healer</option>
|
|
||||||
<option value="melee">Melee DPS</option>
|
|
||||||
<option value="ranged">Ranged Physical DPS</option>
|
|
||||||
<option value="caster">Caster DPS</option>
|
|
||||||
</select>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{/* Archetype Filter */}
|
|
||||||
<div>
|
|
||||||
<label className="text-xs text-muted">Archetype / Build</label>
|
|
||||||
<select
|
|
||||||
value={selectedArchetype}
|
|
||||||
onChange={(e) => setSelectedArchetype(e.target.value)}
|
|
||||||
className="mt-1.5 w-full rounded-md border border-line bg-bg px-3 py-1.5 text-sm outline-none focus:border-gold"
|
|
||||||
>
|
|
||||||
<option value="all">Auto / Integral Archetype</option>
|
|
||||||
{selectedRealm === "wildcard" && (
|
|
||||||
<>
|
|
||||||
{wildcardArchetypes.map((b) => (
|
|
||||||
<option key={b.id} value={b.id}>
|
|
||||||
{b.name} ({formatRole(b.roles)}) [{formatStat(b.primary_stat)}]
|
|
||||||
</option>
|
|
||||||
))}
|
|
||||||
</>
|
|
||||||
)}
|
|
||||||
{selectedRealm === "reborn" && (
|
|
||||||
<>
|
|
||||||
<option value="spiritguard">Spirit Guard Shaman (Tank)</option>
|
|
||||||
<option value="darkapoth">Dark Apotheosis Warlock (Tank)</option>
|
|
||||||
<option value="guardianbear">Guardian Bear Druid (Tank)</option>
|
|
||||||
<option value="protpal">Protection Paladin (Tank)</option>
|
|
||||||
<option value="protwar">Protection Warrior (Tank)</option>
|
|
||||||
<option value="holypriest">Holy Priest (Healer)</option>
|
|
||||||
<option value="restodruid">Restoration Druid / Shaman</option>
|
|
||||||
</>
|
|
||||||
)}
|
|
||||||
{selectedRealm === "coa" && (
|
|
||||||
<option value="class_spec">Class Mastery Specialization</option>
|
|
||||||
)}
|
|
||||||
</select>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{/* Deployment Actions */}
|
|
||||||
<div className="flex flex-wrap items-center gap-3 pt-2">
|
|
||||||
<Button
|
|
||||||
variant="primary"
|
|
||||||
disabled={busy || !valid || job !== null || !isRealmOperational}
|
|
||||||
onClick={() => void handleSpawn()}
|
|
||||||
>
|
|
||||||
{busy && <Loader2 className="h-4 w-4 animate-spin mr-2" />}
|
|
||||||
{spawnMode === "fleet"
|
|
||||||
? `Spawn Level ${targetLevel} Fleet`
|
|
||||||
: `Deploy ${valid ? count : ""} Bots`}
|
|
||||||
</Button>
|
|
||||||
|
|
||||||
{running && pop && pop.bots_total > pop.bots_online && (
|
|
||||||
<Button
|
|
||||||
variant="secondary"
|
|
||||||
disabled={busy || job !== null || !isRealmOperational}
|
|
||||||
onClick={() => void handleLoginAll()}
|
|
||||||
title="Bring all created bots online"
|
|
||||||
>
|
|
||||||
<Power className="h-4 w-4 mr-1.5 text-ok" />
|
|
||||||
Bring All Online ({pop.bots_total - pop.bots_online} idle)
|
|
||||||
</Button>
|
|
||||||
)}
|
|
||||||
|
|
||||||
{!running && (
|
|
||||||
<span className="text-xs text-muted">
|
|
||||||
Server stopped: bots will be created directly in DB or queued for startup.
|
|
||||||
</span>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{/* Progress Bar during active spawn */}
|
|
||||||
{job && (
|
|
||||||
<div className="rounded-lg border border-line bg-bg/40 p-4 space-y-2">
|
|
||||||
<div className="flex justify-between text-sm">
|
|
||||||
<span className="font-medium">
|
|
||||||
Creating bots: {done} / {job.target}
|
|
||||||
</span>
|
|
||||||
<span className="text-gold font-bold">
|
|
||||||
{Math.round((done / job.target) * 100)}%
|
|
||||||
</span>
|
|
||||||
</div>
|
|
||||||
<div className="h-2 overflow-hidden rounded-full bg-white/10">
|
|
||||||
<div
|
|
||||||
className="h-full rounded-full bg-gold transition-[width] duration-300"
|
|
||||||
style={{ width: `${(done / job.target) * 100}%` }}
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
<div className="flex justify-between items-center pt-1">
|
|
||||||
<span className="text-xs text-muted">
|
|
||||||
Paced creation prevents server stalls and guarantees full talent/gear setup.
|
|
||||||
</span>
|
|
||||||
<Button size="sm" variant="ghost" disabled={busy} onClick={() => void stopCreating()}>
|
|
||||||
Cancel Queue
|
|
||||||
</Button>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
|
|
||||||
{note && !job && (
|
|
||||||
<p className="text-sm text-ok flex items-center gap-1.5">
|
|
||||||
<CheckCircle2 className="h-4 w-4 shrink-0" />
|
|
||||||
{note}
|
|
||||||
</p>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{/* Online Fleet Management (Despawn, Purge) */}
|
|
||||||
{running && pop && pop.bots_total > 0 && isViewingActiveRealm && (
|
|
||||||
<div className="border-t border-line pt-5 space-y-3">
|
|
||||||
<h3 className="font-semibold text-sm tracking-wide uppercase text-muted">
|
|
||||||
Online Fleet Management
|
|
||||||
</h3>
|
|
||||||
|
|
||||||
<div className="flex flex-wrap items-center gap-3 text-sm">
|
|
||||||
<label htmlFor="despawn-n" className="text-muted text-xs">
|
|
||||||
Despawn Batch:
|
|
||||||
</label>
|
|
||||||
<input
|
<input
|
||||||
id="despawn-n"
|
id="despawn-n"
|
||||||
value={despawnN}
|
value={despawnN}
|
||||||
onChange={(e) => setDespawnN(e.target.value)}
|
onChange={(e) => setDespawnN(e.target.value)}
|
||||||
inputMode="numeric"
|
inputMode="numeric"
|
||||||
aria-invalid={!dnValid}
|
aria-invalid={!dnValid}
|
||||||
className="w-20 rounded-md border border-line bg-bg px-2.5 py-1 text-right text-sm outline-none focus:border-gold"
|
className="w-20 rounded-md border border-line bg-bg px-3 py-1.5 text-right outline-none focus:border-gold"
|
||||||
/>
|
/>
|
||||||
<Button
|
<Button size="sm" variant="secondary" disabled={busy || !dnValid} onClick={() => void despawnSome()}>
|
||||||
size="sm"
|
{t("comp.despawnSome", { n: dnValid ? dn : "…" })}
|
||||||
variant="secondary"
|
|
||||||
disabled={busy || !dnValid}
|
|
||||||
onClick={() => void despawnSome()}
|
|
||||||
>
|
|
||||||
Despawn {dnValid ? dn : "…"} Bots
|
|
||||||
</Button>
|
</Button>
|
||||||
|
</div>
|
||||||
|
<p className="mt-1 text-xs text-muted">{t("comp.despawnHint")}</p>
|
||||||
|
<div className="mt-3 flex flex-wrap gap-2">
|
||||||
<Button size="sm" variant="secondary" disabled={busy} onClick={takeOffline}>
|
<Button size="sm" variant="secondary" disabled={busy} onClick={takeOffline}>
|
||||||
Take All Offline
|
{t("comp.offline")}
|
||||||
</Button>
|
</Button>
|
||||||
|
<Button size="sm" variant="ghost" className="text-bad hover:text-bad" disabled={busy} onClick={deleteAll}>
|
||||||
<Button
|
{t("comp.delete")}
|
||||||
size="sm"
|
|
||||||
variant="ghost"
|
|
||||||
className="text-bad hover:text-bad ml-auto"
|
|
||||||
disabled={busy}
|
|
||||||
onClick={deleteAll}
|
|
||||||
>
|
|
||||||
Purge Entire Fleet ({pop.bots_total})
|
|
||||||
</Button>
|
</Button>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
{/* Startup Auto-Login Configuration */}
|
<div className="mt-5 border-t border-line pt-4">
|
||||||
<div className="border-t border-line pt-5 space-y-3">
|
<h3 className="text-sm font-semibold">{t("comp.startTitle")}</h3>
|
||||||
<h3 className="font-semibold text-sm tracking-wide uppercase text-muted">
|
<label className="mt-2 flex cursor-pointer items-center gap-2 text-sm">
|
||||||
Persistent Startup Fleet
|
<input type="checkbox" checked={autoOn} onChange={(e) => setAutoOn(e.target.checked)} />
|
||||||
</h3>
|
{t("comp.startAuto")}
|
||||||
<p className="text-xs text-muted">
|
</label>
|
||||||
Configure how many bots automatically log into the world whenever the server launches.
|
<div className="mt-2 flex flex-wrap items-center gap-2 text-sm">
|
||||||
</p>
|
<label htmlFor="start-max" className="text-muted">{t("comp.startCount")}</label>
|
||||||
|
<input
|
||||||
<div className="flex flex-wrap items-center gap-4 text-sm">
|
id="start-max"
|
||||||
<label className="flex cursor-pointer items-center gap-2">
|
value={autoMax}
|
||||||
<input
|
onChange={(e) => setAutoMax(e.target.value)}
|
||||||
type="checkbox"
|
inputMode="numeric"
|
||||||
checked={autoOn}
|
disabled={!autoOn}
|
||||||
onChange={(e) => setAutoOn(e.target.checked)}
|
aria-invalid={!maxValid}
|
||||||
className="rounded border-line text-gold focus:ring-gold"
|
className="w-24 rounded-md border border-line bg-bg px-3 py-1.5 text-right outline-none focus:border-gold disabled:opacity-40"
|
||||||
/>
|
/>
|
||||||
<span>Enable Auto-Login on Server Startup</span>
|
<Button size="sm" variant="secondary" disabled={startBusy || (autoOn && !maxValid)} onClick={() => void saveStart()}>
|
||||||
</label>
|
{t("comp.startSave")}
|
||||||
|
</Button>
|
||||||
<div className="flex items-center gap-2">
|
|
||||||
<label htmlFor="start-max" className="text-xs text-muted">
|
|
||||||
Startup Limit:
|
|
||||||
</label>
|
|
||||||
<input
|
|
||||||
id="start-max"
|
|
||||||
value={autoMax}
|
|
||||||
onChange={(e) => setAutoMax(e.target.value)}
|
|
||||||
inputMode="numeric"
|
|
||||||
disabled={!autoOn}
|
|
||||||
aria-invalid={!maxValid}
|
|
||||||
className="w-24 rounded-md border border-line bg-bg px-2.5 py-1 text-right text-sm outline-none focus:border-gold disabled:opacity-40"
|
|
||||||
/>
|
|
||||||
<Button
|
|
||||||
size="sm"
|
|
||||||
variant="secondary"
|
|
||||||
disabled={startBusy || (autoOn && !maxValid)}
|
|
||||||
onClick={() => void saveStart()}
|
|
||||||
>
|
|
||||||
Save Setting
|
|
||||||
</Button>
|
|
||||||
</div>
|
|
||||||
</div>
|
</div>
|
||||||
{startNote && <p className="text-xs text-ok">{startNote}</p>}
|
{autoOn && !maxValid && autoMax !== "" && <p className="mt-1 text-xs text-warn">{t("comp.startInvalid")}</p>}
|
||||||
|
<p className="mt-1 text-xs text-muted">{t("comp.startHint")}</p>
|
||||||
|
{startNote && <p className="mt-2 text-sm text-ok" role="status">{startNote}</p>}
|
||||||
</div>
|
</div>
|
||||||
|
{error && <p className="mt-3 text-sm text-bad" role="alert">{error.human.code === "unknown" ? error.technical : human(error.human).message}</p>}
|
||||||
{error && (
|
|
||||||
<div className="rounded-md border border-bad/40 bg-bad/10 p-3 text-sm text-bad flex items-center gap-2">
|
|
||||||
<AlertCircle className="h-4 w-4 shrink-0" />
|
|
||||||
<span>{error.human.code === "unknown" ? error.technical : human(error.human).message}</span>
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
</Card>
|
</Card>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
@@ -1,4 +1,4 @@
|
|||||||
import { useState } from "react";
|
import { useEffect, useState } from "react";
|
||||||
import { open } from "@tauri-apps/plugin-dialog";
|
import { open } from "@tauri-apps/plugin-dialog";
|
||||||
import { AlertTriangle, Check, Minus } from "lucide-react";
|
import { AlertTriangle, Check, Minus } from "lucide-react";
|
||||||
import { api, asUiError, type Classification, type ScanReport, type ServerSummary, type UiError } from "@/lib/api";
|
import { api, asUiError, type Classification, type ScanReport, type ServerSummary, type UiError } from "@/lib/api";
|
||||||
@@ -17,10 +17,17 @@ export function ImportServer(props: {
|
|||||||
canCancel: boolean;
|
canCancel: boolean;
|
||||||
onCancel: () => void;
|
onCancel: () => void;
|
||||||
onAdded: (s: ServerSummary) => void | Promise<void>;
|
onAdded: (s: ServerSummary) => void | Promise<void>;
|
||||||
|
onCopy: (path: string) => void;
|
||||||
}) {
|
}) {
|
||||||
const t = useT();
|
const t = useT();
|
||||||
const human = useHuman();
|
const human = useHuman();
|
||||||
const [report, setReport] = useState<ScanReport | null>(null);
|
const [report, setReport] = useState<ScanReport | null>(null);
|
||||||
|
// A classic core (modules compiled in) is not added as it is: the Modules Preview makes a modular copy next to it.
|
||||||
|
const [classic, setClassic] = useState(false);
|
||||||
|
useEffect(() => {
|
||||||
|
setClassic(false);
|
||||||
|
if (report && report.classification !== "incompatible") void api.isClassicServer(report.path).then(setClassic).catch(() => setClassic(false));
|
||||||
|
}, [report]);
|
||||||
const [error, setError] = useState<UiError | null>(null);
|
const [error, setError] = useState<UiError | null>(null);
|
||||||
const [busy, setBusy] = useState(false);
|
const [busy, setBusy] = useState(false);
|
||||||
|
|
||||||
@@ -149,16 +156,28 @@ export function ImportServer(props: {
|
|||||||
</p>
|
</p>
|
||||||
))}
|
))}
|
||||||
|
|
||||||
<div className="mt-5 flex items-center justify-between border-t border-line pt-4">
|
{classic ? (
|
||||||
<p className="text-sm text-muted">{t("import.noChanges")}</p>
|
<div className="mt-5 border-t border-line pt-4">
|
||||||
<Button
|
<p className="font-medium">{t("import.classic.title")}</p>
|
||||||
variant="primary"
|
<p className="mt-1 text-sm text-muted">{t("import.classic.text")}</p>
|
||||||
onClick={add}
|
<div className="mt-3 flex justify-end">
|
||||||
disabled={busy || report.classification === "incompatible"}
|
<Button variant="primary" disabled={busy} onClick={() => props.onCopy(report.path)}>
|
||||||
>
|
{t("import.classic.copy")}
|
||||||
{t("import.add")}
|
</Button>
|
||||||
</Button>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
) : (
|
||||||
|
<div className="mt-5 flex items-center justify-between border-t border-line pt-4">
|
||||||
|
<p className="text-sm text-muted">{t("import.noChanges")}</p>
|
||||||
|
<Button
|
||||||
|
variant="primary"
|
||||||
|
onClick={add}
|
||||||
|
disabled={busy || report.classification === "incompatible"}
|
||||||
|
>
|
||||||
|
{t("import.add")}
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
</Card>
|
</Card>
|
||||||
)}
|
)}
|
||||||
</main>
|
</main>
|
||||||
|
|||||||
@@ -2,7 +2,7 @@ import { useEffect, useState } from "react";
|
|||||||
import { listen } from "@tauri-apps/api/event";
|
import { listen } from "@tauri-apps/api/event";
|
||||||
import { open } from "@tauri-apps/plugin-dialog";
|
import { open } from "@tauri-apps/plugin-dialog";
|
||||||
import { Check, ChevronDown, ChevronRight, Loader2 } from "lucide-react";
|
import { Check, ChevronDown, ChevronRight, Loader2 } from "lucide-react";
|
||||||
import { api, asUiError, type InstallEnvironment, type InstallRequirements, type InstallStep, type Preflight, type ServerSummary, type UiError } from "@/lib/api";
|
import { api, asUiError, type CopyReport, type InstallEnvironment, type InstallRequirements, type InstallStep, type Preflight, type ServerSummary, type UiError } from "@/lib/api";
|
||||||
import { formatBytes } from "@/lib/utils";
|
import { formatBytes } from "@/lib/utils";
|
||||||
import { Button } from "@/components/ui/button";
|
import { Button } from "@/components/ui/button";
|
||||||
import { Card } from "@/components/ui/card";
|
import { Card } from "@/components/ui/card";
|
||||||
@@ -16,14 +16,18 @@ const STEP_KEYS: Record<string, Key> = {
|
|||||||
Unpacking: "install.step.unpacking",
|
Unpacking: "install.step.unpacking",
|
||||||
"Preparing database": "install.step.database",
|
"Preparing database": "install.step.database",
|
||||||
Finishing: "install.step.finishing",
|
Finishing: "install.step.finishing",
|
||||||
|
"Installing the modular core": "install.step.modularCore",
|
||||||
|
"Copying the old server's data": "install.step.copying",
|
||||||
};
|
};
|
||||||
|
|
||||||
type Phase = "choose" | "installing" | "done";
|
type Phase = "choose" | "installing" | "done";
|
||||||
|
|
||||||
export function InstallServer(props: { canCancel: boolean; onCancel: () => void; onDone: (s: ServerSummary) => void | Promise<void> }) {
|
export function InstallServer(props: { canCancel: boolean; copyFrom?: string; onCancel: () => void; onDone: (s: ServerSummary) => void | Promise<void> }) {
|
||||||
const t = useT();
|
const t = useT();
|
||||||
const human = useHuman();
|
const human = useHuman();
|
||||||
const [dest, setDest] = useState("C:\\Games\\CoA Server");
|
const copyFrom = props.copyFrom;
|
||||||
|
const [dest, setDest] = useState(copyFrom ? copyFrom.replace(/[\\/]+$/, "") + " (modular)" : "C:\\Games\\CoA Server");
|
||||||
|
const [copied, setCopied] = useState<CopyReport | null>(null);
|
||||||
const [pre, setPre] = useState<Preflight | null>(null);
|
const [pre, setPre] = useState<Preflight | null>(null);
|
||||||
const [req, setReq] = useState<InstallRequirements | null>(null);
|
const [req, setReq] = useState<InstallRequirements | null>(null);
|
||||||
const [phase, setPhase] = useState<Phase>("choose");
|
const [phase, setPhase] = useState<Phase>("choose");
|
||||||
@@ -32,6 +36,8 @@ export function InstallServer(props: { canCancel: boolean; onCancel: () => void;
|
|||||||
const [showAdvanced, setShowAdvanced] = useState(false);
|
const [showAdvanced, setShowAdvanced] = useState(false);
|
||||||
const [pkg, setPkg] = useState("");
|
const [pkg, setPkg] = useState("");
|
||||||
const [installed, setInstalled] = useState<ServerSummary | null>(null);
|
const [installed, setInstalled] = useState<ServerSummary | null>(null);
|
||||||
|
const [classicCore, setClassicCore] = useState<string | null>(null);
|
||||||
|
const [modulesOff, setModulesOff] = useState<string[]>([]);
|
||||||
const [showDetails, setShowDetails] = useState(false);
|
const [showDetails, setShowDetails] = useState(false);
|
||||||
// What this computer installs. A repack (Windows) needs nothing more than a folder; Docker (Linux) also needs the game data
|
// What this computer installs. A repack (Windows) needs nothing more than a folder; Docker (Linux) also needs the game data
|
||||||
// folder and a package, and Docker itself.
|
// folder and a package, and Docker itself.
|
||||||
@@ -87,8 +93,11 @@ export function InstallServer(props: { canCancel: boolean; onCancel: () => void;
|
|||||||
setPhase("installing");
|
setPhase("installing");
|
||||||
setStep({ step: "Preparing your server", percent: 0, detail: null });
|
setStep({ step: "Preparing your server", percent: 0, detail: null });
|
||||||
try {
|
try {
|
||||||
const s = await api.installNew(dest, pkg.trim() || undefined, docker ? gameData.trim() : undefined);
|
const { preview_core_error, modules_off, copied, ...s } = await api.installNew(dest, copyFrom ? undefined : pkg.trim() || undefined, docker ? gameData.trim() : undefined, copyFrom);
|
||||||
setInstalled(s);
|
setInstalled(s);
|
||||||
|
setCopied(copied);
|
||||||
|
setClassicCore(preview_core_error);
|
||||||
|
setModulesOff(modules_off);
|
||||||
setPhase("done");
|
setPhase("done");
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
setError(asUiError(e));
|
setError(asUiError(e));
|
||||||
@@ -112,6 +121,7 @@ export function InstallServer(props: { canCancel: boolean; onCancel: () => void;
|
|||||||
<div className="h-full rounded-full bg-gold transition-[width] duration-300" style={{ width: `${step.percent}%` }} />
|
<div className="h-full rounded-full bg-gold transition-[width] duration-300" style={{ width: `${step.percent}%` }} />
|
||||||
</div>
|
</div>
|
||||||
{step.detail && <p className="mt-2 text-xs text-muted">{step.detail}</p>}
|
{step.detail && <p className="mt-2 text-xs text-muted">{step.detail}</p>}
|
||||||
|
{step.step === "Installing the modular core" && copyFrom && <p className="mt-2 text-xs text-muted">{t("install.modularCoreHint")}</p>}
|
||||||
</Card>
|
</Card>
|
||||||
{step.step === "Downloading server" && (
|
{step.step === "Downloading server" && (
|
||||||
<Button className="mt-4 self-start" variant="ghost" size="sm" onClick={() => void api.cancelInstall()}>
|
<Button className="mt-4 self-start" variant="ghost" size="sm" onClick={() => void api.cancelInstall()}>
|
||||||
@@ -130,6 +140,32 @@ export function InstallServer(props: { canCancel: boolean; onCancel: () => void;
|
|||||||
</div>
|
</div>
|
||||||
<h1 className="mt-5 text-2xl font-semibold">{t("install.doneTitle")}</h1>
|
<h1 className="mt-5 text-2xl font-semibold">{t("install.doneTitle")}</h1>
|
||||||
<p className="mt-1 text-muted">{t("install.doneText")}</p>
|
<p className="mt-1 text-muted">{t("install.doneText")}</p>
|
||||||
|
{copied && (
|
||||||
|
<p className="mt-3 text-sm text-muted">
|
||||||
|
{t("install.copy.done", { accounts: copied.accounts, characters: copied.characters, settings: copied.config_files.length })}
|
||||||
|
{" "}{t("install.copy.worldSettings", { n: copied.world_settings.length })}
|
||||||
|
</p>
|
||||||
|
)}
|
||||||
|
{copied && copied.world_settings_skipped.length > 0 && (
|
||||||
|
<Card className="mt-6 border-warn/40 p-4 text-left">
|
||||||
|
<p className="text-sm text-warn">{t("install.copy.worldSkipped")}</p>
|
||||||
|
<pre className="selectable mt-2 max-h-32 overflow-auto whitespace-pre-wrap rounded bg-black/40 p-2 text-xs">{copied.world_settings_skipped.join("\n")}</pre>
|
||||||
|
</Card>
|
||||||
|
)}
|
||||||
|
{classicCore && (
|
||||||
|
<Card className="mt-6 border-warn/40 p-4 text-left" role="alert">
|
||||||
|
<p className="font-medium text-warn">{t("install.classicCoreTitle")}</p>
|
||||||
|
<p className="mt-1 text-sm text-muted">{t("install.classicCoreText")}</p>
|
||||||
|
<pre className="selectable mt-2 max-h-32 overflow-auto whitespace-pre-wrap rounded bg-black/40 p-2 text-xs">{classicCore}</pre>
|
||||||
|
</Card>
|
||||||
|
)}
|
||||||
|
{modulesOff.length > 0 && (
|
||||||
|
<Card className="mt-6 border-warn/40 p-4 text-left" role="alert">
|
||||||
|
<p className="font-medium text-warn">{t("install.modulesOffTitle")}</p>
|
||||||
|
<p className="mt-1 text-sm text-muted">{t("install.modulesOffText")}</p>
|
||||||
|
<pre className="selectable mt-2 max-h-32 overflow-auto whitespace-pre-wrap rounded bg-black/40 p-2 text-xs">{modulesOff.join("\n")}</pre>
|
||||||
|
</Card>
|
||||||
|
)}
|
||||||
<Button className="mt-8" variant="primary" size="xl" onClick={() => void props.onDone(installed)}>
|
<Button className="mt-8" variant="primary" size="xl" onClick={() => void props.onDone(installed)}>
|
||||||
{t("install.open")}
|
{t("install.open")}
|
||||||
</Button>
|
</Button>
|
||||||
@@ -140,8 +176,9 @@ export function InstallServer(props: { canCancel: boolean; onCancel: () => void;
|
|||||||
return (
|
return (
|
||||||
<main className="mx-auto flex h-full max-w-2xl flex-col justify-center gap-5 px-8 py-10">
|
<main className="mx-auto flex h-full max-w-2xl flex-col justify-center gap-5 px-8 py-10">
|
||||||
<div>
|
<div>
|
||||||
<h1 className="text-2xl font-semibold">{t("install.title")}</h1>
|
<h1 className="text-2xl font-semibold">{copyFrom ? t("install.copy.title") : t("install.title")}</h1>
|
||||||
<p className="mt-1 text-muted">{t("install.subtitle")}</p>
|
<p className="mt-1 text-muted">{copyFrom ? t("install.copy.subtitle") : t("install.subtitle")}</p>
|
||||||
|
{copyFrom && <p className="selectable mt-2 break-all text-sm">{t("install.copy.from")} {copyFrom}</p>}
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div>
|
<div>
|
||||||
@@ -213,7 +250,7 @@ export function InstallServer(props: { canCancel: boolean; onCancel: () => void;
|
|||||||
</Card>
|
</Card>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
{!docker && <div>
|
{!docker && !copyFrom && <div>
|
||||||
<button onClick={() => setShowAdvanced((v) => !v)} aria-expanded={showAdvanced} className="flex cursor-pointer items-center gap-1 text-sm text-muted hover:text-ink">
|
<button onClick={() => setShowAdvanced((v) => !v)} aria-expanded={showAdvanced} className="flex cursor-pointer items-center gap-1 text-sm text-muted hover:text-ink">
|
||||||
{showAdvanced ? <ChevronDown className="h-4 w-4" aria-hidden /> : <ChevronRight className="h-4 w-4" aria-hidden />}
|
{showAdvanced ? <ChevronDown className="h-4 w-4" aria-hidden /> : <ChevronRight className="h-4 w-4" aria-hidden />}
|
||||||
{t("install.advanced")}
|
{t("install.advanced")}
|
||||||
|
|||||||
+548
-747
File diff suppressed because it is too large.
Load diff
@@ -1,581 +1,189 @@
|
|||||||
import { useState } from "react";
|
import { useState } from "react";
|
||||||
import { open } from "@tauri-apps/plugin-dialog";
|
import { open } from "@tauri-apps/plugin-dialog";
|
||||||
import {
|
import { AlertTriangle, ArrowRight, Check, Database, FolderOpen, Info, Loader2 } from "lucide-react";
|
||||||
AlertCircle,
|
|
||||||
AlertTriangle,
|
|
||||||
ArrowRight,
|
|
||||||
CheckCircle2,
|
|
||||||
Database,
|
|
||||||
FileCheck,
|
|
||||||
FolderOpen,
|
|
||||||
Loader2,
|
|
||||||
RotateCcw,
|
|
||||||
Server,
|
|
||||||
Shield,
|
|
||||||
ShieldCheck,
|
|
||||||
Users,
|
|
||||||
} from "lucide-react";
|
|
||||||
import { Button } from "@/components/ui/button";
|
import { Button } from "@/components/ui/button";
|
||||||
import { Card } from "@/components/ui/card";
|
import { Card } from "@/components/ui/card";
|
||||||
import {
|
import { api, asUiError, type CopyPreview, type ServerSummary, type UiError } from "@/lib/api";
|
||||||
api,
|
import { useHuman, useT } from "@/i18n";
|
||||||
type ConflictResolutionPolicy,
|
|
||||||
type MigrationExecutionReport,
|
|
||||||
type MigrationPlan,
|
|
||||||
type MigrationScope,
|
|
||||||
type SourceInspectionReport,
|
|
||||||
} from "@/lib/api";
|
|
||||||
import { cn } from "@/lib/utils";
|
|
||||||
|
|
||||||
export interface ServerMigrationWizardProps {
|
/**
|
||||||
currentRealmId: string;
|
* Moving a server to the modular core. A server with the classic core is never converted in place: a new server is
|
||||||
onClose?: () => void;
|
* installed next to it and its data is copied there (`modular_copy`). This page shows what the old server holds and
|
||||||
onSuccess?: () => void;
|
* what the copy takes, then hands over to the same install screen "Manage another server" uses for a modular copy.
|
||||||
}
|
*/
|
||||||
|
export function ServerMigrationWizard(props: {
|
||||||
|
servers: ServerSummary[];
|
||||||
|
currentName: string;
|
||||||
|
onCopy: (path: string) => void;
|
||||||
|
}) {
|
||||||
|
const t = useT();
|
||||||
|
const human = useHuman();
|
||||||
|
const [path, setPath] = useState("");
|
||||||
|
const [busy, setBusy] = useState(false);
|
||||||
|
const [info, setInfo] = useState<CopyPreview | null>(null);
|
||||||
|
const [error, setError] = useState<UiError | null>(null);
|
||||||
|
|
||||||
type WizardStep = "source" | "inspect" | "scope" | "plan" | "executing" | "result";
|
async function inspect(p: string) {
|
||||||
|
if (!p.trim()) return;
|
||||||
export function ServerMigrationWizard({
|
setPath(p);
|
||||||
currentRealmId,
|
setError(null);
|
||||||
onClose,
|
setInfo(null);
|
||||||
onSuccess,
|
setBusy(true);
|
||||||
}: ServerMigrationWizardProps) {
|
|
||||||
const locale = "ru";
|
|
||||||
|
|
||||||
const [step, setStep] = useState<WizardStep>("source");
|
|
||||||
const [sourcePath, setSourcePath] = useState("");
|
|
||||||
const [inspecting, setInspecting] = useState(false);
|
|
||||||
const [report, setReport] = useState<SourceInspectionReport | null>(null);
|
|
||||||
|
|
||||||
// Scope
|
|
||||||
const [scope, setScope] = useState<MigrationScope>({
|
|
||||||
accounts_and_characters: true,
|
|
||||||
module_owned_data: true,
|
|
||||||
server_configuration: true,
|
|
||||||
selected_modules: [],
|
|
||||||
});
|
|
||||||
|
|
||||||
// Conflict policy
|
|
||||||
const [conflictPolicy, setConflictPolicy] = useState<ConflictResolutionPolicy>(
|
|
||||||
"remap_colliding_guids"
|
|
||||||
);
|
|
||||||
|
|
||||||
// Plan & Execution
|
|
||||||
const [planning, setPlanning] = useState(false);
|
|
||||||
const [plan, setPlan] = useState<MigrationPlan | null>(null);
|
|
||||||
const [executing, setExecuting] = useState(false);
|
|
||||||
const [execReport, setExecReport] = useState<MigrationExecutionReport | null>(null);
|
|
||||||
const [errorMsg, setErrorMsg] = useState<string | null>(null);
|
|
||||||
|
|
||||||
async function handlePickSource() {
|
|
||||||
setErrorMsg(null);
|
|
||||||
try {
|
try {
|
||||||
const selected = await open({
|
setInfo(await api.modularCopyPreview(p.trim()));
|
||||||
directory: true,
|
|
||||||
multiple: false,
|
|
||||||
title: locale === "ru" ? "Выберите каталог исходного сервера" : "Select Source Server Directory",
|
|
||||||
});
|
|
||||||
if (typeof selected === "string") {
|
|
||||||
setSourcePath(selected);
|
|
||||||
}
|
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
setErrorMsg(String(e));
|
setError(asUiError(e));
|
||||||
|
} finally {
|
||||||
|
setBusy(false);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
async function handleInspect() {
|
async function browse() {
|
||||||
if (!sourcePath.trim()) return;
|
const picked = await open({ directory: true, multiple: false, title: t("migrate.dialogTitle") });
|
||||||
setErrorMsg(null);
|
if (typeof picked === "string") await inspect(picked);
|
||||||
setInspecting(true);
|
|
||||||
try {
|
|
||||||
const res = await api.previewMigrationInspect(sourcePath);
|
|
||||||
setReport(res);
|
|
||||||
// Auto-select detected modules
|
|
||||||
setScope((prev) => ({
|
|
||||||
...prev,
|
|
||||||
selected_modules: res.detected_modules.map((m) => m.id),
|
|
||||||
}));
|
|
||||||
setStep("inspect");
|
|
||||||
} catch (e: any) {
|
|
||||||
setErrorMsg(e?.human?.message || e?.technical || String(e));
|
|
||||||
} finally {
|
|
||||||
setInspecting(false);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
async function handleCreatePlan() {
|
const gb = (bytes: number) => (bytes / 1024 ** 3).toFixed(1);
|
||||||
if (!report) return;
|
const count = (n: number | null) => (n === null ? t("migrate.countLater") : String(n));
|
||||||
setErrorMsg(null);
|
|
||||||
setPlanning(true);
|
|
||||||
try {
|
|
||||||
const res = await api.previewMigrationPlan(sourcePath, currentRealmId, scope, conflictPolicy);
|
|
||||||
setPlan(res);
|
|
||||||
setStep("plan");
|
|
||||||
} catch (e: any) {
|
|
||||||
setErrorMsg(e?.human?.message || e?.technical || String(e));
|
|
||||||
} finally {
|
|
||||||
setPlanning(false);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
async function handleExecute() {
|
|
||||||
if (!plan) return;
|
|
||||||
setErrorMsg(null);
|
|
||||||
setExecuting(true);
|
|
||||||
setStep("executing");
|
|
||||||
try {
|
|
||||||
const res = await api.previewMigrationExecute(plan);
|
|
||||||
setExecReport(res);
|
|
||||||
setStep("result");
|
|
||||||
if (res.success && onSuccess) {
|
|
||||||
onSuccess();
|
|
||||||
}
|
|
||||||
} catch (e: any) {
|
|
||||||
setErrorMsg(e?.human?.message || e?.technical || String(e));
|
|
||||||
setStep("plan");
|
|
||||||
} finally {
|
|
||||||
setExecuting(false);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="flex h-full flex-col max-w-4xl mx-auto p-6 space-y-6">
|
<div className="mx-auto flex max-w-3xl flex-col gap-5 px-8 py-8">
|
||||||
{/* Header */}
|
<div>
|
||||||
<div className="flex items-center justify-between border-b border-line pb-4">
|
<h1 className="text-2xl font-semibold">{t("migrate.title")}</h1>
|
||||||
<div>
|
<p className="mt-1 text-sm text-muted">{t("migrate.subtitle")}</p>
|
||||||
<h2 className="text-xl font-bold tracking-tight text-ink flex items-center gap-2">
|
</div>
|
||||||
<RotateCcw className="h-6 w-6 text-gold" />
|
|
||||||
{locale === "ru" ? "Центр переноса сервера" : "Server Migration Center"}
|
<Card className="flex flex-col gap-3 p-5">
|
||||||
<span className="rounded bg-sky-500/20 px-2 py-0.5 text-xs font-mono font-medium text-sky-400">
|
<h2 className="font-semibold">{t("migrate.source")}</h2>
|
||||||
MIGRATION WIZARD
|
{props.servers.length > 0 && (
|
||||||
</span>
|
<div className="flex flex-wrap gap-2">
|
||||||
</h2>
|
{props.servers.map((s) => (
|
||||||
<p className="mt-1 text-xs text-muted">
|
<Button key={s.id} variant="secondary" size="sm" disabled={busy} onClick={() => void inspect(s.path)}>
|
||||||
{locale === "ru"
|
{s.name}
|
||||||
? "Перенос персонажей, аккаунтов, данных модулей и конфигураций в изолированный модульный сервер Preview."
|
</Button>
|
||||||
: "Migrate characters, accounts, module data and configs into an isolated modular Preview realm."}
|
))}
|
||||||
</p>
|
</div>
|
||||||
</div>
|
|
||||||
{onClose && (
|
|
||||||
<Button size="sm" variant="ghost" onClick={onClose} className="text-xs">
|
|
||||||
{locale === "ru" ? "Закрыть" : "Close"}
|
|
||||||
</Button>
|
|
||||||
)}
|
)}
|
||||||
</div>
|
<div className="flex gap-2">
|
||||||
|
<input
|
||||||
|
className="flex-1 rounded-md border border-line bg-bg px-3 py-2 font-mono text-sm outline-none focus:border-gold"
|
||||||
|
value={path}
|
||||||
|
placeholder="C:\Games\CoA Server"
|
||||||
|
onChange={(e) => setPath(e.target.value)}
|
||||||
|
onKeyDown={(e) => e.key === "Enter" && void inspect(path)}
|
||||||
|
/>
|
||||||
|
<Button variant="secondary" onClick={() => void browse()} disabled={busy}>
|
||||||
|
<FolderOpen className="mr-2 h-4 w-4" aria-hidden /> {t("migrate.browse")}
|
||||||
|
</Button>
|
||||||
|
<Button onClick={() => void inspect(path)} disabled={busy || !path.trim()}>
|
||||||
|
{busy ? <Loader2 className="h-4 w-4 animate-spin" aria-hidden /> : t("migrate.inspect")}
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
<p className="text-xs text-muted">{t("migrate.readOnly")}</p>
|
||||||
|
</Card>
|
||||||
|
|
||||||
{errorMsg && (
|
{error && (
|
||||||
<Card className="border-bad/40 bg-bad/5 p-4 text-xs text-bad flex items-start gap-2.5">
|
<Card className="border-bad/40 p-4" role="alert">
|
||||||
<AlertCircle className="h-4 w-4 shrink-0 mt-0.5" />
|
<p className="font-medium text-bad">{human(error.human).title}</p>
|
||||||
<div className="flex-1">
|
<p className="mt-1 text-sm text-muted">{human(error.human).message}</p>
|
||||||
<p className="font-semibold">{locale === "ru" ? "Ошибка переноса" : "Migration Error"}</p>
|
|
||||||
<p className="mt-0.5 whitespace-pre-wrap">{errorMsg}</p>
|
|
||||||
</div>
|
|
||||||
</Card>
|
</Card>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
{/* Stepper Progress */}
|
{info && (
|
||||||
<div className="flex items-center justify-between text-xs font-medium text-muted px-2">
|
<Card className="flex flex-col gap-4 p-5">
|
||||||
<span className={cn(step === "source" && "text-gold font-bold")}>1. Исходный сервер</span>
|
<div className="flex items-start gap-3">
|
||||||
<ArrowRight className="h-3 w-3 text-line" />
|
{info.classic ? (
|
||||||
<span className={cn(step === "inspect" && "text-gold font-bold")}>2. Анализ данных</span>
|
<Check className="mt-0.5 h-5 w-5 text-ok" aria-hidden />
|
||||||
<ArrowRight className="h-3 w-3 text-line" />
|
|
||||||
<span className={cn(step === "scope" && "text-gold font-bold")}>3. Область переноса</span>
|
|
||||||
<ArrowRight className="h-3 w-3 text-line" />
|
|
||||||
<span className={cn(step === "plan" && "text-gold font-bold")}>4. План и риски</span>
|
|
||||||
<ArrowRight className="h-3 w-3 text-line" />
|
|
||||||
<span className={cn((step === "executing" || step === "result") && "text-gold font-bold")}>5. Перенос</span>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{/* STEP 1: SELECT SOURCE */}
|
|
||||||
{step === "source" && (
|
|
||||||
<Card className="p-6 space-y-4">
|
|
||||||
<h3 className="text-sm font-semibold text-ink flex items-center gap-2">
|
|
||||||
<FolderOpen className="h-4 w-4 text-gold" />
|
|
||||||
{locale === "ru" ? "Шаг 1: Укажите каталог исходного сервера" : "Step 1: Select Source Server"}
|
|
||||||
</h3>
|
|
||||||
<p className="text-xs text-muted">
|
|
||||||
{locale === "ru"
|
|
||||||
? "Поддерживаются серверы под управлением CoA Server Manager, устаревшие CoA-серверы со встроенными ботами, а также стандартные серверы AzerothCore."
|
|
||||||
: "Supports CSM-managed servers, legacy embedded CoA installations, and standard AzerothCore."}
|
|
||||||
</p>
|
|
||||||
|
|
||||||
<div className="flex items-center gap-3">
|
|
||||||
<input
|
|
||||||
type="text"
|
|
||||||
value={sourcePath}
|
|
||||||
onChange={(e) => setSourcePath(e.target.value)}
|
|
||||||
placeholder="C:\games\CoA Server или путь к серверу..."
|
|
||||||
className="flex-1 rounded-md border border-line bg-bg px-3 py-2 text-xs text-ink focus:border-gold focus:outline-none font-mono"
|
|
||||||
/>
|
|
||||||
<Button size="sm" variant="secondary" onClick={handlePickSource}>
|
|
||||||
<FolderOpen className="h-3.5 w-3.5 mr-1.5" />
|
|
||||||
{locale === "ru" ? "Обзор..." : "Browse..."}
|
|
||||||
</Button>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div className="rounded-lg bg-white/5 border border-line p-3 text-xs text-muted space-y-1">
|
|
||||||
<p className="font-semibold text-ink flex items-center gap-1.5">
|
|
||||||
<ShieldCheck className="h-4 w-4 text-ok" />
|
|
||||||
{locale === "ru" ? "Гарантия безопасности данных" : "Safety Guarantee"}
|
|
||||||
</p>
|
|
||||||
<p>
|
|
||||||
{locale === "ru"
|
|
||||||
? "Анализ выполняется строго в режиме чтения (Read-Only). Никакие скрипты и изменения на исходном сервере не выполняются."
|
|
||||||
: "Source server inspection is strictly read-only. No scripts or writes are performed."}
|
|
||||||
</p>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div className="flex justify-end pt-2">
|
|
||||||
<Button
|
|
||||||
size="sm"
|
|
||||||
variant="primary"
|
|
||||||
disabled={!sourcePath.trim() || inspecting}
|
|
||||||
onClick={handleInspect}
|
|
||||||
>
|
|
||||||
{inspecting && <Loader2 className="h-3.5 w-3.5 mr-1.5 animate-spin" />}
|
|
||||||
{locale === "ru" ? "Проанализировать сервер" : "Inspect Server"}
|
|
||||||
<ArrowRight className="h-3.5 w-3.5 ml-1.5" />
|
|
||||||
</Button>
|
|
||||||
</div>
|
|
||||||
</Card>
|
|
||||||
)}
|
|
||||||
|
|
||||||
{/* STEP 2: INSPECTION REPORT */}
|
|
||||||
{step === "inspect" && report && (
|
|
||||||
<Card className="p-6 space-y-4">
|
|
||||||
<h3 className="text-sm font-semibold text-ink flex items-center gap-2">
|
|
||||||
<Server className="h-4 w-4 text-gold" />
|
|
||||||
{locale === "ru" ? "Шаг 2: Результаты анализа исходного сервера" : "Step 2: Source Inspection Results"}
|
|
||||||
</h3>
|
|
||||||
|
|
||||||
<div className="grid grid-cols-2 gap-3 sm:grid-cols-4">
|
|
||||||
<div className="rounded-lg border border-line bg-card p-3">
|
|
||||||
<span className="text-[11px] text-muted">{locale === "ru" ? "Тип сервера" : "Server Type"}</span>
|
|
||||||
<p className="mt-1 font-mono text-xs font-semibold text-ink">
|
|
||||||
{report.source_type === "CSM_MANAGED_COA" && "CSM Managed CoA"}
|
|
||||||
{report.source_type === "LEGACY_EMBEDDED_COA" && "Legacy CoA (Embedded)"}
|
|
||||||
{report.source_type === "STANDARD_AZEROTH_CORE" && "Standard AzerothCore"}
|
|
||||||
{report.source_type === "UNKNOWN_CUSTOM" && "Custom Layout"}
|
|
||||||
</p>
|
|
||||||
</div>
|
|
||||||
<div className="rounded-lg border border-line bg-card p-3">
|
|
||||||
<span className="text-[11px] text-muted">{locale === "ru" ? "Аккаунтов" : "Accounts"}</span>
|
|
||||||
<p className="mt-1 font-mono text-xs font-semibold text-ink flex items-center gap-1.5">
|
|
||||||
<Users className="h-3.5 w-3.5 text-gold" />
|
|
||||||
{report.accounts_count}
|
|
||||||
</p>
|
|
||||||
</div>
|
|
||||||
<div className="rounded-lg border border-line bg-card p-3">
|
|
||||||
<span className="text-[11px] text-muted">{locale === "ru" ? "Персонажей" : "Characters"}</span>
|
|
||||||
<p className="mt-1 font-mono text-xs font-semibold text-ink flex items-center gap-1.5">
|
|
||||||
<Users className="h-3.5 w-3.5 text-sky-400" />
|
|
||||||
{report.characters_count}
|
|
||||||
</p>
|
|
||||||
</div>
|
|
||||||
<div className="rounded-lg border border-line bg-card p-3">
|
|
||||||
<span className="text-[11px] text-muted">{locale === "ru" ? "Схема БД" : "DB Schema"}</span>
|
|
||||||
<p className="mt-1 font-mono text-xs font-semibold text-ink">
|
|
||||||
{report.schema_version ?? "2026_10_28_00"}
|
|
||||||
</p>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{/* Detected Modules */}
|
|
||||||
<div>
|
|
||||||
<h4 className="text-xs font-semibold text-ink mb-2">
|
|
||||||
{locale === "ru" ? "Обнаруженные модули и таблицы:" : "Detected Modules & Tables:"}
|
|
||||||
</h4>
|
|
||||||
{report.detected_modules.length === 0 ? (
|
|
||||||
<p className="text-xs text-muted italic">
|
|
||||||
{locale === "ru" ? "Сторонние модули не обнаружены." : "No external modules detected."}
|
|
||||||
</p>
|
|
||||||
) : (
|
) : (
|
||||||
<div className="divide-y divide-line border border-line rounded-lg">
|
<Info className="mt-0.5 h-5 w-5 text-warn" aria-hidden />
|
||||||
{report.detected_modules.map((m) => (
|
|
||||||
<div key={m.id} className="p-3 flex items-center justify-between text-xs">
|
|
||||||
<div>
|
|
||||||
<p className="font-semibold text-ink">{m.name} <span className="font-mono text-[11px] text-muted">({m.id})</span></p>
|
|
||||||
<p className="text-[11px] text-muted">Обнаружен через: {m.detected_via}</p>
|
|
||||||
</div>
|
|
||||||
<span className="rounded bg-ok/10 text-ok border border-ok/30 px-2 py-0.5 text-[11px] font-medium">
|
|
||||||
✓ Адаптер готов
|
|
||||||
</span>
|
|
||||||
</div>
|
|
||||||
))}
|
|
||||||
</div>
|
|
||||||
)}
|
)}
|
||||||
</div>
|
|
||||||
|
|
||||||
<div className="flex justify-between pt-2">
|
|
||||||
<Button size="sm" variant="ghost" onClick={() => setStep("source")}>
|
|
||||||
{locale === "ru" ? "Назад" : "Back"}
|
|
||||||
</Button>
|
|
||||||
<Button size="sm" variant="primary" onClick={() => setStep("scope")}>
|
|
||||||
{locale === "ru" ? "Настроить перенос" : "Configure Scope"}
|
|
||||||
<ArrowRight className="h-3.5 w-3.5 ml-1.5" />
|
|
||||||
</Button>
|
|
||||||
</div>
|
|
||||||
</Card>
|
|
||||||
)}
|
|
||||||
|
|
||||||
{/* STEP 3: SCOPE & CONFLICT RESOLUTION */}
|
|
||||||
{step === "scope" && report && (
|
|
||||||
<Card className="p-6 space-y-5">
|
|
||||||
<h3 className="text-sm font-semibold text-ink flex items-center gap-2">
|
|
||||||
<Database className="h-4 w-4 text-gold" />
|
|
||||||
{locale === "ru" ? "Шаг 3: Выбор категорий данных и политика конфликтов" : "Step 3: Migration Scope"}
|
|
||||||
</h3>
|
|
||||||
|
|
||||||
<div className="space-y-3">
|
|
||||||
<label className="flex items-start gap-3 p-3 rounded-lg border border-line bg-card cursor-pointer hover:border-gold/40">
|
|
||||||
<input
|
|
||||||
type="checkbox"
|
|
||||||
checked={scope.accounts_and_characters}
|
|
||||||
onChange={(e) => setScope({ ...scope, accounts_and_characters: e.target.checked })}
|
|
||||||
className="mt-0.5 h-4 w-4 rounded border-line text-gold focus:ring-gold"
|
|
||||||
/>
|
|
||||||
<div>
|
|
||||||
<p className="text-xs font-semibold text-ink">
|
|
||||||
{locale === "ru" ? "Аккаунты и персонажи" : "Accounts & Characters"}
|
|
||||||
</p>
|
|
||||||
<p className="text-[11px] text-muted">
|
|
||||||
{locale === "ru"
|
|
||||||
? "Учетные записи, персонажи, инвентарь, таланты, заклинания, символы, навыки, репутация, квесты и питомцы."
|
|
||||||
: "Accounts, characters, inventory, spells, talents, glyphs, skills, reputation, quests, and pets."}
|
|
||||||
</p>
|
|
||||||
</div>
|
|
||||||
</label>
|
|
||||||
|
|
||||||
<label className="flex items-start gap-3 p-3 rounded-lg border border-line bg-card cursor-pointer hover:border-gold/40">
|
|
||||||
<input
|
|
||||||
type="checkbox"
|
|
||||||
checked={scope.module_owned_data}
|
|
||||||
onChange={(e) => setScope({ ...scope, module_owned_data: e.target.checked })}
|
|
||||||
className="mt-0.5 h-4 w-4 rounded border-line text-gold focus:ring-gold"
|
|
||||||
/>
|
|
||||||
<div>
|
|
||||||
<p className="text-xs font-semibold text-ink">
|
|
||||||
{locale === "ru" ? "Данные модулей" : "Module-owned Data"}
|
|
||||||
</p>
|
|
||||||
<p className="text-[11px] text-muted">
|
|
||||||
{locale === "ru"
|
|
||||||
? "Сохраненные боты (Companions/Playerbots), данные масштабирования контента, таблицы аукцион-бота и зачарователя."
|
|
||||||
: "Saved bot configurations, content scaling overrides, AH bot data, and NPC enchanter states."}
|
|
||||||
</p>
|
|
||||||
</div>
|
|
||||||
</label>
|
|
||||||
|
|
||||||
<label className="flex items-start gap-3 p-3 rounded-lg border border-line bg-card cursor-pointer hover:border-gold/40">
|
|
||||||
<input
|
|
||||||
type="checkbox"
|
|
||||||
checked={scope.server_configuration}
|
|
||||||
onChange={(e) => setScope({ ...scope, server_configuration: e.target.checked })}
|
|
||||||
className="mt-0.5 h-4 w-4 rounded border-line text-gold focus:ring-gold"
|
|
||||||
/>
|
|
||||||
<div>
|
|
||||||
<p className="text-xs font-semibold text-ink">
|
|
||||||
{locale === "ru" ? "Конфигурация сервера (.conf)" : "Server Configurations (.conf)"}
|
|
||||||
</p>
|
|
||||||
<p className="text-[11px] text-muted">
|
|
||||||
{locale === "ru"
|
|
||||||
? "Пользовательские настройки модулей из configs/modules (с сохранением безопасных значений)."
|
|
||||||
: "Preserve customized configs from configs/modules/."}
|
|
||||||
</p>
|
|
||||||
</div>
|
|
||||||
</label>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{/* Conflict Policy */}
|
|
||||||
<div className="border-t border-line pt-4 space-y-2">
|
|
||||||
<h4 className="text-xs font-semibold text-ink">
|
|
||||||
{locale === "ru" ? "Политика разрешения конфликтов GUID:" : "GUID Conflict Resolution Policy:"}
|
|
||||||
</h4>
|
|
||||||
<div className="grid gap-2 sm:grid-cols-3">
|
|
||||||
<button
|
|
||||||
type="button"
|
|
||||||
onClick={() => setConflictPolicy("remap_colliding_guids")}
|
|
||||||
className={cn(
|
|
||||||
"p-3 rounded-lg border text-left text-xs transition-colors",
|
|
||||||
conflictPolicy === "remap_colliding_guids"
|
|
||||||
? "border-gold bg-gold/10 text-gold"
|
|
||||||
: "border-line bg-card text-muted hover:text-ink"
|
|
||||||
)}
|
|
||||||
>
|
|
||||||
<p className="font-semibold text-ink">Переназначить GUID</p>
|
|
||||||
<p className="text-[11px] text-muted mt-1">
|
|
||||||
Безопасное смещение ID персонажей и предметов. Ничего не теряется.
|
|
||||||
</p>
|
|
||||||
</button>
|
|
||||||
<button
|
|
||||||
type="button"
|
|
||||||
onClick={() => setConflictPolicy("skip_colliding_guids")}
|
|
||||||
className={cn(
|
|
||||||
"p-3 rounded-lg border text-left text-xs transition-colors",
|
|
||||||
conflictPolicy === "skip_colliding_guids"
|
|
||||||
? "border-gold bg-gold/10 text-gold"
|
|
||||||
: "border-line bg-card text-muted hover:text-ink"
|
|
||||||
)}
|
|
||||||
>
|
|
||||||
<p className="font-semibold text-ink">Пропустить дубликаты</p>
|
|
||||||
<p className="text-[11px] text-muted mt-1">
|
|
||||||
Персонажи с существующими GUID не импортируются.
|
|
||||||
</p>
|
|
||||||
</button>
|
|
||||||
<button
|
|
||||||
type="button"
|
|
||||||
onClick={() => setConflictPolicy("overwrite_existing")}
|
|
||||||
className={cn(
|
|
||||||
"p-3 rounded-lg border text-left text-xs transition-colors",
|
|
||||||
conflictPolicy === "overwrite_existing"
|
|
||||||
? "border-bad bg-bad/10 text-bad"
|
|
||||||
: "border-line bg-card text-muted hover:text-ink"
|
|
||||||
)}
|
|
||||||
>
|
|
||||||
<p className="font-semibold text-ink">Перезаписать (Опасно)</p>
|
|
||||||
<p className="text-[11px] text-muted mt-1">
|
|
||||||
Заменяет существующих персонажей на целевом сервере.
|
|
||||||
</p>
|
|
||||||
</button>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div className="flex justify-between pt-2">
|
|
||||||
<Button size="sm" variant="ghost" onClick={() => setStep("inspect")}>
|
|
||||||
{locale === "ru" ? "Назад" : "Back"}
|
|
||||||
</Button>
|
|
||||||
<Button size="sm" variant="primary" disabled={planning} onClick={handleCreatePlan}>
|
|
||||||
{planning && <Loader2 className="h-3.5 w-3.5 mr-1.5 animate-spin" />}
|
|
||||||
{locale === "ru" ? "Сформировать план" : "Generate Plan"}
|
|
||||||
<ArrowRight className="h-3.5 w-3.5 ml-1.5" />
|
|
||||||
</Button>
|
|
||||||
</div>
|
|
||||||
</Card>
|
|
||||||
)}
|
|
||||||
|
|
||||||
{/* STEP 4: PLAN & RISKS */}
|
|
||||||
{step === "plan" && plan && (
|
|
||||||
<Card className="p-6 space-y-4">
|
|
||||||
<h3 className="text-sm font-semibold text-ink flex items-center gap-2">
|
|
||||||
<FileCheck className="h-4 w-4 text-gold" />
|
|
||||||
{locale === "ru" ? "Шаг 4: План переноса и подтверждение" : "Step 4: Preflight Plan"}
|
|
||||||
</h3>
|
|
||||||
|
|
||||||
<div className="rounded-lg border border-gold/30 bg-gold/5 p-4 text-xs space-y-2">
|
|
||||||
<p className="font-semibold text-gold flex items-center gap-1.5">
|
|
||||||
<Shield className="h-4 w-4" />
|
|
||||||
{locale === "ru" ? "Автоматическое создание точки восстановления" : "Automatic Restore Point"}
|
|
||||||
</p>
|
|
||||||
<p className="text-muted">
|
|
||||||
{locale === "ru"
|
|
||||||
? "Перед началом переноса будет создана полная резервная копия целевой базы данных и файлов. В случае любой ошибки состояние будет полностью восстановлено."
|
|
||||||
: "A complete backup of the destination realm will be created before any changes. Full rollback is guaranteed on failure."}
|
|
||||||
</p>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{plan.warnings.length > 0 && (
|
|
||||||
<div className="space-y-1">
|
|
||||||
<h4 className="text-xs font-semibold text-ink flex items-center gap-1.5">
|
|
||||||
<AlertTriangle className="h-3.5 w-3.5 text-warn" />
|
|
||||||
{locale === "ru" ? "Предупреждения и риски:" : "Warnings:"}
|
|
||||||
</h4>
|
|
||||||
<ul className="list-disc list-inside text-xs text-muted space-y-1">
|
|
||||||
{plan.warnings.map((w, idx) => (
|
|
||||||
<li key={idx}>{w}</li>
|
|
||||||
))}
|
|
||||||
</ul>
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
|
|
||||||
<div>
|
|
||||||
<h4 className="text-xs font-semibold text-ink mb-1.5">
|
|
||||||
{locale === "ru" ? "Таблицы к переносу (" + plan.tables_to_migrate.length + "):" : "Tables to Migrate:"}
|
|
||||||
</h4>
|
|
||||||
<div className="flex flex-wrap gap-1.5">
|
|
||||||
{plan.tables_to_migrate.map((t) => (
|
|
||||||
<span key={t} className="rounded bg-white/5 border border-line px-2 py-0.5 text-[11px] font-mono text-muted">
|
|
||||||
{t}
|
|
||||||
</span>
|
|
||||||
))}
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div className="flex justify-between pt-3 border-t border-line">
|
|
||||||
<Button size="sm" variant="ghost" onClick={() => setStep("scope")}>
|
|
||||||
{locale === "ru" ? "Назад" : "Back"}
|
|
||||||
</Button>
|
|
||||||
<Button size="sm" variant="primary" disabled={executing} onClick={handleExecute} className="bg-ok hover:bg-ok/90 text-white">
|
|
||||||
{executing && <Loader2 className="h-3.5 w-3.5 mr-1.5 animate-spin" />}
|
|
||||||
{locale === "ru" ? "Подтвердить и перенести" : "Start Migration"}
|
|
||||||
</Button>
|
|
||||||
</div>
|
|
||||||
</Card>
|
|
||||||
)}
|
|
||||||
|
|
||||||
{/* STEP 5: EXECUTING */}
|
|
||||||
{step === "executing" && (
|
|
||||||
<Card className="p-8 text-center space-y-4">
|
|
||||||
<Loader2 className="h-8 w-8 text-gold animate-spin mx-auto" />
|
|
||||||
<h3 className="text-base font-bold text-ink">
|
|
||||||
{locale === "ru" ? "Выполняется перенос сервера..." : "Migrating Server Data..."}
|
|
||||||
</h3>
|
|
||||||
<p className="text-xs text-muted max-w-md mx-auto">
|
|
||||||
{locale === "ru"
|
|
||||||
? "Создание резервной копии, перенос персонажей, адаптация таблиц модулей и проверка ссылочной целостности."
|
|
||||||
: "Creating backup, remapping character GUIDs, executing module adapters, and verifying integrity."}
|
|
||||||
</p>
|
|
||||||
</Card>
|
|
||||||
)}
|
|
||||||
|
|
||||||
{/* STEP 6: RESULT */}
|
|
||||||
{step === "result" && execReport && (
|
|
||||||
<Card className="p-6 space-y-5">
|
|
||||||
<div className="flex items-center gap-3">
|
|
||||||
<CheckCircle2 className="h-8 w-8 text-ok shrink-0" />
|
|
||||||
<div>
|
<div>
|
||||||
<h3 className="text-base font-bold text-ink">
|
<h2 className="font-semibold">
|
||||||
{locale === "ru" ? "Перенос сервера успешно завершен!" : "Migration Completed Successfully!"}
|
{info.classic ? t("migrate.classic.title") : info.modular ? t("migrate.modular.title") : t("migrate.none.title")}
|
||||||
</h3>
|
</h2>
|
||||||
<p className="text-xs text-muted">
|
<p className="text-sm text-muted">
|
||||||
{locale === "ru"
|
{info.classic ? t("migrate.classic.text") : info.modular ? t("migrate.modular.text") : t("migrate.none.text")}
|
||||||
? `Все выбранные данные перенесены за ${(execReport.duration_ms / 1000).toFixed(1)} с.`
|
|
||||||
: `All data migrated in ${(execReport.duration_ms / 1000).toFixed(1)}s.`}
|
|
||||||
</p>
|
</p>
|
||||||
|
<p className="selectable mt-1 break-all text-xs text-muted">{info.path}</p>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div className="grid grid-cols-2 gap-3 sm:grid-cols-4">
|
{(info.classic || info.modular) && (
|
||||||
<div className="rounded-lg border border-line bg-card p-3">
|
<dl className="grid grid-cols-2 gap-3 text-sm sm:grid-cols-4">
|
||||||
<span className="text-[11px] text-muted">Аккаунтов</span>
|
<Fact label={t("migrate.fact.version")} value={info.version ?? t("migrate.unknown")} />
|
||||||
<p className="font-mono text-sm font-bold text-ink">{execReport.accounts_transferred}</p>
|
<Fact label={t("migrate.fact.database")} value={t(`migrate.db.${info.database}`)} />
|
||||||
</div>
|
<Fact label={t("migrate.fact.accounts")} value={count(info.accounts)} />
|
||||||
<div className="rounded-lg border border-line bg-card p-3">
|
<Fact label={t("migrate.fact.characters")} value={count(info.characters)} />
|
||||||
<span className="text-[11px] text-muted">Персонажей</span>
|
</dl>
|
||||||
<p className="font-mono text-sm font-bold text-ink">{execReport.characters_transferred}</p>
|
|
||||||
</div>
|
|
||||||
<div className="rounded-lg border border-line bg-card p-3">
|
|
||||||
<span className="text-[11px] text-muted">Модулей адаптировано</span>
|
|
||||||
<p className="font-mono text-sm font-bold text-ok">{execReport.modules_migrated.length}</p>
|
|
||||||
</div>
|
|
||||||
<div className="rounded-lg border border-line bg-card p-3">
|
|
||||||
<span className="text-[11px] text-muted">Таблиц перенесено</span>
|
|
||||||
<p className="font-mono text-sm font-bold text-ink">{execReport.tables_migrated.length}</p>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{execReport.backup_path && (
|
|
||||||
<div className="rounded-lg bg-white/5 border border-line p-3 text-xs text-muted">
|
|
||||||
<p className="font-semibold text-ink">{locale === "ru" ? "Точка восстановления:" : "Restore Point:"}</p>
|
|
||||||
<p className="font-mono text-[11px] break-all">{execReport.backup_path}</p>
|
|
||||||
</div>
|
|
||||||
)}
|
)}
|
||||||
|
|
||||||
<div className="flex justify-end pt-2">
|
{info.classic && info.database === "missing" && (
|
||||||
<Button size="sm" variant="primary" onClick={onClose}>
|
<p className="flex items-start gap-2 text-sm text-bad">
|
||||||
{locale === "ru" ? "Готово" : "Finish"}
|
<AlertTriangle className="mt-0.5 h-4 w-4 shrink-0" aria-hidden /> {t("migrate.db.missingText")}
|
||||||
</Button>
|
</p>
|
||||||
</div>
|
)}
|
||||||
|
|
||||||
|
{info.classic && info.database !== "missing" && (
|
||||||
|
<>
|
||||||
|
<div>
|
||||||
|
<h3 className="flex items-center gap-2 text-sm font-semibold">
|
||||||
|
<Database className="h-4 w-4" aria-hidden /> {t("migrate.copied")}
|
||||||
|
</h3>
|
||||||
|
<ul className="mt-2 list-disc space-y-1 pl-5 text-sm text-muted">
|
||||||
|
<li>
|
||||||
|
{info.schemas.length > 0
|
||||||
|
? t("migrate.copied.schemas", { list: info.schemas.join(", ") })
|
||||||
|
: t("migrate.copied.allSchemas")}
|
||||||
|
</li>
|
||||||
|
<li>{t("migrate.copied.settings", { n: info.config_files.length })}</li>
|
||||||
|
<li>{t("migrate.copied.world")}</li>
|
||||||
|
<li>{t("migrate.copied.ports")}</li>
|
||||||
|
<li>{t("migrate.copied.modules")}</li>
|
||||||
|
{info.extra_worlds.length > 0 && (
|
||||||
|
<li>{t("migrate.copied.worlds", { list: info.extra_worlds.join(", ") })}</li>
|
||||||
|
)}
|
||||||
|
</ul>
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<h3 className="text-sm font-semibold">{t("migrate.notCopied")}</h3>
|
||||||
|
<ul className="mt-2 list-disc space-y-1 pl-5 text-sm text-muted">
|
||||||
|
<li>{t("migrate.notCopied.conf")}</li>
|
||||||
|
<li>{t("migrate.notCopied.merge", { name: props.currentName })}</li>
|
||||||
|
</ul>
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<h3 className="flex items-center gap-2 text-sm font-semibold text-warn">
|
||||||
|
<AlertTriangle className="h-4 w-4" aria-hidden /> {t("migrate.risks")}
|
||||||
|
</h3>
|
||||||
|
<ul className="mt-2 list-disc space-y-1 pl-5 text-sm text-muted">
|
||||||
|
<li>{t("migrate.risk.oldKept")}</li>
|
||||||
|
<li>{t("migrate.risk.ports")}</li>
|
||||||
|
{info.database === "running" ? (
|
||||||
|
<li>{t("migrate.risk.running")}</li>
|
||||||
|
) : (
|
||||||
|
<li>{t("migrate.risk.stopped", { gb: gb(info.database_bytes) })}</li>
|
||||||
|
)}
|
||||||
|
<li>{t("migrate.risk.build")}</li>
|
||||||
|
</ul>
|
||||||
|
</div>
|
||||||
|
<div className="flex justify-end">
|
||||||
|
<Button onClick={() => props.onCopy(info.path)}>
|
||||||
|
{t("migrate.start")} <ArrowRight className="ml-2 h-4 w-4" aria-hidden />
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
</>
|
||||||
|
)}
|
||||||
</Card>
|
</Card>
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function Fact(props: { label: string; value: string }) {
|
||||||
|
return (
|
||||||
|
<div className="rounded-md border border-line p-3">
|
||||||
|
<dt className="text-xs text-muted">{props.label}</dt>
|
||||||
|
<dd className="mt-1 font-mono text-sm">{props.value}</dd>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -46,6 +46,8 @@ export function Shell(props: {
|
|||||||
activeId: string;
|
activeId: string;
|
||||||
onSelect: (id: string) => void;
|
onSelect: (id: string) => void;
|
||||||
onAddAnother: () => void;
|
onAddAnother: () => void;
|
||||||
|
/** Make a modular copy of a classic server (the install screen takes over). */
|
||||||
|
onCopy: (path: string) => void;
|
||||||
onForget: (id: string) => Promise<void>;
|
onForget: (id: string) => Promise<void>;
|
||||||
}) {
|
}) {
|
||||||
const t = useT();
|
const t = useT();
|
||||||
@@ -174,7 +176,7 @@ export function Shell(props: {
|
|||||||
) : page === "players" ? (
|
) : page === "players" ? (
|
||||||
<PlayersPage key={server.id} serverId={server.id} />
|
<PlayersPage key={server.id} serverId={server.id} />
|
||||||
) : page === "migration" ? (
|
) : page === "migration" ? (
|
||||||
<ServerMigrationWizard key={server.id} currentRealmId={server.id} onClose={() => setPage("overview")} />
|
<ServerMigrationWizard key={server.id} servers={props.servers} currentName={server.name} onCopy={props.onCopy} />
|
||||||
) : page === "backups" ? (
|
) : page === "backups" ? (
|
||||||
<BackupsPage key={server.id} serverId={server.id} />
|
<BackupsPage key={server.id} serverId={server.id} />
|
||||||
) : (
|
) : (
|
||||||
|
|||||||
@@ -5,7 +5,7 @@ import os
|
|||||||
ROOT = os.path.join(os.path.dirname(os.path.abspath(__file__)), "..")
|
ROOT = os.path.join(os.path.dirname(os.path.abspath(__file__)), "..")
|
||||||
cats = [("general", "General"), ("population", "Population"), ("login", "Login"), ("roles", "Roles"),
|
cats = [("general", "General"), ("population", "Population"), ("login", "Login"), ("roles", "Roles"),
|
||||||
("openworld", "Open World"), ("quests", "Quests"), ("combat", "Combat"), ("dungeon", "Dungeon Finder"),
|
("openworld", "Open World"), ("quests", "Quests"), ("combat", "Combat"), ("dungeon", "Dungeon Finder"),
|
||||||
("battlegrounds", "Battlegrounds"), ("social", "Social Behavior"), ("advanced", "Advanced")]
|
("scaling", "Bot Strength"), ("battlegrounds", "Battlegrounds"), ("social", "Social Behavior"), ("advanced", "Advanced")]
|
||||||
P = "CoaBots."
|
P = "CoaBots."
|
||||||
# key, type, category, title, description, default, min, max, unit, advanced, dangerous
|
# key, type, category, title, description, default, min, max, unit, advanced, dangerous
|
||||||
R = [
|
R = [
|
||||||
@@ -55,6 +55,17 @@ R = [
|
|||||||
("WorldBrain.QuestSuspendMaxMs", "int", "quests", "Set-aside time (long)", "The longest a quest can stay set aside after repeated failures.", 7200000, 60000, 86400000, "ms", True, False),
|
("WorldBrain.QuestSuspendMaxMs", "int", "quests", "Set-aside time (long)", "The longest a quest can stay set aside after repeated failures.", 7200000, 60000, 86400000, "ms", True, False),
|
||||||
("LfgFill.Enable", "bool", "dungeon", "Dungeon Finder bot fill", "When you queue alone for a dungeon, bots fill the missing tank, healer and damage roles.", True, None, None, None, False, False),
|
("LfgFill.Enable", "bool", "dungeon", "Dungeon Finder bot fill", "When you queue alone for a dungeon, bots fill the missing tank, healer and damage roles.", True, None, None, None, False, False),
|
||||||
("AutoQueueDungeon.Enable", "bool", "dungeon", "Bots queue for dungeons by themselves", "Experimental: idle tank bots queue for a dungeon on their own and the fill above completes the party.", False, None, None, None, True, True),
|
("AutoQueueDungeon.Enable", "bool", "dungeon", "Bots queue for dungeons by themselves", "Experimental: idle tank bots queue for a dungeon on their own and the fill above completes the party.", False, None, None, None, True, True),
|
||||||
|
# Bot strength (mod-coa-playerbots BotScaling.cpp). Multipliers 1 = unchanged; they stack on the content scaling module.
|
||||||
|
("Scaling.Enable", "bool", "scaling", "Help bots in group content", "Applies the multipliers below to bots, their pets and totems. With every multiplier at 1 nothing changes.", True, None, None, None, False, False),
|
||||||
|
("Scaling.Dungeons", "bool", "scaling", "In dungeons", "Apply the multipliers in 5-player dungeons.", True, None, None, None, False, False),
|
||||||
|
("Scaling.Raids", "bool", "scaling", "In raids", "Apply the multipliers in raids.", True, None, None, None, False, False),
|
||||||
|
("Scaling.Battlegrounds", "bool", "scaling", "In battlegrounds and arenas", "Apply the multipliers in battlegrounds and arenas, against creatures only.", False, None, None, None, False, False),
|
||||||
|
("Scaling.World", "bool", "scaling", "In the open world", "Apply the multipliers outside instances.", False, None, None, None, False, False),
|
||||||
|
("Scaling.DamageDone", "float", "scaling", "Bot damage", "Damage bots deal to monsters. 1 is normal, 1.5 is half as much again.", 1.0, 0.1, 10, "x", False, False),
|
||||||
|
("Scaling.HealingDone", "float", "scaling", "Bot healing", "Healing bots cast. 1 is normal.", 1.0, 0.1, 10, "x", False, False),
|
||||||
|
("Scaling.DamageTaken", "float", "scaling", "Damage bots take", "Damage monsters deal to bots. Below 1 bots take less; 0.7 means 30% less.", 1.0, 0.1, 10, "x", False, False),
|
||||||
|
("Scaling.TankThreat", "float", "scaling", "Bot tank threat", "Threat a bot tank generates, so monsters stay on it. 1 is normal.", 1.0, 1, 10, "x", False, False),
|
||||||
|
("Scaling.BossTuning", "bool", "scaling", "Extra help against a few hard bosses", "Stronger multipliers for Loken, Drakkari Elemental, Drakkari Colossus and Gal'darah, which level 60 bots could not beat otherwise.", False, None, None, None, True, False),
|
||||||
("BGFill.Enable", "bool", "battlegrounds", "Battleground bot fill", "When anyone queues for a battleground, both teams are topped up with bots so the match starts at once.", True, None, None, None, False, False),
|
("BGFill.Enable", "bool", "battlegrounds", "Battleground bot fill", "When anyone queues for a battleground, both teams are topped up with bots so the match starts at once.", True, None, None, None, False, False),
|
||||||
("BGFill.TargetPlayersPerTeam", "int", "battlegrounds", "Battleground team size", "Bots per team to fill up to. 0 means a full team for that battleground.", 0, 0, 40, None, False, False),
|
("BGFill.TargetPlayersPerTeam", "int", "battlegrounds", "Battleground team size", "Bots per team to fill up to. 0 means a full team for that battleground.", 0, 0, 40, None, False, False),
|
||||||
("WorldBrain.HelpOthers", "bool", "social", "Bots help nearby players", "A passing bot joins a fight that a friendly player is losing, without taking their loot or credit.", True, None, None, None, False, False),
|
("WorldBrain.HelpOthers", "bool", "social", "Bots help nearby players", "A passing bot joins a fight that a friendly player is losing, without taking their loot or credit.", True, None, None, None, False, False),
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"version": "0.9.9",
|
"version": "0.9.10",
|
||||||
"notes": [
|
"notes": [
|
||||||
"Update and recovery checks use the temporary login port even with a Windows override"
|
"Custom Races patch installation recovers from interrupted downloads"
|
||||||
]
|
]
|
||||||
}
|
}
|
||||||
@@ -1,12 +1,30 @@
|
|||||||
{
|
{
|
||||||
"core": "14cf375f1e006770b330d3fb89201ace54bfca24",
|
"components": {
|
||||||
"bots": "447558bc27d6bb447aaf10eefcb2e85ac2b15c32",
|
"core": {
|
||||||
"squid": "fa4cfd31997367b3e574a2b89b858c4669ff53fb",
|
"repository": "Corfirean/azerothcore-wotlk-coa",
|
||||||
|
"sha": "85ecc2122efd4bc168e750ab35c3e3e8d9c49735"
|
||||||
|
},
|
||||||
|
"upstream": {
|
||||||
|
"repository": "jealous-sound/azerothcore-wotlk-coa",
|
||||||
|
"sha": "f8955cb9b29042c359a938ff732e4b608dd62ea5"
|
||||||
|
},
|
||||||
|
"bots": {
|
||||||
|
"repository": "Corfirean/mod-coa-playerbots",
|
||||||
|
"sha": "0588a8e5cdfe54f81fe47bbb40fc9f75d29662e3"
|
||||||
|
},
|
||||||
|
"scaling": {
|
||||||
|
"repository": "Corfirean/mod-coa-content-scaling",
|
||||||
|
"sha": "3c2febf636bd09087bb278e381b975271a70fdf6"
|
||||||
|
},
|
||||||
|
"build": {
|
||||||
|
"repository": "Corfirean/coa-server-build",
|
||||||
|
"sha": "ccb121b2a050e9f6eae4e5798dbca1c4ee66264f"
|
||||||
|
}
|
||||||
|
},
|
||||||
"notes": [
|
"notes": [
|
||||||
"Server startup waits for ports that Windows is still releasing",
|
"Login server startup works when Windows does not list its listening port",
|
||||||
"Normal Classic dungeons retain their authored damage at full party size",
|
"Updated SQUID's Playerbots to 2.9.4 and refreshed Dungeon Clear",
|
||||||
"Companions avoid repeating unreachable routes in the open world",
|
"Updated SQUID Playerbots to 2.9.4",
|
||||||
"Updated the reviewed CoA upstream snapshot"
|
"Updated the reviewed CoA upstream snapshot"
|
||||||
],
|
]
|
||||||
"dungeon-clear": "9a9d09cf512e0a883af9cda6973445b81c123b13"
|
|
||||||
}
|
}
|
||||||
@@ -1,223 +0,0 @@
|
|||||||
import pathlib
|
|
||||||
import runpy
|
|
||||||
import sys
|
|
||||||
import tempfile
|
|
||||||
import unittest
|
|
||||||
import time
|
|
||||||
from unittest.mock import patch
|
|
||||||
|
|
||||||
BRIDGE = pathlib.Path(__file__).resolve().parents[1] / 'crates/coa-core/src/launcher_bridge.py'
|
|
||||||
|
|
||||||
|
|
||||||
class LauncherBridgeTests(unittest.TestCase):
|
|
||||||
def launch(self, action, body):
|
|
||||||
with tempfile.TemporaryDirectory() as directory:
|
|
||||||
script = pathlib.Path(directory) / 'Scripts/manage.py'
|
|
||||||
script.parent.mkdir()
|
|
||||||
script.write_text(body, encoding='utf8')
|
|
||||||
original = runpy.run_path
|
|
||||||
def capture(*args, **kwargs):
|
|
||||||
self.launcher = original(*args, **kwargs)
|
|
||||||
return self.launcher
|
|
||||||
with patch.object(sys, 'argv', ['bridge', str(script), action]), patch.object(runpy, 'run_path', side_effect=capture):
|
|
||||||
return original(str(BRIDGE))
|
|
||||||
|
|
||||||
def shutdown_fixture(self, *, console_error='RuntimeError', stopped=True, foreign=False, same=True, modern=False, terminate_error=False):
|
|
||||||
return f'''
|
|
||||||
from pathlib import Path
|
|
||||||
from contextlib import nullcontext
|
|
||||||
calls = []
|
|
||||||
world = {{'pid': 123, 'created': 456, 'exe': str(Path(__file__).resolve().parents[1] / {'"foreign.exe"' if foreign else '"Core/worldserver.exe"'})}}
|
|
||||||
def wait_ready(*args): pass
|
|
||||||
def start_mysql(): raise AssertionError('must not start')
|
|
||||||
def main(): raise AssertionError('must not prepare')
|
|
||||||
def settings(): return {{}}
|
|
||||||
def control_lock(): return nullcontext()
|
|
||||||
def process(name): return world if name == 'world' else None
|
|
||||||
def same_process(record): return {same!r}
|
|
||||||
def ra(command, config):
|
|
||||||
calls.append('console')
|
|
||||||
{'raise '+console_error+'("Start this repack worldserver first")' if console_error else 'return "Graceful shutdown"'}
|
|
||||||
def terminate(record):
|
|
||||||
assert record is world
|
|
||||||
calls.append('terminate')
|
|
||||||
{'raise RuntimeError("identity changed")' if terminate_error else 'pass'}
|
|
||||||
def wait_stopped(record, seconds):
|
|
||||||
assert record is world
|
|
||||||
calls.append('wait')
|
|
||||||
return {stopped!r}
|
|
||||||
def stop_all(config):
|
|
||||||
record = process('world')
|
|
||||||
if record:
|
|
||||||
if {modern!r}:
|
|
||||||
try: ra('server shutdown 1s 0', config)
|
|
||||||
except (OSError, RuntimeError): terminate(record)
|
|
||||||
else:
|
|
||||||
ra('server shutdown 1s 0', config)
|
|
||||||
if not wait_stopped(record, 60): raise RuntimeError('world still alive')
|
|
||||||
calls.append('mysql-shutdown')
|
|
||||||
'''
|
|
||||||
|
|
||||||
def test_unavailable_console_in_restored_legacy_launcher_stops_owned_world_before_mysql(self):
|
|
||||||
for error in ['RuntimeError', 'OSError']:
|
|
||||||
with self.subTest(error=error):
|
|
||||||
result = self.launch('stop-all', self.shutdown_fixture(console_error=error))
|
|
||||||
self.assertEqual(result['launcher']['calls'], ['console', 'terminate', 'wait', 'wait', 'mysql-shutdown'])
|
|
||||||
|
|
||||||
def test_force_stop_terminates_only_the_owned_world_before_mysql(self):
|
|
||||||
body = self.shutdown_fixture(console_error=None)
|
|
||||||
body = body.replace("return world if name == 'world' else None", "return world if name == 'world' and 'terminate' not in calls else None")
|
|
||||||
result = self.launch('force-stop-all', body)
|
|
||||||
self.assertEqual(result['launcher']['calls'], ['terminate', 'wait', 'mysql-shutdown'])
|
|
||||||
|
|
||||||
def test_force_stop_rejects_foreign_or_reused_pids_and_a_world_that_stays_alive(self):
|
|
||||||
for options, message in [({'foreign': True}, 'ownership could not be verified'),
|
|
||||||
({'same': False}, 'ownership could not be verified'),
|
|
||||||
({'stopped': False}, 'database was left running')]:
|
|
||||||
with self.subTest(options=options):
|
|
||||||
with self.assertRaisesRegex(Exception, message):
|
|
||||||
self.launch('force-stop-all', self.shutdown_fixture(**options))
|
|
||||||
self.assertNotIn('mysql-shutdown', self.launcher['calls'])
|
|
||||||
|
|
||||||
def test_healthy_console_keeps_graceful_shutdown(self):
|
|
||||||
result = self.launch('stop-all', self.shutdown_fixture(console_error=None))
|
|
||||||
self.assertEqual(result['launcher']['calls'], ['console', 'wait', 'mysql-shutdown'])
|
|
||||||
|
|
||||||
def test_foreign_or_reused_process_is_never_terminated_even_by_a_modern_launcher_catch(self):
|
|
||||||
for modern in [False, True]:
|
|
||||||
for identity in [{'foreign': True}, {'same': False}]:
|
|
||||||
with self.subTest(modern=modern, **identity):
|
|
||||||
with self.assertRaisesRegex(Exception, 'ownership could not be verified'):
|
|
||||||
self.launch('stop-all', self.shutdown_fixture(modern=modern, **identity))
|
|
||||||
self.assertEqual(self.launcher['calls'], ['console'])
|
|
||||||
|
|
||||||
def test_world_that_stays_alive_blocks_database_shutdown(self):
|
|
||||||
for modern in [False, True]:
|
|
||||||
with self.subTest(modern=modern):
|
|
||||||
with self.assertRaisesRegex(Exception, 'database was left running'):
|
|
||||||
self.launch('stop-all', self.shutdown_fixture(stopped=False, modern=modern))
|
|
||||||
self.assertEqual(self.launcher['calls'], ['console', 'terminate', 'wait'])
|
|
||||||
|
|
||||||
def test_termination_identity_failure_leaves_mysql_untouched(self):
|
|
||||||
for modern in [False, True]:
|
|
||||||
with self.subTest(modern=modern):
|
|
||||||
with self.assertRaisesRegex(Exception, 'could not be stopped safely'):
|
|
||||||
self.launch('stop-all', self.shutdown_fixture(terminate_error=True, modern=modern))
|
|
||||||
self.assertEqual(self.launcher['calls'], ['console', 'terminate'])
|
|
||||||
|
|
||||||
def test_slow_mysql_gets_time_to_finish_but_other_waits_are_unchanged(self):
|
|
||||||
result = self.launch('start-mysql', '''
|
|
||||||
calls = []
|
|
||||||
def wait_ready(name, port, seconds=180):
|
|
||||||
calls.append((name, seconds))
|
|
||||||
if name == 'mysql' and seconds < 162:
|
|
||||||
raise RuntimeError('mysql is still starting')
|
|
||||||
def start_mysql():
|
|
||||||
wait_ready('mysql', 12345, 60)
|
|
||||||
def main():
|
|
||||||
start_mysql()
|
|
||||||
wait_ready('world', 23456, 180)
|
|
||||||
wait_ready('mysql', 12345, 900)
|
|
||||||
''')
|
|
||||||
calls = result['launcher']['calls']
|
|
||||||
self.assertEqual(calls[0], ('mysql', 300))
|
|
||||||
self.assertEqual(calls[2], ('mysql', 900))
|
|
||||||
self.assertEqual(calls[1][0], 'world')
|
|
||||||
self.assertAlmostEqual(calls[1][1], 1500, delta=1)
|
|
||||||
|
|
||||||
def world_start(self, *, game_at=420, console_at=480, dies_at=None, requested=180):
|
|
||||||
clock = [0.0]
|
|
||||||
def sleep(seconds): clock[0] += seconds
|
|
||||||
body = f'''
|
|
||||||
import time
|
|
||||||
calls = []
|
|
||||||
dies_at = {dies_at!r}
|
|
||||||
def wait_ready(name, port, seconds=180):
|
|
||||||
until = time.monotonic() + seconds
|
|
||||||
while time.monotonic() < until:
|
|
||||||
if dies_at is not None and time.monotonic() >= dies_at:
|
|
||||||
raise RuntimeError('world stopped during startup')
|
|
||||||
if time.monotonic() >= ({game_at!r} if port == 1 else {console_at!r}):
|
|
||||||
calls.append(port)
|
|
||||||
return
|
|
||||||
time.sleep(0.5)
|
|
||||||
raise RuntimeError('world is still starting')
|
|
||||||
def start_mysql(): pass
|
|
||||||
def settings(): return {{}}
|
|
||||||
def process(name): return {{'pid': 1}}
|
|
||||||
def ra(command, config): return 'server info ready'
|
|
||||||
def main():
|
|
||||||
wait_ready('world', 1, {requested})
|
|
||||||
wait_ready('world', 2, {requested})
|
|
||||||
'''
|
|
||||||
with patch('time.monotonic', side_effect=lambda: clock[0]), patch('time.sleep', side_effect=sleep):
|
|
||||||
result = self.launch('start-all', body)
|
|
||||||
return clock[0], result['launcher']['calls']
|
|
||||||
|
|
||||||
def test_open_ports_do_not_finish_startup_until_commands_are_processed(self):
|
|
||||||
clock = [0.0]
|
|
||||||
def sleep(seconds): clock[0] += seconds
|
|
||||||
body = """
|
|
||||||
import time
|
|
||||||
calls=[]
|
|
||||||
def wait_ready(*args): pass
|
|
||||||
def start_mysql(): pass
|
|
||||||
def settings(): return {}
|
|
||||||
def process(name): return {'pid': 1}
|
|
||||||
def ra(command, config):
|
|
||||||
calls.append(command)
|
|
||||||
if time.monotonic() < 5: raise TimeoutError('main loop is loading')
|
|
||||||
return 'ready'
|
|
||||||
def main():
|
|
||||||
wait_ready('world',1)
|
|
||||||
wait_ready('world',2)
|
|
||||||
"""
|
|
||||||
with patch('time.monotonic', side_effect=lambda: clock[0]), patch('time.sleep', side_effect=sleep):
|
|
||||||
result=self.launch('start-all',body)
|
|
||||||
self.assertEqual(clock[0],5)
|
|
||||||
self.assertEqual(set(result['launcher']['calls']),{'server info'})
|
|
||||||
|
|
||||||
def test_world_death_after_ports_open_is_a_startup_failure(self):
|
|
||||||
body="""
|
|
||||||
def wait_ready(*args): pass
|
|
||||||
def start_mysql(): pass
|
|
||||||
def settings(): return {}
|
|
||||||
def process(name): return None
|
|
||||||
def main(): pass
|
|
||||||
"""
|
|
||||||
with self.assertRaisesRegex(RuntimeError,'stopped before its console accepted'):
|
|
||||||
self.launch('start-world',body)
|
|
||||||
|
|
||||||
def test_legacy_coa_world_waits_for_both_ports_after_three_minutes(self):
|
|
||||||
elapsed, calls = self.world_start()
|
|
||||||
self.assertEqual((elapsed, calls), (480, [1, 2]))
|
|
||||||
|
|
||||||
def test_console_wait_shares_the_world_deadline(self):
|
|
||||||
with self.assertRaisesRegex(RuntimeError, 'still starting'):
|
|
||||||
self.world_start(game_at=1490, console_at=1510)
|
|
||||||
self.assertEqual(self.launcher['calls'], [1])
|
|
||||||
|
|
||||||
def test_world_exit_is_reported_without_waiting_out_the_extended_budget(self):
|
|
||||||
with self.assertRaisesRegex(RuntimeError, 'stopped during startup'):
|
|
||||||
self.world_start(dies_at=12)
|
|
||||||
self.assertEqual(self.launcher['calls'], [])
|
|
||||||
|
|
||||||
def test_existing_longer_world_timeout_is_preserved(self):
|
|
||||||
self.assertEqual(self.world_start(game_at=1600, console_at=1700, requested=1800), (1700, [1, 2]))
|
|
||||||
|
|
||||||
def test_stop_dispatch_does_not_prepare_or_start_anything(self):
|
|
||||||
result = self.launch('stop-all', '''
|
|
||||||
from contextlib import nullcontext
|
|
||||||
calls = []
|
|
||||||
def wait_ready(*args): raise AssertionError('must not wait')
|
|
||||||
def start_mysql(): raise AssertionError('must not start')
|
|
||||||
def main(): raise AssertionError('must not prepare')
|
|
||||||
def settings(): return {'mysqlPort': 12345}
|
|
||||||
def control_lock(): return nullcontext()
|
|
||||||
def stop_all(config): calls.append(config['mysqlPort'])
|
|
||||||
''')
|
|
||||||
self.assertEqual(result['launcher']['calls'], [12345])
|
|
||||||
|
|
||||||
|
|
||||||
if __name__ == '__main__':
|
|
||||||
unittest.main()
|
|
||||||
Reference in new issue
Block a user